Pygame五子棋小游戏
Pygame五子棋小游戏

Pygame五子棋小游戏

1、先安装python

2、新建TXT文本,起名为五子棋

3、打开五子棋文本,输入代码

代码部分:

BOARD_SIZE = 15
 
# 初始化棋盘
def init_board():
    return [['·' for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
 
# 打印棋盘
def print_board(board):
    print("   " + " ".join(f"{i:2}" for i in range(BOARD_SIZE)))
    for idx, row in enumerate(board):
        print(f"{idx:2} " + " ".join(row))
 
# 检查是否胜利
def check_win(board, x, y, player):
    directions = [(1, 0), (0, 1), (1, 1), (1, -1)]  # 横、竖、斜、反斜
    for dx, dy in directions:
        count = 1
        for step in range(1, 5):
            nx, ny = x + dx * step, y + dy * step
            if 0 <= nx < BOARD_SIZE and 0 <= ny < BOARD_SIZE and board[ny][nx] == player:
                count += 1
            else:
                break
        for step in range(1, 5):
            nx, ny = x - dx * step, y - dy * step
            if 0 <= nx < BOARD_SIZE and 0 <= ny < BOARD_SIZE and board[ny][nx] == player:
                count += 1
            else:
                break
        if count >= 5:
            return True
    return False
 
# 游戏主循环
def play_game():
    board = init_board()
    current_player = 'X'
    while True:
        print_board(board)
        try:
            move = input(f"玩家 {current_player} 落子(格式:x y): ")
            x_str, y_str = move.strip().split()
            x, y = int(x_str), int(y_str)
            if not (0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE):
                print(" 坐标越界,请重新输入!")
                continue
            if board[y][x] != '·':
                print("该位置已有棋子,请重新选择!")
                continue
        except ValueError:
            print(" 输入格式错误,请按格式输入 x y!")
            continue
 
        board[y][x] = current_player
        if check_win(board, x, y, current_player):
            print_board(board)
            print(f"玩家 {current_player} 获胜!")
            break
        current_player = 'O' if current_player == 'X' else 'X'
 
# 运行游戏
if __name__ == "__main__":
    play_game()

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注