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

news2024/10/7 16:22:36

在这里插入图片描述

文章目录

    • 下面分别是C语言和Python语言实现五子棋游戏的代码:
    • 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的胜率和智能程度。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/795660.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

华为华三思科 交换机基础配置一览

console密码修改 华为 user-interface console 0 authentication-mode password set authentication password cipher XXXXXXXXX华三 line aux 0 authentication-mode password set auth pass simple XXX思科 en configure terminal line console 0 password 123 login忘记…

打开英雄联盟提示d3dcompiler47.dll缺失怎么修复

1.d3dcompiler_47.dll缺失的原因 损坏的文件&#xff1a;d3dcompiler_47.dll文件可能由于某些原因损坏&#xff0c;如病毒感染、意外删除等。 不兼容的操作系统&#xff1a;某些应用程序要求特定版本的d3dcompiler_47.dll文件&#xff0c;如果操作系统不兼容&#xff0c;则可能…

前端实现导出excel表格(单行表头)

需求&#xff1a;实现勾选行导出为表格 一、安装插件 npm install --save file-saver xlsx运行项目报如下警告的话 运行npm install xlsx0.16.0 --save 来降低版本号&#xff08;最初我安装的版本号是0.18.16的版本&#xff09;再次运行项目就不会报如下警告了 二、新建一个ex…

语音分帧简述

目录 1. 分帧 1.1 非整齐分帧 1.2 整齐分帧 2. 示例代码 1. 分帧 问题1&#xff1a;总帧数如何计算&#xff1f; 记符号N为语音总长度&#xff0c;FRAME_LEN为帧长&#xff0c;OVERLAP_LEN为帧与帧之间的重叠部分&#xff0c;STEP_LEN为帧移(步长)。则总帧数N_Frames计算…

kotlin 编写一个简单的天气预报app(二)

增加界面显示openweathermap返回的信息。 在activity_main.xml里增加输入框来输入城市&#xff0c;在输入款旁边增加搜索按钮来进行查询。 然后原来显示helloworld的TextView用来显示结果。 1. 增加输入城市名字的EditText <EditTextandroid:id"id/editTextCity"…

AcrelEMS企业微电网能效管理平台实现用户侧智能配电和智能用电管理-安科瑞黄安南

摘要&#xff1a;随着科技的发展&#xff0c;电力系统正逐步向智能化、数字化、互联网化迈进。智能配电与智能用电是电力产业发展的重要方向&#xff0c;将为传统电力系统带来革命性的变革。本文将对智能配电和智能用电的概念、特点、关键技术及应用进行详细介绍。 1、智能配电…

Rust vs Go:常用语法对比(八)

题目来自 Golang vs. Rust: Which Programming Language To Choose in 2023?[1] 141. Iterate in sequence over two lists Iterate in sequence over the elements of the list items1 then items2. For each iteration print the element. 依次迭代两个列表 依次迭代列表项1…

【linux基础(一)】Linux基本指令(上)

&#x1f493;博主CSDN主页:杭电码农-NEO&#x1f493;   ⏩专栏分类:Linux从入门到开通⏪   &#x1f69a;代码仓库:NEO的学习日记&#x1f69a;   &#x1f339;关注我&#x1faf5;带你学更多操作系统知识   &#x1f51d;&#x1f51d; 这里写目录标题 1. 前言1. 创…

[vulnhub]DC2

文章目录 [vulnhub]DC2信息收集flag1flag2cewlwpscan flag3什么是rbash&#xff1f; flag4flag5git提权 总结 [vulnhub]DC2 信息收集 扫ip&#xff0c;有两种方式&#xff1a;arp、nmap nmap -sP 192.168.56.0/24 -T4arp-scan -l192.168.56.137 扫端口&#xff1a; nmap -…

1312. 让字符串成为回文串的最少插入次数;971. 翻转二叉树以匹配先序遍历

1312. 让字符串成为回文串的最少插入次数 核心思想&#xff1a;最后的回文串有两种情况&#xff0c;一种是奇数回文串&#xff0c;一种是偶数回文串&#xff0c;奇数回文串的中心一定是原来就有的&#xff0c;偶数回文串的中心也是原来就有的。假设除去中心的部分为q,p,最后要…

