我已經編寫了一個nack和cross的遊戲,並使用while循環來運行遊戲。但是,我必須做錯事,因爲當X或O的行/列/對角線出現在板上時,我無法打印出'您贏'或'您輸了'。我知道檢查電路板的功能,因爲我已經自己測試了它,通過手動將X放入電路板中,但通常在玩遊戲時,它完全忽略了3中的任何X或Os。下面是代碼,對不起長。由於Python:while循環中的無序和十字架
import random
board = [
['1','-','-','-'],
['2','-','-','-'],
['3','-','-','-'],
['#','1','2','3'],
[' ',' ',' ',' ']
]
rows = {
'top':
board[0][1:],
'mid':
board[1][1:],
'bottom':
board[2][1:]
}
cols = {
'left':
[board[0][1],
board[1][1],
board[2][1]],
'mid':
[board[0][2],
board[1][2],
board[2][2]],
'right':
[board[0][3],
board[1][3],
board[2][3]]
}
diags = {
'top-bottom':
[board[0][1],
board[1][2],
board[2][3]],
'bottom-top':
[board[2][1],
board[1][2],
board[0][3]]
}
gamestate = 1
def print_board(board):
for i in board:
print " ".join(i)
def win_check(rows,cols,diags):
plrWin = ['X','X','X']
cpuWin = ['O','O','O']
global gamestate
for i in rows.values():
if i == plrWin:
return True
gamestate = 0
elif i == cpuWin:
return False
gamestate = 0
for x in cols.values():
if x == plrWin:
return True
gamestate = 0
elif x == cpuWin:
return False
gamestate = 0
for y in diags.values():
if y == plrWin:
return True
gamestate = 0
elif y == cpuWin:
return False
gamestate = 0
def game_entry():
print "Your turn."
coordY = input("Guess column: ")
coordX = input("Guess row: ")
board[coordX - 1][coordY] = 'X'
def random_location():
while True:
cpuX = random.randint(1,3)
cpuY = random.randint(1,3)
if (board[cpuX - 1][cpuY] == 'X') or (board[cpuX - 1][cpuY] == 'O'):
continue
else:
board[cpuX - 1][cpuY] = 'O'
break
while gamestate == 1:
print_board(board)
game_entry()
random_location()
if win_check(rows,cols,diags) == True:
print "You win!"
gamestate = 0
break
elif win_check(rows,cols,diags) == False:
print "You lose."
gamestate = 0
break
else:
continue
你能縮小它,你所得到的錯誤或者你認爲你是誰? – squiguy 2013-04-11 00:55:01
@squiguy沒有具體的錯誤,它只是不應該如此。當有一行充滿X時,它不會顯示「你贏」並結束程序,它只是繼續前進。 – user2253076 2013-04-11 00:59:46