嗨,我正在制作这个tic tac toe游戏,我看了一些教程,但没有任何游戏可以以平局结束,我试图制作一个,但当平局出现时游戏冻结请不要担心我的芬兰变量和注释
import random
board = [0,1,2,
3,4,5,
6,7,8]
def show():
print board[0], '|',board[1],'|',board[2]
print '----------'
print board[3], '|',board[4],'|',board[5]
print '----------'
print board[6], '|',board[7],'|',board[8]
def checkLine(char, spot1, spot2, spot3):
if (board[spot1] == char) and (board[spot2] == char) and (board [spot3] == char) :
return True
else:
return False
def checkAll(char):
ret = False
if checkLine(char, 0, 1, 2):
ret = True
if checkLine(char, 0,3, 6):
ret = True
if checkLine(char, 1, 4, 7):
ret = True
if checkLine(char, 2, 5, 8):
ret = True
if checkLine(char, 6, 7, 8):
ret = True
if checkLine(char, 3, 4, 5):
ret = True
if checkLine(char, 2, 4, 6):
ret = True
if checkLine(char, 0, 4, 8):
ret = True
return ret
moves = range(9)
numindex = 1
ratkennut = False
while moves:
show()
input = raw_input("Put x: ")
try:
val = int(input)
input = int(input)
except ValueError:
print("Input number!")
input = raw_input("Put x: ")
input = int(input)
if input in moves:
moves.remove(input)
if board [input] != 'x' and board[input] != 'o':
board[input] = 'x'
if checkAll('x') == True:
print "~~ X Won ~~"
ratkennut = True
break;
while moves:
random.seed() #Gives opponents move
opponent = random.choice(moves)
moves.remove(opponent)
if board[opponent] != 'o' and board[opponent] != 'x':
board[opponent] = 'o'
if checkAll('o') == True:
print "~~ O Won ~~"
ratkennut = True
break;
else:
print 'This spot is taken'
else:
print "Tie!"问:这段代码有什么问题,当游戏以平局游戏结束时,它冻结了,我需要ctrl +c如何让它找到平局游戏并打印“平局游戏”我编辑了它,现在它真的很好用!
发布于 2014-03-01 20:08:00
你在while循环中为对手选择的randint移动可能会无限运行,特别是当剩余的有效移动数量变得更少的时候。相反,你应该列出一个有效的移动列表,并对其中的每一个移动进行list.remove():
moves = range(9) 这简化了用户的移动:
if input in moves:
moves.remove(input)对手的动作:
opponent = random.choice(moves)
moves.remove(opponent)并决定游戏的结束:
while moves:
...
else:
print "It's a tie."发布于 2014-03-01 19:21:50
你可以数一下你的走法,在一个井字游戏中只有9步。
你想要这样的东西:
if not checkAll('o') and not checkAll('x') and moves == 9:
print "Tie Game"
breakhttps://stackoverflow.com/questions/22113548
复制相似问题