Tic-tac-toe胜利检测系统-Python

时间:2015-11-30 10:42:22

标签: python tic-tac-toe

我正在python中创建一个Tic-Tac-Toe游戏,我正在努力创建一个模块来检测是否有人赢了。我将两件事传递到模块,董事会和一组获胜组合中:
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

2 个答案:

答案 0 :(得分: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 且无法递增。

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

编辑:关于命名约定的注释,为Classed保留CamelCase。

也是一线解决方案:

# cat /etc/os-release 
NAME="Ubuntu"
VERSION="14.04.3 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.3 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

root@yeni2:/# cat /etc/debian_version 
jessie/sid

答案 1 :(得分:0)

您可以使用python的设置功能轻松确定获胜者。

#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