c++五子棋教程

216 阅读2分钟

1.## 1.下面有完整教程自己看吧(师傅领进门,修行在个人)

#include<stdio.h>
#include<graphics.h>//首先还是要引入头文件

除此之外,还有一些新的与播放音乐相关的头文件如:mmsystem,这是包含多媒体设备接口头文件。

#include<graphics.h>//首先还是要引入头文件
#include<mmsystem.h>//这是包含多媒体设备接口头文件
#pragma comment(lib,"winmm.lib")//加载静态库


```js

2.### 2.完整代码(需要一个图片和音乐素材)

素材:通过网盘分享的文件:五子棋 链接: pan.baidu.com/s/1ePcrq6pD… 提取码: v8fi  --来自百度网盘超级会员v4的分享

`/*******************************

  • 项目名称:五子棋(无禁手版)
  • 开发环境:vs2022 + Easyx
  • 作者:永远爱你的
  • 代码长度:121行
  • 完成时间:2025.1.17
  • 用时:2.5小时 *******************************/

#include<stdio.h> #include<windows.h> #include<graphics.h> #include<mmsystem.h> #pragma comment(lib,"winmm.lib") int Width = 700, Height = 600; int board[18][18] = { 0 };//棋盘数组 int flag = 0;

void InitGame() { initgraph(Width, Height); loadimage(NULL, _T("1.jpg"), Width, Height, true); //播放背景音乐,使用windos自带的多媒体接口 //先打开,在播放 mciSendString("open 1.mp3", 0, 0, 0); mciSendString("play 1.mp3", 0, 0, 0);

setlinecolor(BLACK);
//画格子
for (int i = 70; i <= 500; i += 25) {
    line(5, i, 430, i);
    line(i - 65, 70, i - 65, 495);
}
//加粗边界线
line(431, 70, 431, 495);
line(5, 496, 430, 496);
line(5, 69, 430, 69);
TCHAR s1[] = _T("玩家1:黑棋");
TCHAR s2[] = _T("玩家2:白棋");
//设置文本
outtextxy(480, 80, s1);
outtextxy(480, 120, s2);

}

// 判断是否胜利 int judge(int a, int b) { int directions[4][2] = { {1, 0}, {0, 1}, {1, 1}, {1, -1} }; // 方向:水平、垂直、斜线1、斜线2 for (int dir = 0; dir < 4; dir++) { int count = 1; // 记录当前方向上的棋子数 // 检查正方向 for (int i = 1; i <= 4; i++) { int x = a + i * directions[dir][0]; int y = b + i * directions[dir][1]; if (x < 0 || x > 17 || y < 0 || y > 17 || board[x][y] != board[a][b]) break; count++; } // 检查反方向 for (int i = 1; i <= 4; i++) { int x = a - i * directions[dir][0]; int y = b - i * directions[dir][1]; if (x < 0 || x > 17 || y < 0 || y > 17 || board[x][y] != board[a][b]) break; count++; } if (count >= 5) { return 1; // 五子连珠,胜利 } } return 0; // 没有五子连珠 }

// 下棋落子 void playChess() { int a, b; MOUSEMSG m; HWND hwnd = GetForegroundWindow(); while (1) { m = GetMouseMsg(); if (m.uMsg == WM_LBUTTONDOWN) { //是棋子落在中心点,确定行列位置用/25 a = (m.x + 13) / 25; b = (m.y - 70 + 13) / 25; if (a > 17 || a < 0 || b > 17 || b < 0) { MessageBox(hwnd, "鼠标点击越界", "提示", MB_OK); continue; } if (board[a][b] != 0) { MessageBox(hwnd, "这里已经存在棋子", "提示", MB_OK); continue; } if (flag % 2 == 0) { setfillcolor(BLACK); board[a][b] = 1; } else { setfillcolor(WHITE); board[a][b] = 2; } flag++; solidcircle(a * 25 + 5, b * 25 + 70, 10);

        if (judge(a, b)) {
            if (flag % 2 == 1) {
                MessageBox(hwnd, "玩家一胜利", "提示", MB_OK);
            }
            else {
                MessageBox(hwnd, "玩家二胜利", "提示", MB_OK);
            }
            return;
        }
    }
}

}

int main() { InitGame(); playChess(); while (1); return 0; }`