Tic Tac Toe Python计划

时间:2015-04-09 13:34:27

标签: python

我正在尝试编写Tic Tac Toe游戏,我不知道如何检查并查看是否有人赢了。我在这个网站上看到了一些答案,但这些答案似乎都不符合我的计划。任何帮助,将不胜感激!!!!

import turtle

t = turtle.Pen()
t.speed(300),t.pu(),t.goto(-150,-150),t.pd()

canvas = turtle.Screen()
canvas.setup(800,400)
canvas.title("Tic Tac Toe")

def square():
    for i in range(0,4):
        t.forward(100)
        t.left(90)

def grid():
    for i in range(0,3):
        square()
        t.forward(100)

grid(),t.pu(),t.goto(-150,-50),t.pd()
grid(),t.pu(),t.goto(-150,50),t.pd()
grid(),t.ht()

def Xs_and_Os(choice, seal):
    t.pu()
    grid_pos = {1:(-100,100), 2:(0,100),  3:(100,100),
                4:(-100,0),   5:(0,0),    6:(100,0),
                7:(-100,-100),8:(0,-100), 9:(100,-100)}
   if choice in grid_pos:
        t.setpos(grid_pos[choice])
        t.pd()
        t.write(seal, font = ("Arial",30,"bold"))

grid_choices = [1,2,3,4,5,6,7,8,9]
while grid_choices != []:
    x = canvas.numinput( "Player 1, choose a grid."," ",9,1)
    while x not in grid_choices:
        x = canvas.numinput("Player 1, choose again."," ",9,1)
    grid_choices.remove(x)
    Xs_and_Os(x,"X")

    y = canvas.numinput("\n" + "Player 2, choose a square.     "," ",9,1)
    while y not in grid_choices:
        y = canvas.numinput("\n" + "Player 2, choose a square.     "," ",9,1)
    grid_choices.remove(y)
    Xs_and_Os(y, "O")

5 个答案:

答案 0 :(得分:1)

要检查某人是否赢了,你需要检查所有可能的胜利条件。在tic-tac-toe中,有8:3水平,3垂直和2对角线。您必须设置一些可以与

比较的值
def check_for_win(entries, player):
    # entries: list grid with X's and O's
    # player: string - 'X' or 'O', whoever's turn it is
    if entries[0] == entries[1] == entries[2] == player or \
        entries[3] == entries[4] == entries[5] == player or \
        entries[6] == entries[7] == entries[8] == player:
        return True

    elif entries[0] == entries[3] == entries[6] == player or \
        entries[1] == entries[4] == entries[7] == player or \
        entries[2] == entries[5] == entries[8] == player:
        return True

    elif entries[0] == entries[4] == entries[8] == player or \
        entries[2] == entries[4] == entries[7] == player:
        return True

    return False

(在您提供的代码中)

....
if choice in grid_pos:
    t.setpos(grid_pos[choice])
    entries[choice-1] = seal  # new
    t.pd()
    t.write(seal, font = ("Arial",30,"bold"))
    if check_for_win(grid_pos, seal):  # new
        has_won(seal)

grid_choices = [1,2,3,4,5,6,7,8,9]
entries = 9*[0]  # new
...
def has_won(player):  # new
    print("Congrats %s's, you have won!" % seal)  # new

当然,就像所有事情一样,这是一种方法(这是我在进行c ++练习时设置我的井字游戏的方法)。我选择使用entries来比较当前的董事会。如果玩家1在单元格4中放置X,则entries[3] = 'X'。然后check_for_win下的if / elif语句只检查8个胜利条件中的一个。 entries[0] == entries[1] == entries[2] == player表示对entries中的第1,第2和第3个索引进行python检查,它们等于任何人。这样,您就不会在空白单元格上获胜!当然,如果没有获胜者,那么return False可以确保游戏进展顺利

干杯! 马特

(评论是否需要更多解释或我输入错误信息)

答案 1 :(得分:1)

