基本上我已经有了这个游戏,这些是规则:
-2名玩家;
-玩家 1 从 5x5 网格(矩阵)中选择一个数字,将 0 替换为 1,然后玩家 2 也做同样的事情(他们轮流这样做);
我的问题是,当玩家用他们的数字制作 2x2 网格(示例)或每个数字 0 已被 1 或 2 替换(这使其成为平局)时,如何使其停止:
0 0 0 0 0
0 1 1 2 0
0 1 1 0 0
0 0 0 2 0
0 0 0 0 2
玩家 1 获胜
<小时/>我的代码:
grid= [[0 for row in range (5)] for col in range (5)]
for i in range (0,10): (THIS IS THE PART THAT I NEED TO REPLACE)
player1_row = int (input ("Player 1, please enter the number of the row (0-4): "))
player1_col = int (input ("Player 1, please enter the number of the column (0-4): "))
grid [player1_row][player1_col]= 1
for s in grid:
print(*s)
player2_row = int (input ("Player 2, please enter the number of the row (0-4): "))
player2_col = int (input ("Player 2, please enter the number of the column (0-4): "))
grid [player2_row][player2_col]= 2
for s in grid:
print(*s)
<小时/>
这是我到目前为止的代码:
def check_for_win(grid):
for x in range(4):
for y in range(4):
rect = (grid[x][y], grid[x+1][y], grid[x][y+1], grid[x+1][y+1])
if 0 not in rect and 1 not in rect:
# player 2 won
return 2
if 0 not in rect and 2 not in rect:
# player 1 won
return 1
return None
def check_finished(grid):
for row in grid:
if 0 in row:
return False
return True
grid= [[0 for row in range (5)] for col in range (5)]
for i in range (0,50):
player1_row = int (input ("Player 1, please enter the number of the row (0-4): "))
player1_col = int (input ("Player 1, please enter the number of the column (0-4): "))
grid [player1_row][player1_col]= 1
for s in grid:
print(*s)
player2_row = int (input ("Player 2, please enter the number of the row (0-4): "))
player2_col = int (input ("Player 2, please enter the number of the column (0-4): "))
grid [player2_row][player2_col]= 2
for s in grid:
print(*s)
check_for_win(grid)
check_finished(grid)
这是输出:(它应该停止并说玩家一赢了)
Player 1, please enter the number of the row (0-4): 1
Player 1, please enter the number of the column (0-4): 1
1 1 0 0 0
1 1 0 0 0
0 0 2 0 0
0 0 0 0 2
0 0 0 0 2
Player 2, please enter the number of the row (0-4):
我应该做什么?
最佳答案
您可以编写一个函数来检查其中一名玩家是否获胜,如下所示:
def check_for_win(grid):
for x in range(4):
for y in range(4):
rect = (grid[x][y], grid[x+1][y], grid[x][y+1], grid[x+1][y+1])
if 0 not in rect and 1 not in rect:
# player 2 won
return 2
if 0 not in rect and 2 not in rect:
# player 1 won
return 1
return None
如果玩家 1 获胜,此函数返回 1
;如果玩家 2 获胜,则返回 2
;否则返回 None
。
检查游戏是否完成非常简单:
def check_finished(grid):
for row in grid:
if 0 in row:
return False
return True
这能回答你的问题吗?
关于python - 当玩家在 5x5 网格上画出 2x2 网格时,如何让游戏停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53714269/