所以现在我已经编写了一个简单的井字棋游戏。我什至没有使用过我制作的所有功能,但这是我的问题: 我如何确定玩家是否将 1 或 2 放置在已经有 1 的地方,我想我知道该怎么做,但是如果他们输入非法字符或他们尝试覆盖已经放置的 1 或 2。
还有更紧凑的方法吗?
这是游戏的代码:
nr = [0,0,0,0,0,0,0,0,0]
keepGoing = True
def checkP1():
if nr[0] and nr[1] and nr[2] or nr[3] and nr[4] and nr[5] or nr[6] and nr[7] and nr[8] or nr[0] and nr[3] and \
nr[6] or nr[1] and nr[4] and nr[7] or nr[2] and nr[5] and nr[8] or nr[0] and nr[4] and nr[8] or nr[2] and nr[4] and nr[6] == 1:
print("P1 Wins")
keepGoing = False
return keepGoing
def checkP2():
if nr[0] and nr[1] and nr[2] or nr[3] and nr[4] and nr[5] or nr[6] and nr[7] and nr[8] or nr[0] and nr[3] and \
nr[6] or nr[1] and nr[4] and nr[7] or nr[2] and nr[5] and nr[8] or nr[0] and nr[4] and nr[8] or nr[2] and nr[4] and nr[6] == 2:
print("P2 Wins")
keepGoing = False
return keepGoing
def Game():
while keepGoing:
PrintBoard()
in1 = 0
in2 = 0
in1 = input("Please enter the number of the position you want to put your symbol P1.")
nr[int(in1)-1] = 1
check = checkP1()
if check == 0:
PrintBoard()
break
in2 = input("Please enter the number of the position you want to put your symbol P2.")
check = checkP2()
if check == 0:
PrintBoard()
break
nr[int(in2)-1] = 2
def PrintBoard():
print("",nr[0],nr[1],nr[2],"\n",nr[3],nr[4],nr[5],"\n",nr[6],nr[7],nr[8])
def Reset():
nr = [0,0,0,0,0,0,0,0,0]
keepGoing = True
最佳答案
回答您的具体问题
how can I then put them back at the
"Input your number"
prompt if they enter an illegal character or they try to overwrite an already placed1
or2
我会创建一个函数来执行此操作:
def get_valid_input(board):
while True:
try:
move = int(input("Please enter the number of the position you want to put your symbol."))
except ValueError:
print("Input must be an integer number.")
else:
if move not in range(1, 10):
print("Move must be 1-9.")
elif board[move-1] in (1, 2):
print("Location already used.")
else:
return move
这将继续,直到当前进行的玩家给出有效的移动
:
in1 = get_valid_input(nr)
一些更一般的提示:
- 您当前对获胜者的检查不起作用 -
如果 a 或 b == c
没有按照您的想法进行操作(例如,参见 this question )。例如,nr[0]和nr[1]和nr[2] == 2
实际上测试了bool(nr[0])和bool(nr[1])和(nr [2]==2)
;只要最后一个值是 2 并且另外两个值不为零,它就是True
。 CoDEmanX 在评论中的建议在这里很有用。 - 使用标志
keepgoing
不太符合 Python 风格;我会创建一个函数game_over(board)
,如果游戏结束(无论是胜利还是平局),它返回True
,否则返回False
,那么整个循环就变成了while True: ... if game_over(board): break
。 - 不要依赖作用域来访问变量,而是显式传递您需要的内容(例如,将
board
参数传递给get_valid_input
和game_over
)。摆脱keepgoing
会删除您的全局变量之一,但您可以将board
作为其他函数的参数,并根据需要return
。或者,考虑创建一个类
来保存board
和所有功能。
关于Python tic tac toe 检测作弊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23292491/