首页 > 解决方案 > 检查tictactoe游戏是否结束并返回获胜者

问题描述

我正在尝试编写检查tictactoe游戏是否结束并在游戏结束时返回获胜者的函数。你能帮我编码这部分吗?

输入:s,一个 3*3 整数矩阵,描述游戏的当前状态。如果矩阵的元素等于 0 意味着该位置是空的,如果元素等于 1 意味着该位置被“X”玩家占据,如果元素等于 -1 意味着该位置被'O' 球员。

输出:

 e: the result, an integer scalar with value 0, 1 or -1.
            if e = None, the game has not ended yet.
            if e = 0, the game ended with a draw.
            if e = 1, X player won the game.
            if e = -1, O player won the game.

我尝试了一些用户定义的函数来解决这个问题,但无法正确完成。你能帮我编码这部分吗?

[代码]

def check_game(s):
    e = None
    def sum_all_straights(S):
        r3 = np.arange(3)
        return np.concatenate([s.sum(0),s.sum(1),s[[r3,2-r3],r3].sum(1)])

    def winner(S):
        ss = sum_all_straights(S)
        ssa = np.absolute(ss)
        win, = np.where(ssa==3)
        if win.size:
            e = ss[win[0]]//3

        sas = sum_all_straights(np.absolute(S))
        if (sas>ssa).all():
            e = 0
return e            

标签: numpymatrixtic-tac-toe

解决方案


这是一种方法:我们可以通过对每条直线的字段求和来检查获胜者。如果总和中至少有一个是 3 或 -3,则玩家 X 或 O 获胜。

如果没有获胜者,我们将检查平局。如果没有玩家可以获胜,则游戏为平局,即如果每条直线至少有一个 X 和一个 O。我们可以通过首先取棋盘的绝对值然后求和来检测,称之为“SAS”——这计算了每条直线上的筹码,无论它们属于谁——首先求和然后取绝对值,称为“SSA”。如果两个玩家在一条线上都有筹码,那么总和会有所抵消,SSA 将小于 SAS。如果对于每条直线都是如此,则游戏被绘制。

执行:

import numpy as np

def sum_all_straights(S):
    r3 = np.arange(3)
    return np.concatenate([S.sum(0),S.sum(1),S[[r3,2-r3],r3].sum(1)])
#                               ^        ^            ^ 
#                               |        |            |
#                               |         ------------+-----
#                               |                     |     |
#                               |         ------------      |
# This returns the three vertical sums,  |   the three horizontal sums and
# the two diagonal sums, using advanced indexing


def winner(S):
    ss = sum_all_straights(S)
    ssa = np.absolute(ss)
    win, = np.where(ssa==3)
    if win.size:
        return ss[win[0]]//3
    sas = sum_all_straights(np.absolute(S))
    if (sas>ssa).all():
        return 0


examples = b"""
XO.   OOO   ...   XXO
OXO   XX.   .X.   OXX
XXO   OXX   .O.   XOO
"""

examples = np.array(examples.strip().split()).reshape(3,4,1).view("S1").transpose(1,0,2)

examples = 0 + (examples==b'X') - (examples==b'O')
for example in examples:
    print(example,winner(example),"\n")

演示:

[[ 1 -1  0]
 [-1  1 -1]
 [ 1  1 -1]] None 

[[-1 -1 -1]
 [ 1  1  0]
 [-1  1  1]] -1 

[[ 0  0  0]
 [ 0  1  0]
 [ 0 -1  0]] None 

[[ 1  1 -1]
 [-1  1  1]
 [ 1 -1 -1]] 0 

推荐阅读