我正在做一个井字游戏,但是我在做的时候遇到了一些问题
第一个问题是,当我有董事会时:
X | - | X
或者说:
- | X | X
这算是一场胜利,我不知道为什么。如果我说:
X | X | -
这没问题
第二个问题是,我想阻止用户选择一个已经在使用的位置,所以我的想法是将已经选择的位置添加到列表中,并比较它是否已经在其中。问题是,当我第二次调用该函数时,它没有包含previus位置信息的previus列表(它创建了一个新列表),因此它从未检测到用户给出的位置已经在使用中
board = ["-","-","-",
"-","-","-",
"-","-","-"]
def display():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
def turn():
exist=[]
pos = int(input("Choose your position"))
while True:
if pos not in exist:
exist.append(pos)
print(exist)
print("Correct position")
break
else:
print("That position has been selected, choose another one")
board[pos-1] = "X"
display()
def checkwin():
#row
if (board[0] and board[1] and board[2] == "X") or (board[3] and board[4] and board[5] == "X") or (board[6] and board[7] and board[8] == "X"):
print("Victory")
return False
else:
return True
display()
while checkwin():
turn()
checkwin()
print(board)
print("Game has ended")
注意:现在游戏只能有X玩家,我还需要添加O玩家。而且,它只能检测行的赢。我还在做这个
对于第二个问题,您在函数
turn
中声明了您的列表,每当玩家做出选择时都会调用该函数。当函数返回时,其所有局部变量都不再可访问。将其与您的代码进行比较每次调用函数时,也会调用
items = []
。编辑以澄清我的第一句话,函数创建自己的作用域。变量的范围是在程序中可用的位置。比如说(board[0] and board[1] and board[2] == "X")
的逻辑将不起作用,因为您只检查是board[2] == 'X'
,其他的只是真实的,因此'-'
也将计算为True
您应该像这样检查
(board[0] == board[1] == board[2] == "X")
。 这确保所有值都等于'X'
sin Triba明确指出了
turn
函数为何会以这种方式运行至于如何让它正常工作。。。也许我遗漏了一些东西,但是你不想确保你不能选择一个已经被占用的空间吗?为此,你可以直接检查电路板
这将一直询问,直到指定一个空正方形
相关问题 更多 >
编程相关推荐