希望有人能理解什么可能是一些非常混乱的代码。我慢慢进入Python在我的空闲时间,并决定做一个井字游戏。你知道吗
问题是,在游戏快结束时,如果人类玩家没有赢,计算机的turn函数就会进入一个无限循环,导致代码崩溃。你知道吗
代码:
import random
board = [[' ',' ',' ',],[' ',' ',' ',],[' ',' ',' ',]]
def printboard():
spacercount = 0
print " | | "
for row in board:
print row[0] + " | " + row[1] + " | " + row[2]
if spacercount < 2:
print "---------------"
print " | | "
spacercount += 1
print "\n"
print "____________________ \n \n"
def userturn():
x = raw_input("Choose row: ")
y = raw_input("Choose column: ")
print "\n"
if board[int(x)][int(y)] == " ":
board[int(x)][int(y)] = "X"
printboard()
if checkwin("X") == True:
print "player has won!"
elif checkfull() == True:
print "it's a tie!"
else:
computerturn()
else:
print "this space is already taken, try again"
userturn()
def computerturn():
x = random.randint(1,2)
y = random.randint(1,2)
print "\n"
if board[int(x)][int(y)] == " ":
board[int(x)][int(y)] = "O"
printboard()
if checkwin("O") == True:
print "computer has won!"
elif checkfull() == True:
print "it's a tie!"
else:
userturn()
else:
computerturn()
def checkwin(le):
return ((board[0][2] == le and board[1][1] == le and board[2][0] == le) or
(board[0][0] == le and board[1][1] == le and board[2][2] == le) or
(board[0][0] == le and board[1][0] == le and board[2][0] == le) or
(board[0][1] == le and board[1][1] == le and board[2][1] == le) or
(board[0][2] == le and board[1][2] == le and board[2][2] == le) or
(board[0][0] == le and board[0][1] == le and board[0][2] == le) or
(board[1][0] == le and board[1][1] == le and board[1][2] == le) or
(board[2][0] == le and board[2][1] == le and board[2][2] == le))
def checkfull():
for x in board:
if x[0] != " " and x[1] != " " and x[2] != " ":
return True
else:
return False
printboard()
userturn()
我一定已经使用了computerturn函数一百次,试图确定无限循环为什么会启动,但都没有成功。你知道吗
非常感谢任何帮助:)希望代码足够简单,不需要注释,但如果是这样,我会添加它们
首先,你的空
board
:单个空格字符表示空正方形。你知道吗
接下来,程序在打印电路板之后要做的第一件事就是调用
userturn()
。用户进行某种移动,如果成功,程序将调用computerturn()
。但是,计算机是如何运行的呢?你知道吗它在电路板的一部分寻找空的方块(不是所有的—只有第二和第三列和行,因为
randint(1,2)
而不是randint(0,2)
)。如果随机选择的方块被占用,计算机会再次尝试。一旦它检查的所有方格都被占用了,它就再也不能做任何事情了,只能再次尝试。然后它将重复执行,直到它被最大递归深度停止。你知道吗我们怎么解决这个问题?我们不会让计算机从整个棋盘中重复选择一个随机的移动,并让它不断尝试直到选择一个有效的移动,而是将其移动限制到实际可用的移动。你知道吗
现在是一个“干净”的版本,删除了注释和过时的代码:
我们hardly even need the comments-您可以从代码本身看到发生了什么。你知道吗
相关问题 更多 >
编程相关推荐