# checking for the winner of the tic tac toe game
def check_if_winner(self, tic_tac_toe):

    human = 0
    computer = 0

    # row
    for row in range(self.row):
        count = 0
        for col in range(self.column):
            if tic_tac_toe[row][col] == "x" and tic_tac_toe[row][col] != " ":
                count += 1
            else:
                pass
        if count == self.column:
            human += 1
            return True

    # column

    for col in range(self.column):
        count = 0
        for row in range(self.row):
            if tic_tac_toe[row][col] == "x" and tic_tac_toe[row][col] != " ":
                count += 1

            else:
                pass
            if count == self.column:
                human += 1

                return True

    # diagonal

    count = 0
    for col in range(self.column):
        # count = 0
        for row in range(self.row):
            if row == col and tic_tac_toe[row][col] != " ":
                if tic_tac_toe[row][col] == "x":
                    count += 1
            else:
                pass
            if count == self.column:
                human += 1

                return True

    count = 0
    sum = self.column
    for row in range(self.row):
        for col in range(self.column):
            if (col + row) == (sum - 1) and tic_tac_toe[row][col] != " ":
                if tic_tac_toe[row][col] == "x":
                    count += 1
            else:
                pass
    if count == self.column:
        human += 1

        return True

    # checking for the winner
    if computer or human == 1 and self.total_chances < self.chance:
        if human > computer:
            print("human wins")
        elif computer > human:
            print("computer wins")
        else:
            print("match draw")

答案 2 :(得分:0)

这是我的方式:)还有更多的事情要做

from tkinter import *
from tkinter import ttk
import tkinter.messagebox
polje = []
igrac1 = []
igrac2 = []
i = 0
j = 0
pobjeda = {(1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 5, 9), (3, 5, 7), (1, 4, 7), (3, 6, 9), (2, 5, 8)}


