井字游戏,检查玩家是否获胜

时间:2020-06-08 04:03:23

标签: python processing tic-tac-toe

我还是OOP编程和编写紧凑代码的新手,所以我可能忽略了一些东西,我试图找到一种方法来检查井字游戏中的垂直胜利和对角胜利,已经是水平的。


如果可能的话,有没有办法将其他两种方式合并到我已经拥有的东西中?

import 'package:gateinn/library/search_choices.dart';

3 个答案:

答案 0 :(得分:5)

您可以添加更多if语句,如下所示:

game_board = [ [0, 0, 0],
               [0, 0, 0],
               [0, 0, 0,] ]

def find_winner():
    for y in range(3):
        if game_board[y][0] == game_board[y][1] == game_board[y][2] != 0: # Check horizontal
            return game_board[y][0]
        if : # Check vertical
            return game_board[0][y]
    if game_board[0][0] == game_board[1][1] == game_board[2][2] != 0 or game_board[0][2] == game_board[1][1] == game_board[2][0] != 0: # Check diagonal
        return game_board[1][1]
    return 0  

答案 1 :(得分:1)

也许有帮助,这是垂直和对角线检查的两个功能

# Checks for vertical row 
def win(game_board, player): 
    for x in range(len(game_board)): 
        win = True

        for y in range(len(game_board)): 
            if game_board[y][x] != player: 
                win = False
                continue

        if win == True: 
            return(win) 
    return(win) 

# Checks diagonal win 
def diag_win(game_board, player): 
    win = True
    y = 0
    for x in range(len(game_board)): 
        if game_board[x, x] != player: 
            win = False
    win = True
    if win: 
        for x in range(len(game_board)): 
            y = len(game_board) - 1 - x 
            if game_board[x, y] != player: 
                win = False
    return win 

如有任何疑问或建议,请随时发表评论。对于上述功能,玩家是随机选择的。使用函数是一个好习惯

答案 2 :(得分:1)

仅3个列表推导

所有胜利和位置

game_board = [ [1, 0, 1],
               [0, 1, 0],
               [0, 1, 0] ]

# Horizontals
h = [str(i+1) + ' Row' for i, v in enumerate(game_board) if sum(v) == 3]

# Verticals
v = [str(i+1) + ' Col' for i in range(3) if sum([j[i] for j in game_board]) == 3]

# Diagonals
d = [['Left Diag', '','Right Diag'][i+1] for i in [-1, 1] if sum([game_board[0][1+i], game_board[1][1]], game_board[2][1-i]) == 3]

if any([h,v,d]):
    print('You won on:', h, v, d)
else:
    print('No win yet')