我是新來的編碼,最近開始學習python。我的第一個挑戰是建立一個tic tac toe遊戲。下面是我的遊戲代碼,除了當我想重新開始遊戲或結束遊戲時,循環不會中斷或遊戲無法啓動,所有的一切都運行正常。任何人都可以弄清楚我的代碼有什麼問題。謝謝!蟒蛇井字問題
Matrix = [[' ' for i in range(3)]for j in range(3)]
for i in Matrix:
print(i) #this is the 3x3 board
def check_done(value): #this is to check if the player has won the game
for a in range(0,3):
if Matrix[0][a]==Matrix[1][a]==Matrix[2][a]==value\
or Matrix[a][0]==Matrix[a][1]==Matrix[a][2]==value:
print ('won')
return True
#when the vertical column or horizontal row is equal, the
player won the game
if Matrix[0][0]==Matrix[1][1]==Matrix[2][2]==value\
or Matrix[2][0]==Matrix[1][1]==Matrix[0][2]==value:
print('won')
return True
#when the diagonal rows are equal, the player won the game
if ' ' not in Matrix[0] and ' ' not in Matrix[1] and ' ' not in
Matrix[2]:
print('draw')
return True
#when every grid is filled in the board and no win criteria is
fulfilled, it is a draw
return False
def replay(): #this is to determine if the player wants to restart or
end the game
command =input('Enter r to restart, or e to end game: ')
while True:
if command == 'r':
player1_input()
if command == 'e':
return
break
else:
print('Invalid command.')
def player1_input(): #this is an input function to allow players to
position their next move
print('Player 1 insert your name here')
name1=input()
print('player 2 insert your name here')
name2=input()
while True:
inputValid = False
while inputValid == False:
print(name1,'please place x coordinates')
xinput=int(input())
print(name1,'please place y coordinates')
yinput=int(input())
if yinput >= 0 & yinput <= 2 & xinput >=0 & xinput <= 2:
if Matrix[yinput][xinput] == ' ':
Matrix[yinput][xinput] = 'X'
for i in Matrix:
print(i)
if check_done('X'):
print(name1,'won')
replay()
inputValid = True
inputValid = False
while inputValid == False:
print(name2,'please place x coordinates')
xinput=int(input())
print(name2,'please place y coordinates')
yinput=int(input())
if yinput >= 0 & yinput <= 2 & xinput >=0 & xinput <= 2:
if Matrix[yinput][xinput] == ' ':
Matrix[yinput][xinput] = 'O'
for i in Matrix:
print(i)
if check_done('O'):
print(name2,'won')
replay()
inputValid = True
return True
請你可以修復你的縮進,以便它準確地表示你正在看什麼?目前這絕對不能運行。此外,你是否能夠將其降低到更小的代碼庫?我認爲有很多代碼可以在不刪除問題的情況下裁剪出來。 – roganjosh
你的第二個'while'循環是無限的...... – Mangohero1
當你詢問重新啓動時輸入'r'時,你的遊戲是否再次要求輸入? –