问题描述
我正在用 Python 编写 Connect4。我的问题是 player_one 和 player_two 的功能似乎不起作用,因此在要求玩家提供输入后,没有棋子掉到棋盘上。我也想知道我在玩家掉落后返回棋盘的代码是否正确;我怀疑我目前的代码没有返回更新了玩家棋子的棋盘,但我是新的,我不知道该怎么做。
请看!
def field(field):
for w in range(14):
if w % 2 == 0:
usable_w = int(w/2)
for h in range(15):
if h % 2 == 0:
usable_h = int(h/2)
if h != 14:
print(field[usable_h][usable_w],end="")
else:
print(" ")
else:
print("|",end="")
else:
print("_"*13)
PlayField = [[" "," "," "],[" "," "]]
field(PlayField)
def player_one(field):
MoveColumn = int(input("Enter the column 1 - 7\n"))
MoveRow = 6
for row in PlayField:
if MoveColumn >= 1 and MoveColumn <= 7:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = "X"
break
MoveRow -= 1
return field(PlayField)
else:
print("Column outside range,please enter valid move")
def player_two(field):
MoveColumn = int(input("Enter the column 1 - 7\n"))
MoveRow = 6
for row in PlayField:
if MoveColumn >= 1 and MoveColumn <= 7:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = "O"
break
MoveRow -= 1
return field(PlayField)
else:
print("Column outside range,please enter valid move")
def launch_play():
while True:
Player = 1
print("Player's turn",Player)
player_one(field)
player_two(field)
launch_play()
解决方法
好吧,您的 player_...
函数包含合适的语句,但顺序不合适;并且由于它们对全局 PlayField
进行操作,因此返回它毫无意义。除此之外,它有两个几乎相同的功能是丑陋的。一种重新排列的变体,其中玩家一和玩家二之间的唯一区别作为参数传递(而不是无用的 field
),如您所料:
def player(xo):
while (MoveColumn := int(input("Enter the column 1 - 7\n"))) < 1 or \
MoveColumn > 7:
print("Column outside range,please enter valid move")
MoveRow = 6
for row in PlayField:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = xo
field(PlayField)
break
MoveRow -= 1
在您的 launch_play
循环中,您现在可以调用
player('X')
player('O')
现在由您通过检查游戏何时结束来完成程序。
,我想出了两个解决方案(在你修改代码之前)来防止玩家轮到改变,但都行不通:
def player(xo):
while MoveColumn := int(input("Enter the column 1 - 7\n")):
MoveRow = 6
for row in PlayField:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = xo
field(PlayField)
break
Return True
MoveRow -= 1
else:
print("Column outside range,please enter valid move")
Return False
def launch_play():
while True:
Player = 'X'
print("Player's turn",Player)
player('X')
Player = '0'
print("Player's turn",Player)
player('0')
launch_play()
另一种解决方案是在播放器函数中引入播放器变量(也没有用):
def player(xo):
while MoveColumn := int(input("Enter the column 1 - 7\n")):
MoveRow = 6
Player = 'X'
for row in PlayField:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = xo
field(PlayField)
break
MoveRow -= 1
Player = '0'
else:
print("Column outside range,please enter valid move")