Xs and Os Referee

井字游戏,有时也被称为“进攻和防守”,是一个两人玩家(X和O)轮流标志着3×3的网格的空间的连珠游戏。最先在任意一条直线(水平线,垂直线或对角线)上成功连接三个标记的一方获胜。
但我们不去玩这个游戏。你将是这个游戏的裁判。你被赋予游戏的结果,以及你必须判断游戏是平局还是有人胜出,以及谁将会成为最后的赢家。如果X玩家获胜,返回“X”。如果O玩家获胜,返回“O”。如果比赛是平局,返回“D”。



游戏的结果是作为字符串形式的列表,其中“X”和“O”是玩家的标志,“.”是空格。

输入: 游戏结果作为字符串形式的列表(Unicode)。

输出: “X”,“O”或“D”作为字符串形式。

解法一:

def checkio(game_result):
    # 横向
    for i in game_result:
        if i.find('XXX') != -1:
            return 'X'
        elif i.find('OOO') != -1:
            return 'O'
    # 纵向
    for j in range(0,3):
        list = []
        for i in range(0,3):
            list.append(game_result[i][j])
        if list[0] == list[1] == list[2] and list[0] != '.':
            return list[0]
    # 对角线
    diagList = [game_result[i][i] for i in range(0,3)]
    if diagList[0] == diagList[1] == diagList[2] and diagList[0] != '.':
        return diagList[0]
    diagList = [game_result[abs(i-2)][i] for i in range(0,3)[::-1]]
    if diagList[0] == diagList[1] == diagList[2] and diagList[0] != '.':
        return diagList[0]
    return 'D'
if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio([
        "X.O",
        "XX.",
        "XOO"]) == "X", "Xs wins"
    assert checkio([
        "OO.",
        "XOX",
        "XOX"]) == "O", "Os wins"
    assert checkio([
        "OOX",
        "XXO",
        "OXX"]) == "D", "Draw"
    assert checkio([
        "O.X",
        "XX.",
        "XOO"]) == "X", "Xs wins again"

解法二:

def checkio(result):
    rows = result
    cols = map(''.join, zip(*rows))
    diags = map(''.join, zip(*[(r[i], r[2 - i]) for i, r in enumerate(rows)]))
    lines = rows + list(cols) + list(diags)
    return 'X' if ('XXX' in lines) else 'O' if ('OOO' in lines) else 'D'

lines将所有的组合归到一起, 最后进行筛选。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值