编程实战班--C语言和Python语言实现五子棋游戏的代码

在这里插入图片描述

下面分别是C语言和Python语言实现五子棋游戏的代码:

C语言实现

在使用C语言实现五子棋游戏时,可以使用SDL2图形库来实现图形界面和图形绘制等功能,同时利用简单的算法实现游戏规则判断和AI对战等功能,具体代码如下:

#include <SDL2/SDL.h>
#include <stdbool.h>

// 屏幕尺寸
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
// 棋盘格子大小
#define CELL_SIZE 40
// 棋盘格子行数、列数
#define ROWS 15
#define COLS 15
// 棋子半径
#define STONE_RADIUS 16

// 五子棋游戏
typedef struct _Game {
    
    
    int board[ROWS][COLS];      // 棋盘
    int currentPlayer;         // 当前玩家:0-黑,1-白
    bool gameIsOver;            // 游戏是否结束
} Game;

// 初始化游戏
void init_game(Game *game)
{
    
    
    int row, col;
    game->currentPlayer = 0;
    game->gameIsOver = false;
    for (row = 0; row < ROWS; row++) {
    
    
        for (col = 0; col < COLS; col++) {
    
    
            game->board[row][col] = -1;
        }
    }
}

// 检查是否有5个棋子连成一条线
bool check_five_in_line(Game *game, int row, int col)
{
    
    
    int stone = game->board[row][col];
    int i, count;

    // 水平线
    count = 0;
    for (i = col - 4; i <= col + 4; i++) {
    
    
        if (i < 0 || i >= COLS) continue;
        if (game->board[row][i] == stone) count++;
        else count = 0;
        if (count >= 5) return true;
    }

    // 垂直线
    count = 0;
    for (i = row - 4; i <= row + 4; i++) {
    
    
        if (i < 0 || i >= ROWS) continue;
        if (game->board[i][col] == stone) count++;
        else count = 0;
        if (count >= 5) return true;
    }

    // 左上到右下的斜线
    count = 0;
    for (i = -4; i <= 4; i++) {
    
    
        int j = row + i, k = col + i;
        if (j < 0 || j >= ROWS || k < 0 || k >= COLS) continue;
        if (game->board[j][k] == stone) count++;
        else count = 0;
        if (count >= 5) return true;
    }

    // 左下到右上的斜线
    count = 0;
    for (i = -4; i <= 4; i++) {
    
    
        int j = row - i, k = col + i;
        if (j < 0 || j >= ROWS || k < 0 || k >= COLS) continue;
        if (game->board[j][k] == stone) count++;
        else count = 0;
        if (count >= 5) return true;
    }

    return false;
}

// 判断是否有一方胜出
bool check_win(Game *game)
{
    
    
    int row, col;
    for (row = 0; row < ROWS; row++) {
    
    
        for (col = 0; col < COLS; col++) {
    
    
            if (game->board[row][col] == -1) continue;
            if (check_five_in_line(game, row, col)) {
    
    
                game->gameIsOver = true;
                return true;
            }
        }
    }
    return false;
}

// 绘制棋盘
void draw_board(SDL_Renderer *renderer)
{
    
    
    int row, col;
    SDL_SetRenderDrawColor(renderer, 239, 218, 186, 255);
    SDL_RenderClear(renderer);
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    for (row = 0; row <= ROWS; row++) {
    
    
        int y = row * CELL_SIZE;
        SDL_RenderDrawLine(renderer, 0, y, SCREEN_WIDTH, y);
    }
    for (col = 0; col <= COLS; col++) {
    
    
        int x = col * CELL_SIZE;
        SDL_RenderDrawLine(renderer, x, 0, x, SCREEN_HEIGHT);
    }
}