class App:

    def __init__(self, master):

        self.frame1 = Frame(master)
        self.frame1.grid(row=0, columnspan=3)
        self.L1 = Label(master, text="Igrac1")
        self.L1.grid(row=0, column=0)
        self.L2 = Label(master, text="Draw")
        self.L2.grid(row=0, column=1)
        self.L3 = Label(master, text="Igrac2")
        self.L3.grid(row=0, column=2)
        self.frame2 = Frame(master)
        self.frame2.grid(row=1, columnspan=3)
        self.L4 = Label(master, text="#") #broj pobjeda igraca1
        self.L4.grid(row=1, column=0)
        self.L5 = Label(master, text="#")  # broj remija
        self.L5.grid(row=1, column=1)
        self.L6 = Label(master, text="#")  # broj pobjeda igraca2
        self.L6.grid(row=1, column=2)

        self.frame3 = Frame(master)
        self.frame3.grid(row=2, column=0)
        self.c1 = Canvas(self.frame3, width=70, height=70)
        self.c1.bind("<Button-1>", lambda event, args=self.c1: self.IspisX(event, args))
        self.c1.grid(sticky=NW)
        self.c1.create_line(70, 0, 70, 70)
        self.frame4 = Frame(master)
        self.frame4.grid(row=2, column=1)
        self.c2 = Canvas(self.frame4, width=70, height=70)
        self.c2.grid(sticky=NW)
        self.c2.create_line(70, 0, 70, 70)
        self.frame5 = Frame(master)
        self.frame5.grid(row=2, column=2)
        self.c3 = Canvas(self.frame5, width=70, height=70)
        self.c3.grid(sticky=NW)

        self.frame6 = Frame(master)
        self.frame6.grid(row=3, column=0)
        self.c4 = Canvas(self.frame6, width=70, height=70)
        self.c4.grid(sticky=NW)
        self.c4.create_line(1, 1, 69, 1)
        self.c4.create_line(70, 0, 70, 70)
        self.frame7 = Frame(master)
        self.frame7.grid(row=3, column=1)
        self.c5 = Canvas(self.frame7, width=70, height=70)
        self.c5.grid(sticky=NW)
        self.c5.create_line(1, 1, 69, 1)
        self.c5.create_line(70, 0, 70, 70)
        self.frame8 = Frame(master)
        self.frame8.grid(row=3, column=2)
        self.c6 = Canvas(self.frame8, width=70, height=70)
        self.c6.grid(sticky=NW)
        self.c6.create_line(1, 1, 69, 1)

        self.frame9 = Frame(master)
        self.frame9.grid(row=4, column=0)
        self.c7 = Canvas(self.frame9, width=70, height=70)
        self.c7.grid(sticky=NW)
        self.c7.create_line(1, 1, 69, 1)
        self.c7.create_line(70, 0, 70, 70)
        self.frame10 = Frame(master)
        self.frame10.grid(row=4, column=1)
        self.c8 = Canvas(self.frame10, width=70, height=70)
        self.c8.grid(sticky=NW)
        self.c8.create_line(1, 1, 69, 1)
        self.c8.create_line(70, 0, 70, 70)
        self.frame11 = Frame(master)
        self.frame11.grid(row=4, column=2)
        self.c9 = Canvas(self.frame11, width=70, height=70)
        self.c9.grid(sticky=NW)
        self.c9.create_line(1, 1, 69, 1)

    def IspisX(self, event, x):
        if x == self.c1:
            if 1 not in polje:
                x.create_line(10, 10, 60, 60)
                x.create_line(10, 60, 60, 10)
                polje.append(1)
                igrac1.append(1)
                self.Igranje("igrac2")

            else:
                pass
        elif x == self.c2:
            if 2 not in polje:
                x.create_line(10, 10, 60, 60)
                x.create_line(10, 60, 60, 10)
                polje.append(2)
                igrac1.append(2)
                self.Igranje("igrac2")
            else:
                pass
        elif x == self.c3:
            if 3 not in polje:
                x.create_line(10, 10, 60, 60)
                x.create_line(10, 60, 60, 10)
                polje.append(3)
                igrac1.append(3)
                self.Igranje("igrac2")
            else:
                pass
        elif x == self.c4:
            if 4 not in polje:
                x.create_line(10, 10, 60, 60)
                x.create_line(10, 60, 60, 10)
                polje.append(4)
                igrac1.append(4)
                self.Igranje("igrac2")
            else:
                pass
        elif x == self.c5:
            if 5 not in polje:
                x.create_line(10, 10, 60, 60)
                x.create_line(10, 60, 60, 10)
                polje.append(5)
                igrac1.append(5)
                self.Igranje("igrac2")
            else:
                pass
        elif x == self.c6:
            if 6 not in polje:
                x.create_line(10, 10, 60, 60)
                x.create_line(10, 60, 60, 10)
                polje.append(6)
                igrac1.append(6)
                self.Igranje("igrac2")
            else:
                pass
        elif x == self.c7:
            if 7 not in polje:
                x.create_line(10, 10, 60, 60)
                x.create_line(10, 60, 60, 10)
                polje.append(7)
                igrac1.append(7)
                self.Igranje("igrac2")
            else:
                pass
        elif x == self.c8:
            if 8 not in polje:
                x.create_line(10, 10, 60, 60)
                x.create_line(10, 60, 60, 10)
                polje.append(8)
                igrac1.append(8)
                self.Igranje("igrac2")
            else:
                pass
        elif x == self.c9:
            if 9 not in polje:
                x.create_line(10, 10, 60, 60)
                x.create_line(10, 60, 60, 10)
                polje.append(9)
                igrac1.append(9)
                self.Igranje("igrac2")
            else:
                pass


    def IspisO(self, event, x):
        if x == self.c1:
            if 1 not in polje:
                x.create_oval(25, 25, 50, 50)
                polje.append(1)
                igrac2.append(1)
                self.Igranje("igrac1")
            else:
                pass
        elif x == self.c2:
            if 2 not in polje:
                x.create_oval(25, 25, 50, 50)
                polje.append(2)
                igrac2.append(2)
                self.Igranje("igrac1")
            else:
                pass
        elif x == self.c3:
            if 3 not in polje:
                x.create_oval(25, 25, 50, 50)
                polje.append(3)
                igrac2.append(3)
                self.Igranje("igrac1")
            else:
                pass
        elif x == self.c4:
            if 4 not in polje:
                x.create_oval(25, 25, 50, 50)
                polje.append(4)
                igrac2.append(4)
                self.Igranje("igrac1")
            else:
                pass
        elif x == self.c5:
            if 5 not in polje:
                x.create_oval(25, 25, 50, 50)
                polje.append(5)
                igrac2.append(5)
                self.Igranje("igrac1")
            else:
                pass
        elif x == self.c6:
            if 6 not in polje:
                x.create_oval(25, 25, 50, 50)
                polje.append(6)
                igrac2.append(6)
                self.Igranje("igrac1")
            else:
                pass
        elif x == self.c7:
            if 7 not in polje:
                x.create_oval(25, 25, 50, 50)
                polje.append(7)
                igrac2.append(7)
                self.Igranje("igrac1")
            else:
                pass
        elif x == self.c8:
            if 8 not in polje:
                x.create_oval(25, 25, 50, 50)
                polje.append(8)
                igrac2.append(8)
                self.Igranje("igrac1")
            else:
                pass
        elif x == self.c9:
            if 9 not in polje:
                x.create_oval(25, 25, 50, 50)
                polje.append(9)
                igrac2.append(9)
                self.Igranje("igrac1")
            else:
                pass


    def Igranje(self, turn):
        Game = True
        i = 0
        j = 0
        while Game:
            for k in pobjeda:
                x = set(k)
                if x.issubset(set(igrac1)):
                    tkinter.messagebox.showinfo("Izvjestaj", "Pobjedio je igrac 1")


                elif x.issubset(set(igrac2)):
                    tkinter.messagebox.showinfo("Izvjestaj", "Pobjedio je igrac 2")

                elif(len(polje)==9):
                    tkinter.messagebox.showinfo("Izvjestaj", "Partija je zavrsila remijem")
                    polje.append(10)
                    Game = False
                    break
                else:
                    pass
            if(turn == "igrac1"):
                self.c1.bind("<Button-1>", lambda event, args=self.c1: self.IspisX(event, args)) #lambda funkcija je primila dva argumenta event i arg ,a njena zadaca je bila pozvati funckiju ispisX i poslati joj ta dva argumenta
                self.c2.bind("<Button-1>", lambda event, args=self.c2: self.IspisX(event, args))
                self.c3.bind("<Button-1>", lambda event, args=self.c3: self.IspisX(event, args))
                self.c4.bind("<Button-1>", lambda event, args=self.c4: self.IspisX(event, args))
                self.c5.bind("<Button-1>", lambda event, args=self.c5: self.IspisX(event, args))
                self.c6.bind("<Button-1>", lambda event, args=self.c6: self.IspisX(event, args))
                self.c7.bind("<Button-1>", lambda event, args=self.c7: self.IspisX(event, args))
                self.c8.bind("<Button-1>", lambda event, args=self.c8: self.IspisX(event, args))
                self.c9.bind("<Button-1>", lambda event, args=self.c9: self.IspisX(event, args))

                turn = "igrac2"
                i = i+1
                print(i)
                print("i")
                break
            else:
                self.c1.bind("<Button-1>", lambda event, args=self.c1: self.IspisO(event, args))
                self.c2.bind("<Button-1>", lambda event, args=self.c2: self.IspisO(event, args))
                self.c3.bind("<Button-1>", lambda event, args=self.c3: self.IspisO(event, args))
                self.c4.bind("<Button-1>", lambda event, args=self.c4: self.IspisO(event, args))
                self.c5.bind("<Button-1>", lambda event, args=self.c5: self.IspisO(event, args))
                self.c6.bind("<Button-1>", lambda event, args=self.c6: self.IspisO(event, args))
                self.c7.bind("<Button-1>", lambda event, args=self.c7: self.IspisO(event, args))
                self.c8.bind("<Button-1>", lambda event, args=self.c8: self.IspisO(event, args))
                self.c9.bind("<Button-1>", lambda event, args=self.c9: self.IspisO(event, args))

                j = j+1
                print(j)
                print("j")

                turn = "igrac1"
                break
        if len(polje) < 10:
            pass
        else:
            if(len(polje)==9):
                tkinter.messagebox.showinfo("Izvjestaj", "Partija je zavrsila remijem")
                Game = False


