Python CONNECT 4 CHECK WIN函数

Python connect 4 check win function(Python CONNECT 4 CHECK WIN函数)

本文介绍了Python CONNECT 4 CHECK WIN函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个连接4游戏,在其中您可以选择棋盘的大小。这个游戏对于大多数棋盘大小都能完美地运行,但当棋盘比棋盘宽时,我会遇到问题。我不断得到索引超出范围的错误,我不确定我做错了什么。这就是我目前的支票功能,因为它是唯一有问题的部分。

def checkOWin(board):

    boardHeight = len(board)
    boardWidth = len(board[0])
    tile = 'O'
    # check horizontal spaces
    for y in range(boardHeight):
        for x in range(boardWidth - 3):
            if board[x][y] == tile and board[x+1][y] == tile and board[x+2][y] == tile and board[x+3][y] == tile:
                return True

    # check vertical spaces
    for x in range(boardWidth):
        for y in range(boardHeight - 3):
            if board[x][y] == tile and board[x][y+1] == tile and board[x][y+2] == tile and board[x][y+3] == tile:
                return True

    # check / diagonal spaces
    for x in range(boardWidth - 3):
        for y in range(3, boardHeight):
            if board[x][y] == tile and board[x+1][y-1] == tile and board[x+2][y-2] == tile and board[x+3][y-3] == tile:
                return True

    # check  diagonal spaces
    for x in range(boardWidth - 3):
        for y in range(boardHeight - 3):
            if board[x][y] == tile and board[x+1][y+1] == tile and board[x+2][y+2] == tile and board[x+3][y+3] == tile:
                return True

    return False

如有任何帮助或建议,将不胜感激。提前感谢!

推荐答案

您刚刚混淆了维度,您应该这样设置它们:

def checkOWin(board):
    boardHeight = len(board[0])
    boardWidth = len(board)

因为当您引用board[x]时,这是计算董事会中列表的数量,而当您引用board[x][y]时,只是指董事会中某一特定行的长度。

if board[x][y] == tile and board[x+1][y] == tile and board[x+2][y] == tile and board[x+3][y] == tile:

当我翻转这些值时,函数运行没有错误。

这篇关于Python CONNECT 4 CHECK WIN函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Python CONNECT 4 CHECK WIN函数

基础教程推荐