【问题标题】:Tic-tac-toe win detection system-Python井字游戏中奖检测系统-Python
【发布时间】:2023-03-05 09:57:02
【问题描述】:

我正在用 python 创建一个井字游戏,并且正在努力创建一个模块来检测是否有人获胜。我将 2 件事传递到模块中,即棋盘和一组获胜组合:
win_comb=((0,1,2),(3,4,5),(6,7,8),(6,3,0),(7,4,1),(8,5,2),(6,4,2),(8,4,0))

我用来检查是否有人获胜的模块。在进行 4 次移动后调用该模块。如果有人赢了,那么它应该返回 1,如果有人没有,那么它应该返回 -1。

def Check_Results(Board,win_comb):
    for each in win_comb:
        try:
            if (Board[each[0]] == Board[each[1]] and Board[each[1]]== Board[each[2]] and Board[each[0]]==Board[each[2]]):
                return 1
            else:
                each=each+1
        except:
            pass
        return -1

【问题讨论】:

  • 与问题无关,但请查看PEP8's suggestions for naming conventions。它根本不会改变代码的工作方式,但它使其他人阅读它变得更加容易。 Board -> board, Check_Results -> check_results
  • 你只需要检查每一行(或每一列)和一个对角线。然后,transpose 你的董事会并重复。

标签: python tic-tac-toe


【解决方案1】:

在你的检查中,你只需要两次检查。
由于将隐含第三个相等(如果 a==b 和 b==c 则隐含 a==c)

那么您无需执行each=each+1,因为for 已经为每个获胜组合循环。 最后你的try/except 只会阻止你看到你不能做each+1 因为每个都是tuple 并且不能增加。

def check_Results(board, win_comb):
    for each in win_comb:
        if (board[each[0]] == board[each[1]] and board[each[1]]== board[each[2]]):
            return 1
    return -1

编辑:注意命名约定,为 Classed 保留 CamelCase。

也是一种解决方案:

return any(
    (board[each[0]] == board[each[1]] and board[each[1]]== board[each[2]])
    for each in win_comb)

【讨论】:

  • 您可以将这两个检查合二为一。 a == b == c 作为布尔表达式有效。
【解决方案2】:

您可以使用 python 的 set 功能很容易地确定获胜者。

#Assume pre-defined BOARD_LEN (for instance 3)
Board = [[None for y in range(BOARD_LEN)] for x in range(BOARD_LEN)]

TOKEN_1 = "0"
TOKEN_2 = "X"

"""
Get a sequence of tokens and see which one would win. Examples:
[None,0,x] gives None as winner
[0,0,0] gives 0 as winner
[0,X,0] gives None as winner
"""
def get_winner_of_sequence(seq, TOKEN1, TOKEN2):
  token_set = set(seq)
  if len(token_set) > 1 or None in token_set:
    return None
  return TOKEN1 if TOKEN1 in seq else TOKEN2

"""
Assume a N x N board.
Winning sequences are:
- all rows
- all columns
- the diagonal (0,0 -> N-1,N-1)
"""
def get_possible_winning_sequences(board):
  winning_sequences = []
  #Add each row
  #Add each column
  #Add the diagonal
  return winning_sequences

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多