root = Tk()
a = App(root)
a.Igranje("igrac1")
root.mainloop()

答案 3 :(得分:0)

您可以尝试以下操作: 在下面找到端到端互动井字棋盘游戏的python代码。 代码看起来很冗长,可以优化,但它可以完美地用作交互式井字棋盘游戏。

#Function code to clear the output space (screen)
 
 from IPython.display import clear_output

#code to display just board-

def ttt_borad(board):
cl = clear_output()
print('Your Tic-Tac-Toe board now:\n')
print(board[1] + "|" + board[2] + "|" + board[3])
print("________")
print(board[4] + "|" + board[5] + "|" + board[6])
print("________")
print(board[7] + "|" + board[8] + "|" + board[9])

#function code to accept player key choices-

def player_key():
player_choice = ''
play1 = ''
play2 = ''
while player_choice not in ('Y', 'N'):
    player_choice = input("Player-1 would like to go first ? Enter Y/N: ")
    player_choice = player_choice.upper()
    if player_choice not in ('Y', 'N'):
        print("Invalid Key")
    else:
        pass
if player_choice == 'Y':

    while play1 not in ('X', 'O'):
        play1 = input("Select your Key for Player-1 X or O: ")
        play1 = play1.upper()
        if play1 not in ('X', 'O'):
            print("Invalid Key")
        else:
            pass
