[英]Tkinter - making specific ranges of the window into variables
我正在Tkinter中制作井字游戲,目前可以使用,但是我希望代碼能夠識別單擊窗口中的范圍(例如0、0、200、200),以便可以更改變量。 這樣做的目的是讓游戲在連續出現三個時就知道。 我的問題(如您在第28-29行中看到的,如果self.clicked ...)正在嘗試創建一個變量(或其他解決方案),該變量將使窗口中的框的值為0或1,具體取決於它們已被點擊。 請幫忙。
from tkinter import *
tk = Tk()
width = 600
third = width / 3
canvas = Canvas(width=width, height=width)
tk.title = "Tic Tac Toe"
line1 = canvas.create_line(200, 0, 200, 600)
line2 = canvas.create_line(400, 0, 400, 600)
line3 = canvas.create_line(0, 200, 600, 200)
line4 = canvas.create_line(0, 400, 600, 400)
class XsorOs:
def __init__(self):
self.turn = 0
self.clicked = []
def click(self, row, col):
if (row, col) not in self.clicked:
if self.turn is 0:
canvas.create_line(col * third, row * third, (col + 1) * third, (row + 1) * third)
canvas.create_line((col + 1) * third, row * third, col * third, (row + 1) * third)
self.turn += 1
if self.clicked in range(0, 0, 200, 200):
print('hi')
elif self.turn is 1:
canvas.create_oval(col * third + 5, row * third + 5, (col + 1) * third - 5, (row + 1) * third - 5)
self.turn -= 1
else:
print("Game Over")
self.clicked.append((row, col))
def mouse_click(c, event):
col = int(event.x / third)
row = int(event.y / third)
c.click(row, col)
xo = XsorOs()
canvas.pack()
canvas.bind("<Button-1>", lambda event: mouse_click(xo, event))
canvas.mainloop()
在我弄清楚如何做之前,print hi只是一個占位符。 我希望它成為“使窗口的這一部分成為1(從0開始)”。
我建議使用3x3數組存儲數據,然后使用一些if
語句連續檢測3個數組。 我記得在tkinter中創建井字游戲,這是我使用的方法。
from tkinter import *
tk = Tk()
width = 600
third = width / 3
canvas = Canvas(width=width, height=width)
tk.title = "Tic Tac Toe"
line1 = canvas.create_line(200, 0, 200, 600)
line2 = canvas.create_line(400, 0, 400, 600)
line3 = canvas.create_line(0, 200, 600, 200)
line4 = canvas.create_line(0, 400, 600, 400)
game_board = [['' for x in range(3)] for y in range(3)]
class XsorOs:
def __init__(self):
self.turn = 0
self.clicked = []
def click(self, row, col):
if (row, col) not in self.clicked:
if self.turn % 2 == 0:
canvas.create_line(col * third, row * third, (col + 1) * third, (row + 1) * third)
canvas.create_line((col + 1) * third, row * third, col * third, (row + 1) * third)
self.turn += 1
game_board[row][col] = 'x'
elif self.turn % 2 == 1:
canvas.create_oval(col * third + 5, row * third + 5, (col + 1) * third - 5, (row + 1) * third - 5)
self.turn += 1
game_board[row][col] = 'o'
## add some if statements to detect diagonals, horizontals and verticals in a row.
def mouse_click(c, event):
col = int(event.x / third)
row = int(event.y / third)
c.click(row, col)
xo = XsorOs()
canvas.pack()
canvas.bind("<Button-1>", lambda event: mouse_click(xo, event))
canvas.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.