我不知道如何正确设置转弯。根据我的代码,玩家的单击需要触发计算机的移动。我做到了,人类对人类。下一个代码过分删减,但是我认为我们可以掌握总体思路。
from tkinter import *
import random
root = Tk()
root.title("Tic Tac Toe")
root.resizable(0, 0)
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
def lucky_guess():
#The computer moves randomly
def check_winner():
if board[0] == 'X' and board[1] == 'X' and board[2] == 'X':
print("Player's won. Game over.")
# sys.exit()
# All successful combinations
def set_movement(square, n):
global turn
if board[n] == " " and turn == 'X':
square["text"] = "X"
board[n] = "X"
check_winner()
messages.config(text="Computer's turn")
turn = 'O'
elif turn == 'O':
lucky_guess()
check_winner()
messages.config(text="Player's turn")
turn = 'X'
print(board)
# 9 tiles
tile_6 = Button(root, text="6", bg='gray', fg='white',
height=4, width=8,command=lambda: set_movement(tile_6, 6))
tile_6.grid(row=0, column=0)
#Set turns
choice = random.choice('XO')
beginning = choice, "'s turn."
messages.config(text=beginning)
turn = choice
root.mainloop()
答案 0 :(得分:0)
首先,我建议最终迁移到拥有一个类结构来保持您的游戏状态,这样您就可以避免需要全局变量...但是我们暂时将其保留。
第二,列出的代码不完整,缺少一些重要的变量。
您应该有一种方法或方法来确定轮到人类还是轮到计算机了。在游戏开始(处理您或计算机先行)时以及在切换回合变量之后的每个回合结束时,应调用此方法。如果轮到计算机了,则调用您的方法来拾取计算机的方块并移动计算机。