Debian12中为python3配置虚拟环境及在Pycharm中使用虚拟环境

在Debian 12中&#xff0c;python默认为python 3.11。 基于应用&#xff0c;现需设置虚拟环境。 1.安装venv模块 从python3.3开始&#xff0c;配置python虚拟环境&#xff0c;可用venv模块&#xff0c;更加方便了。 执行命令&#xff1a; #apt install python3.11-venv 2.…

原型模式——对象的克隆

1、简介 1.1、概述 可以通过一个原型对象克隆出多个一模一样的对象&#xff0c;该模式被称为原型模式。 在使用原型模式时&#xff0c;需要首先创建一个原型对象&#xff0c;再通过复制这个原型对象来创建更多同类型的对象。 1.2、定义 原型模式&#xff08;Prototype Patt…

ICASSP 2023说话人识别方向论文合集(一)

ICASSP (International Conference on Acoustics, Speech and Signal Processing) 即国际声学、语音与信号处理会议&#xff0c;是IEEE主办的全世界最大、最全面的信号处理及其应用方面的顶级会议&#xff0c;在国际上享有盛誉并具有广泛的学术影响力。 今年入选 ICASSP 2023 …

【LeetCode每日一题】——946.验证栈序列

文章目录 一【题目类别】二【题目难度】三【题目编号】四【题目描述】五【题目示例】六【题目提示】七【解题思路】八【时间频度】九【代码实现】十【提交结果】 一【题目类别】 栈 二【题目难度】 中等 三【题目编号】 946.验证栈序列 四【题目描述】 给定 pushed 和 p…

【*1900 图论】CF1328 E

Problem - E - Codeforces 题意&#xff1a; 思路&#xff1a; 注意到题目的性质&#xff1a;满足条件的路径个数是极少的&#xff0c;因为每个点离路径的距离<1 先考虑一条链&#xff0c;那么直接就选最深那个点作为端点即可 为什么&#xff0c;因为我们需要遍历所有点…

ChatGPT伦理挑战:人工智能的权利与责任

&#x1f337;&#x1f341; 博主 libin9iOak带您 Go to New World.✨&#x1f341; &#x1f984; 个人主页——libin9iOak的博客&#x1f390; &#x1f433; 《面试题大全》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33…

选读SQL经典实例笔记13_case与聚合

1. 识别非小计行 1.1. 结果集 1.2. DB2 1.3. Oracle 1.4. 超级聚合&#xff08;supera ggregate&#xff09;值 1.4.1. sql select deptno, job, sum(sal) sal,grouping(deptno) deptno_subtotals,grouping(job) job_subtotalsfrom empgroup by cube(deptno,job) 1.5. SQ…

十三、数据结构——二叉树的遍历(先序、中序和后序)详细思路和代码

二叉树遍历 在数据结构中&#xff0c;二叉树是一种常用且重要的数据结构。二叉树的遍历是指按照一定顺序访问二叉树的所有节点&#xff0c;常见的遍历方式有前序遍历、中序遍历和后序遍历。本文将详细介绍这三种遍历算法&#xff0c;并介绍最优二叉树。 二叉树的基本定义 首…

网络摄像机·监控摄像机用镜头驱动芯片(内置光圈控制)MS41908M

产品简述 MS41908M 是一款用于网络摄像机和监控摄像机的镜头 驱动芯片。 芯片内置光圈控制功能&#xff1b;通过电压驱动方式以及扭矩纹 波修正技术&#xff0c;实现了超低噪声微步驱动。 主要特点  电压驱动方式&#xff0c;256 微步驱动电路&#xff08;两通道&…

同一份数据,Redis为什么要存两次

Redis作为目前最主流的高性能缓存&#xff0c;里面有很多精妙的设计&#xff0c;其中有一种数据类型&#xff0c;当在存储的时候会同时采用两种数据结构来进行分别存储&#xff0c;那么 Redis 为什么要这么做呢&#xff1f;这么做会造成同一份数据占用两倍空间吗&#xff1f; …