C语言五子棋小游戏代码
#define _CRT_SECURE_NO_WARNINGS//必须放在第一行
#include <graphics.h> // 引用图形库头文件
#include <conio.h>
#define NUM 15//棋盘大小
#define WIN_NUM 5//五子棋
int pieceArr[NUM][NUM] = { 0 };//记录15*15个棋盘的棋子情况,0表示没有棋子,1表示黑子,2表示白子
/*C标准库,不能画图
* 15*15条边,
* 窗口大小 15*40=600(x) 600(y)
*/
//画线
void Draw_line()
{
setlinecolor(BLUE);
//line(20, 20, 580, 20);
//画竖线
for (int x = 20;x < 600;x += 40)
line(x, 20, x, 580);
//画横线
for (int y = 20;y < 600;y += 40)
line(20, y, 580, y);
}
void Draw_point()//画点
{
setfillcolor(WHITE);
fillcircle(20+(4-1)*40,20+(4-1)*40,5);
fillcircle(20 + (12 - 1) * 40, 20 + (4 - 1) * 40, 5);
fillcircle(20 + (4 - 1) * 40, 20 + (12 - 1) * 40, 5);
fillcircle(20 + (12 - 1) * 40, 20 + (12 - 1) * 40, 5);
fillcircle(20 + (8 - 1) * 40, 20 + (8 - 1) * 40, 5);
}
//black为真
void Draw_piece(bool black,int x, int y)
{
//计算棋盘中的坐标
int i = x / 40;
int j = y / 40;
if (black)//真,黑棋
{
setfillcolor(BLACK);
pieceArr[i][j] = 1;
}
else//白棋
{
setfillcolor(WHITE);
pieceArr[i][j] = 2;
}
fillcircle(20+i*40,20+j*40,15);
}
//这个位置没有其他棋子
bool NicePos(int x, int y)
{
//计算棋子位置
int i = x / 40;
int j = y / 40;
return pieceArr[i][j] == 0;
}
//返回0游戏继续,1黑棋赢,2白棋赢
//只需要判断,刚才的棋子是否为5子即可
//判断它的行,列,45度和135度
int GameOver(int x,int y)
{
x = x / 40;//坐标转换为下标
y = y / 40;
int n = pieceArr[x][y];//得到当前棋子的颜色
if (n == 0)
return 0;
int count = 0;//计数器
int i,j;
//同行的棋子
for (i = x;i >= 0 && pieceArr[i][y] == n;i--)//同行的前面有没有相同
count++;
for (i = x + 1;i < NUM && pieceArr[i][y] == n;i++)//同行的后面有没有相同的
count++;
if (count >= WIN_NUM)
return n;
count = 0;//重新计数,计数器清零
for (j = y;j >= 0 && pieceArr[x][j] == n;j--)//同列的上面
count++;
for (j = y + 1;j < NUM && pieceArr[x][j] == n;j++)//同列的下面
count++;
if (count >= WIN_NUM)
return n;
count = 0;
for (i = x, j = y;i < NUM && j >= 0 && pieceArr[i][j] == n;i++, j--)//右上角
count++;
for (i = x - 1, j = y + 1;i >= 0 && j < NUM && pieceArr[i][j] == n;i--, j++)//左下角
count++;
if (count >= WIN_NUM)
return n;
count = 0;
for (i = x, j = y;i >= 0 && j >= 0 && pieceArr[i][j] == n;i--, j--)//左上角
count++;
for (i = x+1, j = y+1;i <NUM&& j <NUM&& pieceArr[i][j] == n;i++, j++)//右下角
count++;
if (count >= WIN_NUM)
return n;
return 0;
}
int main()
{
initgraph(600, 600);// 绘图窗口初始化
loadimage(NULL, _T("1.png"));// 读取图片至绘图窗口
Draw_line();
Draw_point();
ExMessage m;//鼠标消息
bool black = true;//黑色先手
while (1)
{
m=getmessage(EX_MOUSE);//只返回鼠标消息
if (m.message == WM_LBUTTONDOWN)//左键按下
{
if (NicePos(m.x, m.y))
{
Draw_piece(black, m.x, m.y);
int n = GameOver(m.x,m.y);
if (n == 1)//黑棋赢
{
settextstyle(48, 0, _T("Consolas"));
outtextxy(230,0,_T("黑棋赢"));
break;
}
else if (n == 2)
{
settextstyle(48, 0, _T("Consolas"));
outtextxy(230, 0, _T("白棋赢"));
break;
}
black = !black;
}
}
}
// 按任意键退出
_getch();
closegraph();
return 0;
}
