python - 如何在 Python 井字游戏中切换两个玩家?
问题描述
我是 Python 的初学者,正在尝试创建井字游戏。但我有两个问题。一个问题是我无法切换这两名球员。另一个问题是我无法打印“你赢了!”字样。我无法找出问题所在。
如果你能给我一个提示,我会很高兴的。先感谢您!!
box = {'1': ' ' , '2': ' ' , '3': ' ' ,'4': ' ' , '5': ' ' , '6': ' ' ,'7': ' ' , '8': ' ' , '9': ' ' }
list = []
for i in box:
list.append(i)
def printbox(box):
print(box['1'] + box['2'] + box['3'])
print(box['4'] + box['5'] + box['6'])
print(box['7'] + box['8'] + box['9'])
#Game setting
def game():
turn = 'O'
count = 0
for i in range(9):
printbox(box)
print("Select the number!")
a = input()
if box[a] == ' ':
box[a] = turn
count += 1
else:
print("Pls select another number.")
continue
if count >= 8:
if box['1'] == box['2'] == box['3']:
printbox(box)
print("You won!")
break
elif box['4'] == box['5'] == box['6']:
printbox(box)
print("You won!")
break
elif box['7'] == box['8'] == box['9']:
printbox(box)
print("You won!")
break
elif box['1'] == box['5'] == box['9']:
printbox(box)
print("You won!")
break
elif box['3'] == box['5'] == box['7']:
printbox(box)
print("You won!")
break
elif box['1'] == box['4'] == box['7']:
printbox(box)
print("You won!")
break
elif box['2'] == box['5'] == box['8']:
printbox(box)
print("You won!")
break
elif box['3'] == box['6'] == box['9']:
printbox(box)
print("You won!")
break
#in case of tie match.
if count == 9:
print("It's a Tie!")
# Changing the two players.
if turn =='O':
turn = 'X'
else:
turn = 'O'
game()
if __name__ == "__main__":
game()
解决方案
所以我坐下来让你的程序为自己工作,并注意到一些问题。所以第一个问题是你检查
if turn == 'O':
转不是'O'它是'0'。您在分配转弯时使用了数字 0,而不是字母“O”。这种比较从来都不是真的。
下一个大问题是你在每场比赛结束时都称“比赛”。所以游戏(1)正常运行,然后你到最后并堆叠一个新的游戏()调用。在这个新的游戏调用中,您将 turn 设置为“0”并计数为 0。
如果您在最后删除对 game() 的调用,这将解决您的堆叠调用问题。
最后,在 game() 更改结束时:
# Changing the two players.
if turn =='o':
turn = 'X'
else:
turn = 'o'
game()
至
# Changing the two players.
if turn =='0':
turn = 'X'
else:
turn = '0'
哦,最后一件事,我会更改if count >= 8
并if count >= 4
添加!= " "
到每个框组合检查,以避免连续 3 个空格“获胜”。
编辑:
既然您更新了上面的代码,那么我想指出修复是从游戏函数本身内部删除对“game()”的调用或减少缩进(因为每次 for 循环运行时都会调用一个新游戏) 如果你想让它“再次播放”。您还需要像我建议的那样更改计数 >= 8 检查或强制玩家至少玩 8 回合,即使他们在 5 中获胜(这是可能的)。
刚才在玩这个脚本时,我确实注意到了另外两个问题。
全局声明框适用于第一场比赛,但在第二场比赛中,它永远不会重置。在 game() 函数内移动框,最后,
这无济于事
list = []
for i in box:
list.append(i)
推荐阅读
- imagemagick - Magick.net 调整 GIF 大小,最终文件更大
- vba - 用户表单关闭时拉取选项按钮值
- keras - 训练和预测时的 Keras 功能智能中心
- c++ - 当我从 cin 读取时,为什么转义字符不起作用?
- php - 动态改变一个div的CSS属性类php
- javascript - React Native - 更新“affectedRows:0”并且删除未定义
- javascript - 网站中的实时流媒体在线编辑器
- scala - 如何在不丢失信息的情况下并行化 spark etl(在文件名中)
- c# - Umbraco 从 7.2.8 更新到 7.12
- excel - 使用 Apache POI 读取 Excel 数据的问题