else:
    while play2 not in ('X', 'O'):
        play2 = input("Select your Key for Player-2 X or O: ")
        play2 = play2.upper()
        if play2 not in ('X', 'O'):
            print("Invalid Key")
        else:
            pass

if play1 == 'X':
    play2 = 'O'
elif play1 == 'O':
    play2 = 'X'
elif play2 == 'X':
    play1 = 'O'
elif play2 == 'O':
    play1 = 'X'

print(f'Key for Player-1 is: {play1} and Key for Player-2 is: {play2}')
return play1, play2



#function code to accept key strokes to play game

def enter_key(key, bp):
play1, play2 = key
ind = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
i = 1
while i < 10:
    j = 0
    k = 0
    print(f'Game Move: {i}')
    while j not in ind:
        j = input("Player-1: Select position (1-9) for your Move: ")
        if j not in ind:
            print("Invalid Key or Position already marked")
        else:
            pass
    x = ind.index(j)
    ind.pop(x)
    j = int(j)
    bp[j] = play1
    ttt_borad(bp)
    i = i + 1
    tf = game_winner(key, bp)
    if tf == 1:
        print("The Winner is: Player-1 !!")
        break
    print(f'Game Move: {i}')
    if i == 10:
        break

    while k not in ind:
        k = input("Player-2: Select position (1-9) for your Move: ")
        if k not in ind:
            print("Invalid Key or Position already marked")
        else:
            pass
    y = ind.index(k)
    ind.pop(y)
    k = int(k)
    bp[k] = play2
    ttt_borad(bp)
    i = i + 1
    ft = game_winner(key, bp)
    if ft == 2:
        print("The Winner is: Player-2 !!")
        break
return bp

#function code to calculate and display winner of the game-
def game_winner(key, game):
p1, p2 = key
p = 0
if game[1] == game[2] == game[3] == p1:
    p = 1
    return p
elif game[1] == game[4] == game[7] == p1:
    p = 1
    return p
elif game[1] == game[5] == game[9] == p1:
    p = 1
    return p
elif game[2] == game[5] == game[8] == p1:
    p = 1
    return p
elif game[3] == game[6] == game[9] == p1:
    p = 1
    return p
elif game[4] == game[5] == game[6] == p1:
    p = 1
    return p
elif game[3] == game[5] == game[7] == p1:
    p = 1
    return p
elif game[1] == game[2] == game[3] == p2:
    p = 2
    return p
elif game[1] == game[4] == game[7] == p2:
    p = 2
    return p
elif game[1] == game[5] == game[9] == p2:
    p = 2
    return p
elif game[2] == game[5] == game[8] == p2:
    p = 2
    return p
elif game[3] == game[6] == game[9] == p2:
    p = 2
    return p
elif game[4] == game[5] == game[6] == p2:
    p = 2
    return p
elif game[3] == game[5] == game[7] == p2:
    p = 2
    return p
else:
    p = 3
    return p

#Function code to call all functions in order to start and play game-

def game_play():
clear_output()
entry = ['M', '1', '2', '3', '4', '5', '6', '7', '8', '9']
ttt_borad(entry)
plk = player_key()
new_board = enter_key(plk, entry)
tie = game_winner(plk, new_board)
if tie == 3:
    print("Game Tie !!! :-( ")

#code to continue game (Play game again)

print('Would you like to play again? ')
pa = input("Enter Y to continue OR Enter any other key to exit game: ")
pa = pa.upper()
if pa == 'Y':
    game_play()
else:
    pass

game_play()

#在任何Python3编辑器中尝试整个代码,并让我知道您的反馈。 我已附上示例板代码显示方式。Sample Tic-Tac-Toe board by code

谢谢

答案 4 :(得分:-1)

将单元格条目转换为整数(例如,'O'为1,'X'为-1,空'为0),然后您可以检查8行中每一行的总和。

请参阅以下代码:

def convertToInteger(c):
    if c.upper()=='X':
        return -1
    elif c.upper()=='O':
        return 1
    else:
        return 0

lines = [[0, 1, 2],[3, 4, 5],[6, 7, 8],[0, 3, 6],[1, 4, 7],[2, 5, 8],[0, 4, 8],[2, 4, 6]]
entries =list('x xo xoxo')
entryValues=[convertToInteger(c) for c in entries]
lineValues =[sum(entryValue) for line in lines for entryValue in [[entryValues[j] for j in line]]]
if max(lineValues) == 3:
    print("********  [o] wins!!  ********")
elif min(lineValues) == -3:
    print("********  [x] wins!!  ********")