【问题标题】:How to check for wins in a tic-tac-toe game?如何检查井字游戏中的胜利?
【发布时间】:2021-12-10 04:14:38
【问题描述】:

我的任务是制作井字游戏。网格由 3 行组成。我开发了核心游戏玩法,这很有效,但由于某种原因,我无法检查是否获胜。我在回合结束时有if any(wins_x)if any(wins_o)

row1 = ['-', '-', '-']
row2 = ['-', '-', '-']
row3 = ['-', '-', '-']
table = [row1, row2, row3]

wins_x = [(row1[0] == 'x' and row2[1] == 'x' and row3[2] == 'x'),
          (row3[0] == 'x' and row2[1] == 'x' and row1[2] == 'x'),
          (row1 == ['x', 'x', 'x']),
          (row2 == ['x', 'x', 'x']),
          (row3 == ['x', 'x', 'x']),
          (row1[0] == 'x' and row2[0] == 'x' and row3[0] == 'x'),
          (row1[1] == 'x' and row2[1] == 'x' and row3[1] == 'x'),
          (row1[2] == 'x' and row2[2] == 'x' and row3[2] == 'x')]

wins_o = [(row1[0] == 'o' and row2[1] == 'o' and row3[2] == 'o'),
          (row3[0] == 'o' and row2[1] == 'o' and row1[2] == 'o'),
          (row1 == ['o', 'o', 'o']),
          (row2 == ['o', 'o', 'o']),
          (row3 == ['o', 'o', 'o']),
          (row1[0] == 'o' and row2[0] == 'o' and row3[0] == 'o'),
          (row1[1] == 'o' and row2[1] == 'o' and row3[1] == 'o'),
          (row1[2] == 'o' and row2[2] == 'o' and row3[2] == 'o')]

【问题讨论】:

  • 用调试器试过了吗?
  • wins_xwins_o 中的值决定了列表的创建时间,因此您需要将它们放入创建它们的函数中,并在每次创建时检查它们的值调用。

标签: python any


【解决方案1】:

这应该可行:

def wincheck(table):
  for x in range(0,len(table)):
    if len([y for y in table[x] if y=="x"])==len(table):
      print(f"win x row {x+1}")
    elif len([y for y in table[x] if y=="o"])==len(table):
      print(f"win o row {x+1}")
  for x in range(0,len(table)):
    if len([y for y in table if y[x]=="x"])==len(table):
      print(f"win x Column {x+1}")
    elif len([y for y in table if y[x]=="o"])==len(table):
      print(f"win o Column {x+1}")
  if len([y for y in range(0,len(table)) if table[y][len(table)-1-y] =="x" ])==len(table) or len([y for y in range(0,len(table)) if table[y][y] =="x" ])==len(table):
    print("diagonal win x")
  elif len([y for y in range(0,len(table)) if table[y][len(table)-1-y] =="o" ])==len(table) or len([y for y in range(0,len(table)) if table[y][y] =="o" ])==len(table):
    print("diagonal win o")
wincheck(table)

无论大小如何,它都应该可以工作,但我绝对知道它适用于 3x3。这个函数基本上是检查每一行、每一列和每一对角线,看看里面是否有"o""x"

【讨论】:

  • 没问题。如果您认为值得,请将其标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多