Python-确定井字游戏赢家 [英] Python - Determine Tic-Tac-Toe Winner

查看:73
本文介绍了Python-确定井字游戏赢家的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写代码,确定井字游戏的赢家. (这是用于大学作业)

I am trying to write a code that determines the winner of a tic-tac-toe game. (This is for a college assignment)

我已经编写了以下函数:

I have written the following function to do so:

此代码仅检查水平线,我没有添加其余部分.我觉得这是需要一些硬编码的东西.

This code only checks for horizontal lines, I haven't added the rest. I feel that this is something that needs a bit of hardcoding.

def iswinner(board, decorator):
    win = True
    for row in range(len(board)):
        for col in range(len(board)):
            if board[row][col] == decorator:
                win = True
            else:
                win = False
                break

其中"board"是大小为n ^ 2的2D数组,"decorator"是"X"或"O"值

Where "board" is a 2D array of size n^2 and "decorator" is the "X" or "O" value

我希望完成的是该函数在2D数组的行中循环.然后循环遍历每一行中的值.如果该元素与"decorator"匹配,则它将继续并检查下一个,但如果不匹配,则它将从第一个循环中断并转到下一行.这样做直到在同一行中找到n个元素.然后它将给出布尔值为True,否则为False.

What I hope to accomplish is that the function loops through the 2D array's rows. Then loops through the values in each row. If that element matches the "decorator" then it continues and checks the next but if it doesn't, then it breaks from the first loop and goes to the next row. It does this until it finds n elements in the same row. Then it would give a bool value of True otherwise False.

该代码似乎没有执行此操作,即使我检查了以下"board",它的输出也为"True"

The code doesn't seem to do that and even when I checked with the following "board" it gave me an output of "True"

check_list = [['O', 'X', 'X'],
              ['O', 'X', 'O'],
              ['O', 'X', 'X']]

非常感谢您!

最好, 塞德

推荐答案

一种方法是创建所有可能的索引组合的集合(生成器函数会更好)来检查获胜.然后遍历这些索引组合,并检查它们是否都包含相同的值,如果是,那么这是一个胜利.

One way to do this would be to create a set (a generator function would be even better) of all the possible index combinations to check for the win. Then loop through those index combinations and check if they all contain the same value, if so, then it's a win.

def win_indexes(n):
    # Rows
    for r in range(n):
        yield [(r, c) for c in range(n)]
    # Columns
    for c in range(n):
        yield [(r, c) for r in range(n)]
    # Diagonal top left to bottom right
    yield [(i, i) for i in range(n)]
    # Diagonal top right to bottom left
    yield [(i, n - 1 - i) for i in range(n)


def is_winner(board, decorator):
    n = len(board)
    for indexes in win_indexes(n):
        if all(board[r][c] == decorator for r, c in indexes):
            return True
    return False

这篇关于Python-确定井字游戏赢家的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