我用python3创建了一个简单的Tic-Tac-Toe游戏。游戏本身的工作完全是因为它应该,唯一的问题是,我有复位功能没有正确地擦板。它设置值并打印出来,然后在下一次操作中使用旧值
这个问题的关键是,当你选择,是的,你想再玩一次,游戏立即结束,因为它使用的最后板从上一个游戏。我试过几种不同的方法,但结果都一样。这是一个范围问题吗?代码中的一个明显错误。这个问题应该包含在reset()函数中,其他的都在上下文中
#Tic-Tac-Toe Simulator
from random import *
board = [' ']*9
end = 0
abc = ['A', 'B', 'C']
count = 0
action = str
def render():
print('3 ' + board[0] + '|' + board[1] + '|' + board[2])
print(' -----')
print('2 ' + board[3] + '|' + board[4] + '|' + board[5])
print(' -----')
print('1 ' + board[6] + '|' + board[7] + '|' + board[8])
print(' A B C\n')
def winCheck():
print(board)
if board[0] == board[1] == board[2] != ' ':
return board[0]
elif board[3] == board[4] == board[5] != ' ':
return board[3]
elif board[6] == board[7] == board[8] != ' ':
return board[6]
elif board[0] == board[3] == board[6] != ' ':
return board[0]
elif board[1] == board[4] == board[7] != ' ':
return board[1]
elif board[2] == board[5] == board[8] != ' ':
return board[2]
elif board[0] == board[4] == board[8] != ' ':
return board[0]
elif board[2] == board[4] == board[6] != ' ':
return board[2]
else:
return 0
def convert(location):
coords = list(location.upper())
if coords[0] == 'A' and coords[1] == '3':
return 0
if coords[0] == 'A' and coords[1] == '2':
return 3
if coords[0] == 'A' and coords[1] == '1':
return 6
if coords[0] == 'B' and coords[1] == '3':
return 1
if coords[0] == 'B' and coords[1] == '2':
return 4
if coords[0] == 'B' and coords[1] == '1':
return 7
if coords[0] == 'C' and coords[1] == '3':
return 2
if coords[0] == 'C' and coords[1] == '2':
return 5
if coords[0] == 'C' and coords[1] == '1':
return 8
def move(letter, location):
board[convert(location)] = letter.upper()
def spotCheck(location):
if board[convert(location)] == ' ':
return False
else:
return True
def reset():
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
print(board)
end = 0
abc = ['A', 'B', 'C']
count = 0
action = str
def main():
count = 0
letter = str
turn = 'x'
while letter not in ['x', 'o']:
letter = str(input("Would you like to play as 'X' or 'O': ")).lower()
print("Please enter moves in the form of coordinates, such as A2 or C1")
render()
while winCheck() == 0:
if letter == turn:
action = str(input('Enter move: '))
while spotCheck(action) == True:
action = str(input('Space occupied, try again: '))
move(letter, action)
else:
x = randint(0, 2)
y = randint(1, 3)
x = abc[x]
action = x + str(y)
while spotCheck(action) == True:
x = randint(0, 2)
y = randint(1, 3)
x = abc[x]
action = x + str(y)
move(turn, action)
render()
if turn == 'x':
turn = 'o'
else:
turn = 'x'
count = count + 1
if count == 9:
break
if winCheck() == 'X':
print('X has won the game!')
if winCheck() == 'O':
print('O has won the game!')
if winCheck() == 0:
print('The game is a tie!')
main()
if input("Would you like to play again? ").lower() in ['y','yes']:
reset()
main()
您正在创建与全局变量同名的新局部变量。按名称读取变量(如果您没有在函数范围中用相同的名称声明它们)是可行的,如果您想修改它们,请向python“解释”您指的是全局变量:
阅读更多信息:Use of "global" keyword in Python
相关问题 更多 >
编程相关推荐