// 绘制棋子
void draw_stone(SDL_Renderer *renderer, int row, int col, int player)
{
    
    
    SDL_Rect rect;
    int x = col * CELL_SIZE, y = row * CELL_SIZE;
    rect.x = x - STONE_RADIUS;
    rect.y = y - STONE_RADIUS;
    rect.w = STONE_RADIUS * 2;
    rect.h = STONE_RADIUS * 2;
    SDL_SetRenderDrawColor(renderer, player == 0 ? 0 : 255, 0, 0, 255);
    SDL_RenderFillRect(renderer, &rect);
}

int main(int argc, char *argv[])
{
    
    
    SDL_Window *window = NULL;
    SDL_Renderer *renderer = NULL;
    SDL_Event event;
    Game game;
    int mouseX, mouseY, row, col;
    bool mouseClicked = false, AIEnabled = false;

    // 初始化SDL
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
    
    
        fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError());
        return 1;
    }

    // 创建窗口
    window = SDL_CreateWindow("Five in a Row",
                              SDL_WINDOWPOS_UNDEFINED,
                              SDL_WINDOWPOS_UNDEFINED,
                              SCREEN_WIDTH,
                              SCREEN_HEIGHT,
                              SDL_WINDOW_SHOWN);
    if (window == NULL) {
    
    
        fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    // 创建渲染器
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if (renderer == NULL) {
    
    
        fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 1;
    }

    // 初始化游戏
    init_game(&game);

    // 主循环
    while (!game.gameIsOver) {
    
    
        // 处理事件
        while (SDL_PollEvent(&event)) {
    
    
            switch (event.type) {
    
    
                case SDL_QUIT:
                    game.gameIsOver = true;
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    if (game.currentPlayer == 0 && !AIEnabled) {
    
    
                        mouseClicked = true;
                        mouseX = event.button.x;
                        mouseY = event.button.y;
                    }
                    break;
                default:
                    break;
            }
        }

        // 绘制棋盘
        draw_board(renderer);

        // 绘制棋子
        for (row = 0; row < ROWS; row++) {
    
    
            for (col = 0; col < COLS; col++) {
    
    
                int player = game.board[row][col];
                if (player >= 0) {
    
    
                    draw_stone(renderer, row, col, player);
                }
            }
        }

        // 判断是否有一方胜出
        if (check_win(&game)) {
    
    
            printf("Game Over!\n");
            if (game.currentPlayer == 0) printf("Black wins!\n");
            else printf("White wins!\n");
        }

        // 玩家落子
        if (game.currentPlayer == 0 && mouseClicked) {
    
    
            row = mouseY / CELL_SIZE;
            col = mouseX / CELL_SIZE;
            if (row >= 0 && row < ROWS && col >= 0 && col < COLS) {
    
    
                if (game.board[row][col] == -1) {
    
    
                    game.board[row][col] = 0;
                    game.currentPlayer = 1;
                }
            }
            mouseClicked = false;
        }

        // AI落子
        if (game.currentPlayer == 1 && AIEnabled) {
    
    
            // TODO: AI对战代码
            game.currentPlayer = 0;
        }

        // 显示绘制结果
        SDL_RenderPresent(renderer);
    }

    // 释放资源
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

上述代码实现了五子棋游戏的主要功能,包括绘制棋盘、绘制棋子、检查胜负、玩家落子和AI对战等功能。

Python语言实现

在使用Python语言实现五子棋游戏时,可以使用Python中的Pygame库来实现图形界面和图形绘制等功能,同时也可以利用简单的算法实现游戏规则判断和AI对战等功能,具体代码如下:



import pygame
import random

# 屏幕尺寸
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
# 棋盘格子大小
CELL_SIZE = 40
# 棋盘格子行数、列数
ROWS = 15
COLS = 15
# 棋子半径
STONE_RADIUS = 16

# 五子棋游戏
class Game:
    def __init__(self):
        self.board = [[-1 for i in range(COLS)] for j in range(ROWS)]
        self.currentPlayer = 0  # 0-黑,1-白
        self.gameIsOver = False

    # 检查是否有5个棋子连成一条线
    def check_five_in_line(self, row, col):
        stone = self.board[row][col]
        count = 0
        # 水平线
        for i in range(col - 4, col + 5):
            if i < 0 or i >= COLS:
                continue
            if self.board[row][i] == stone:
                count += 1
            else:
                count = 0
            if count >= 5:
                return True
        # 垂直线
        count = 0
        for i in range(row - 4, row + 5):
            if i < 0 or i >= ROWS:
                continue
            if self.board[i][col] == stone:
                count += 1
            else:
                count = 0
            if count >= 5:
                return True
        # 左上到右下的斜线
        count = 0
        for i in range(-4, 5):
            j, k = row + i, col + i
            if j < 0 or j >= ROWS or k < 0 or k >= COLS:
                continue
            if self.board[j][k] == stone:
                count += 1
            else:
                count = 0
            if count >= 5:
                return True
        # 左下到右上的斜线
        count = 0
        for i in range(-4, 5):
            j, k = row - i, col + i
            if j < 0 or j >= ROWS or k < 0 or k >= COLS:
                continue
            if self.board[j][k] == stone:
                count += 1
            else:
                count = 0
            if count >= 5:
                return True
        return False

    # 判断是否有一方胜出
    def check_win(self):
        for row in range(ROWS):
            for col in range(COLS):
                if self.board[row][col] == -1:
                    continue
                if self.check_five_in_line(row, col):
                    self.gameIsOver = True
                    return True
        return False

# 绘制棋盘
def draw_board(screen):
    for row in range(ROWS):
        for col in range(COLS):
            x, y = col * CELL_SIZE, row * CELL_SIZE
            pygame.draw.rect(screen, (239, 218, 186), (x, y, CELL_SIZE, CELL_SIZE))
            pygame.draw.rect(screen, (0, 0, 0), (x, y, CELL_SIZE, CELL_SIZE), 1)

# 绘制棋子
def draw_stone(screen, row, col, player):
    x, y = col * CELL_SIZE, row * CELL_SIZE
    pygame.draw.circle(screen, (0, 0, 0), (x, y), STONE_RADIUS, 0)
    pygame.draw.circle(screen, (255, 255, 255) if player == 1 else (0, 0, 0), (x, y), STONE_RADIUS - 2, 0)

# AI对战
def play_AI(game):
    empty_cells = [(i, j) for i in range(ROWS) for j in range(COLS) if game.board[i][j] == -1]
    row, col = random.choice(empty_cells)
    game.board[row][col] = 1
    game.currentPlayer = 0

def main():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption('Five in a Row')
    game = Game()

    while not game.gameIsOver:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game.gameIsOver = True
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and game.currentPlayer == 0:
                mouseX, mouseY = pygame.mouse.get_pos()
                row, col = mouseY // CELL_SIZE, mouseX // CELL_SIZE
                if row >= 0 and row < ROWS and col >= 0 and col < COLS:
                    if game.board[row][col] == -1:
                        game.board[row][col] =0 
                        game.currentPlayer = 1

    screen.fill((239, 218, 186))
    draw_board(screen)
    for row in range(ROWS):
        for col in range(COLS):
            player = game.board[row][col]
            if player >= 0:
                draw_stone(screen, row, col, player)

    if game.check_win():
        print('Game Over!')
        if game.currentPlayer == 0:
            print('Black wins!')
        else:
            print('White wins!')

    if game.currentPlayer == 1:
        play_AI(game)

    pygame.display.flip()

pygame.quit()
if name == ‘main’: main()


总结

上述代码使用Pygame库实现了五子棋游戏的主要功能,包括绘制棋盘、绘制棋子、检查胜负、玩家落子和AI对战等功能。 需要注意的是,在AI对战部分,上述代码仅使用了一个随机算法实现,可以通过优化算法来提高AI的胜率和智能程度。

猜你喜欢

转载自blog.csdn.net/AQRSXIAO/article/details/131951443