井字游戏python的GUI逻辑

时间:2020-11-01 14:30:37

标签: python user-interface tkinter tic-tac-toe

我在制作TIC TAC TOE游戏时尝试了我的第一个代码,主要逻辑工作正常。我缺乏用户界面的编码专业知识,任何人都可以帮助我从应用程序中获取行和列o / p以及“ X”或“ O”形式的输入,它们在主要逻辑的帮助下相互切换。 >

这是我的代码:

#below code is for runing python TIC TAC TOE

#Check for result
def check_array(arr):

    for i in range(3):
        set = True
        # print("Checking array value {}".format(arr[i][0]))
        for j in range (1,3):
            # print("Element {0}{1}= {2}".format(i,j,arr[i][j]))
            # print("compared {0} with {1}".format(arr[i][0],arr[i][j]))
            if arr[i][j]==" ":
                set = False
                # print("False")
                break
            if arr[i][0]!=arr[i][j]:
                set = False
                # print("False")
                break
            # print("Value of j = {0} and set = {1}".format(j,set))
        if set==True:
            break
    # print("Checked array horizontaly")
    if set==True:
        print("Horizontal Strike ")
        return 0



    # print("Checking Vertical Strike")
    for i in range(3):
        set = True
        for j in range(1,3):
            # print(arr[0][i],end=" with ")
            # print(arr[j][i])
            if arr[j][i]==" ":
                set = False
                # print("False")
                # print("BREAKING")
                break
            if arr[0][i]!=arr[j][i]:
                set = False
    #             # print("BREAKING")
                break
        if set==True:
            break
    if set==True:
        print("Vertical Strike")
        return 0

    if arr[1][1] == " ":
        set = False
        # print("False")
    elif arr[1][1]==arr[0][0] and arr[1][1]==arr[2][2]:
        set=True
        print("Diagonal Strike")
        return 0
    elif arr[1][1]==arr[2][0] and arr[1][1]==arr[0][2]:
        set=True
        print("Diagonal Strike")
        return 0
    else:
        set=False

#get location of mark
def Get_Loc():
    try:
        i =Get_value()
    except ValueError:
        print("Value Error please enter a int value")
        Get_Loc()
    try:
        j =Get_value()
    except ValueError:
        print("Value Error please enter a int value")
        Get_Loc()
    return i,j

def Get_value():
    value=int(input("Enter value"))
    return value

#check if array is full
def arr_full(arr):
    set=False
    for i in range(3):
        for j in range(3):
            # print("Array[{0},{1}]={2}".format(i,j,arr[i][j]))
            if arr[i][j]==' ':
                # print("RESET")
                set=True
            # print(set)
    if set==False:
        # print(set)
        print("Array is Full")
        return 0

def board(arr):
    print("{0}_|_{1}_|_{2} ".format(arr[0][0],arr[0][1],arr[0][2]))
    print("{0}_|_{1}_|_{2} ".format(arr[1][0],arr[1][1],arr[1][2]))
    print("{0} | {1} | {2} ".format(arr[2][0],arr[2][1],arr[2][2]))

arr=[[" "," "," "],[" "," "," "],[" "," "," "]]
turn=True
player=['X','O']

while True:
    turn = not turn
    print("Player {} turn to play ".format(player[turn]))
    i,j = Get_Loc()
    print("Location value = '{}'".format(arr[i][j]))
    if arr[i][j]!=" ":
        print("Error: Location Full")
        turn = not turn
        continue
    arr[i][j]=player[turn]
    board(arr)
    exit = check_array(arr)
    if exit==0:# or arr_full(arr)==0:
        break

print("Player {} Win".format(player[turn]))

请提及评论以帮助您理解代码

1 个答案:

答案 0 :(得分:0)

起草代码以供参考,

enter image description here

from tkinter import *

class Game():

    def __init__(self):

        # create window
        self.root = Tk()
        self.user = 0
        # creat 3x3 buttons
        self.button = []
        for y in range(3):
            line = []
            for x in range(3):
                bttn = Button(
                    text=' ',
                    width=8,
                    height=4,
                    padx=0,
                    pady=0,
                    command=lambda x0=x, y0=y:self.check(x0, y0)
                )
                bttn.grid(row=y, column=x)
                line.append(bttn)
            self.button.append(line)

        # create text line for status/message
        self.status = Label(text='Player X turn to play', width=24, anchor='w')
        self.status.grid(row=3, column=0, columnspan=3)

        # create button for new game
        self.new = Button(text='New Game', command=self.new)
        self.new.grid(row=4, column=0, columnspan=2)

        # create button for quit
        self.quit = Button(text='Quit', command=self.quit)
        self.quit.grid(row=4, column=2)

    def check(self, x0, y0):
        # callback for all buttons
        print(x0, y0)

        # update button text to "X" or "O"
        text = 'O' if self.user else 'X'
        self.button[y0][x0].configure(text=text)

        # check status
        pass

        # update status
        self.user = 1 - self.user
        text = 'O' if self.user else 'X'
        self.status.configure(text=f'Player {text} turn to play')

    def new(self):
        # restart game
        pass

    def quit(self):
        self.root.destroy()

g = Game()
g.root.mainloop()