Noughts and Crosses Tkinter项目

时间:2017-01-24 19:51:49

标签: python python-3.x tkinter

好吧基本上我已经由我的导师设置了一个任务来创建一个基于GUI的Noughts和Crosses的Python游戏而不使用类,到目前为止,这是我想出的。我有一个问题是我怎么能这样做,所以每次轮到它将玩家切换到“X”然后下一个“O”以便他们可以轮流,我尝试了很多方法,但我需要帮助哈哈。 谢谢!

以下是代码:

player = "O"
from tkinter import *

game = Tk()
game.title("Noughts and Crosses")

game.geometry("")

app = Frame(game)
app.grid()

def tl():
    topLeft.configure(text = player)

def tm():
    topMid.configure(text = player)

def tr():
    topRight.configure(text = player)

def ml():
    midLeft.configure(text = player)

def mm():
    midMid.configure(text = player)

def mr():
    midRight.configure(text = player)

def bl():
    botLeft.configure(text = player)

def bm():
    botMid.configure(text = player)

def br():
    botRight.configure(text = player)

#Top Row
topLeft = Button(app, text = "-", activebackground="red", command=tl)
topLeft.grid(row = 0, column = 0, ipadx=20, ipady=18, padx=10, pady=10)

topMid = Button(app, text = "-", activebackground="red", command=tm)
topMid.grid(row = 0, column = 1, ipadx=20, ipady=18, padx=10, pady=10)

topRight = Button(app, text = "-", activebackground="red", command=tr)
topRight.grid(row = 0, column = 2, ipadx=20, ipady=18, padx=10, pady=10)

#Middle Row
midLeft = Button(app, text = "-", activebackground="red", command=ml)
midLeft.grid(row = 1, column = 0, ipadx=20, ipady=18, padx=10, pady=10)

midMid = Button(app, text = "-", activebackground="red", command=mm)
midMid.grid(row = 1, column = 1, ipadx=20, ipady=18, padx=10, pady=10)

midRight = Button(app, text = "-", activebackground="red", command=mr)
midRight.grid(row = 1, column = 2, ipadx=20, ipady=18, padx=10, pady=10)


#Bottom Row
botLeft = Button(app, text = "-", activebackground="red", command=bl)
botLeft.grid(row = 2, column = 0, ipadx=20, ipady=18, padx=10, pady=10)

botMid = Button(app, text = "-", activebackground="red", command=bm)
botMid.grid(row = 2, column = 1, ipadx=20, ipady=18, padx=10, pady=10)

botRight = Button(app, text = "-", activebackground="red", command=br)
botRight.grid(row = 2, column = 2, ipadx=20, ipady=18, padx=10, pady=10)

game.mainloop()

2 个答案:

答案 0 :(得分:1)

创建更改player的功能。在使用global时,必须使用关键字=来通知函数您使用外部/全局变量。如果没有global,它将创建局部变量,并且不会更改外部player

def change_player():
    global player

    if player == 'O':
        player = 'X'
    else:
        player = 'O'

然后在所有功能中使用此功能 - 如下所示:

def tl():
    topLeft.configure(text = player)
    change_player()

顺便说一句:为了使代码更具可读性,请在import之前添加game = Tk(),在for之前添加所有功能。

您可以使用button[0]循环创建所有按钮并将其保留在linst button[1]Button等等。然后您只能创建一个可以分配给所有按钮的函数{ {1}}。 (但是需要lambda来分配带参数的函数)

答案 1 :(得分:0)

x_turn = True

虽然没有game_over:     如果x_turn为'O'

,则转='X'
# Your one-move code goes here

# At the bottom of the loop:
x_turn = not x_turn