很高兴为您编写一个五子棋的游戏代码。以下是以 GPT-3.5 Turbo 版本回答您的问题的五子棋游戏代码示例:

import numpy as np

# 定义五子棋游戏类
class GomokuGame:
    def __init__(self):
        self.board_size = 15
        self.board = np.zeros((self.board_size, self.board_size), dtype=int)
        self.current_player = 1

    def print_board(self):
        print('  ' + ' '.join(map(str, range(self.board_size))))
        for i in range(self.board_size):
            print(str(i) + ' ' + ' '.join(map(str, self.board[i])))

    def make_move(self, x, y):
        if self.board[x][y] != 0:
            return False
        self.board[x][y] = self.current_player
        return True

    def is_board_full(self):
        return np.count_nonzero(self.board) == self.board_size ** 2

    def check_winner(self):
        for i in range(self.board_size):
            for j in range(self.board_size):
                if self.board[i][j] != 0:
                    if self.check_five_in_row(i, j):
                        return self.board[i][j]
        return 0

    def check_five_in_row(self, x, y):
        directions = [(0, 1), (1, 0), (1, 1), (1, -1)]

        for dx, dy in directions:
            count = 1
            nx, ny = x + dx, y + dy

            while 0 <= nx < self.board_size and 0 <= ny < self.board_size and self.board[nx][ny] == self.board[x][y]:
                count += 1
                nx += dx
                ny += dy

            nx, ny = x - dx, y - dy
            while 0 <= nx < self.board_size and 0 <= ny < self.board_size and self.board[nx][ny] == self.board[x][y]:
                count += 1
                nx -= dx
                ny -= dy

            if count >= 5:
                return True

        return False

# 创建五子棋游戏对象
game = GomokuGame()
game.print_board()

# 游戏循环
while True:
    player = game.current_player
    if player == 1:
        print('轮到玩家1下棋')
    else:
        print('轮到玩家2下棋')

    # 这里是您提供输入的地方
    move = input('请输入您的下棋位置,格式为 'x y':')
    x, y = map(int, move.split())

    # 确保输入位置合法并执行下棋操作
    if x < 0 or x >= game.board_size or y < 0 or y >= game.board_size:
        print('位置无效,请重新输入')
        continue

    if not game.make_move(x, y):
        print('该位置已有棋子,请重新输入')
        continue

    game.print_board()

    winner = game.check_winner()
    if winner != 0:
        if winner == 1:
            print('玩家1获胜!')
        else:
            print('玩家2获胜!')
        break

    if game.is_board_full():
        print('游戏结束,平局!')
        break

    # 切换玩家
    game.current_player = 3 - game.current_player

请注意,这只是一个简单的五子棋游戏代码示例,可能还需要进行更多的优化和完善。希望这对您有所帮助!

五子棋游戏代码:Python 实现

原文地址: https://www.cveoy.top/t/topic/5Fp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录