五子棋程序代码

合集下载

五子棋代码

五子棋代码

#include <stdio.h>#include"bios.h"#include <ctype.h>#include <conio.h>#include <dos.h>#define CROSSRU 0xbf /*右上角点*/#define CROSSLU 0xda /*左上角点*/#define CROSSLD 0xc0 /*左下角点*/#define CROSSRD 0xd9 /*右下角点*/#define CROSSL 0xc3 /*左边*/#define CROSSR 0xb4 /*右边*/#define CROSSU 0xc2 /*上边*/#define CROSSD 0xc1 /*下边*/#define CROSS 0xc5 /*十字交叉点*//*定义棋盘左上角点在屏幕上的位置*/#define MAPXOFT 5#define MAPYOFT 2/*定义1号玩家的操作键键码*/#define PLAY1UP 0x1157/*上移--'W'*/#define PLAY1DOWN 0x1f53/*下移--'S'*/#define PLAY1LEFT 0x1e41/*左移--'A'*/#define PLAY1RIGHT 0x2044/*右移--'D'*/#define PLAY1DO 0x3920/*落子--空格键*//*定义2号玩家的操作键键码*/#define PLAY2UP 0x4800/*上移--方向键up*/#define PLAY2DOWN 0x5000/*下移--方向键down*/ #define PLAY2LEFT 0x4b00/*左移--方向键left*/#define PLAY2RIGHT 0x4d00/*右移--方向键right*/ #define PLAY2DO 0x1c0d/*落子--回车键Enter*//*若想在游戏中途退出, 可按Esc 键*/#define ESCAPE 0x011b/*定义棋盘上交叉点的状态, 即该点有无棋子*//*若有棋子, 还应能指出是哪个玩家的棋子*/#define CHESSNULL 0 /*没有棋子*/#define CHESS1 'O'/*一号玩家的棋子*/#define CHESS2 'X'/*二号玩家的棋子*//*定义按键类别*/#define KEYEXIT 0/*退出键*/#define KEYFALLCHESS 1/*落子键*/#define KEYMOVECURSOR 2/*光标移动键*/#define KEYINVALID 3/*无效键*//*定义符号常量: 真, 假--- 真为1, 假为0 */#define TRUE 1#define FALSE 0/**********************************************************//* 定义数据结构*//*棋盘交叉点坐标的数据结构*/struct point{int x,y;};/**********************************************************//*自定义函数原型说明*/void Init(void);int GetKey(void);int CheckKey(int press);int ChangeOrder(void);int ChessGo(int Order,struct point Cursor);void DoError(void);void DoOK(void);void DoWin(int Order);void MoveCursor(int Order,int press);void DrawCross(int x,int y);void DrawMap(void);int JudgeWin(int Order,struct point Cursor);int JudgeWinLine(int Order,struct point Cursor,int direction); void ShowOrderMsg(int Order);void EndGame(void);/**********************************************************//**********************************************************//* 定义全局变量*/int gPlayOrder; /*指示当前行棋方*/struct point gCursor; /*光标在棋盘上的位置*/char gChessBoard[19][19];/*用于记录棋盘上各点的状态*/ /**********************************************************//**********************************************************//*主函数*/void main(){int press;int bOutWhile=FALSE;/*退出循环标志*/Init();/*初始化图象,数据*/while(1){press=GetKey();/*获取用户的按键值*/switch(CheckKey(press))/*判断按键类别*/{/*是退出键*/case KEYEXIT:clrscr();/*清屏*/bOutWhile = TRUE;break;/*是落子键*/case KEYFALLCHESS:if(ChessGo(gPlayOrder,gCursor)==FALSE)/*走棋*/ DoError();/*落子错误*/else{DoOK();/*落子正确*//*如果当前行棋方赢棋*/if(JudgeWin(gPlayOrder,gCursor)==TRUE){DoWin(gPlayOrder);bOutWhile = TRUE;/*退出循环标志置为真*/}/*否则*/else/*交换行棋方*/ChangeOrder();ShowOrderMsg(gPlayOrder);}break;/*是光标移动键*/case KEYMOVECURSOR:MoveCursor(gPlayOrder,press);break;/*是无效键*/case KEYINVALID:break;}if(bOutWhile==TRUE)break;}/*游戏结束*/EndGame();}/**********************************************************//*界面初始化,数据初始化*/void Init(void){int i,j;char *Msg[]={"Player1 key:"," UP----w"," DOWN--s"," LEFT--a"," RIGHT-d"," DO----space","","Player2 key:"," UP----up"," DOWN--down"," LEFT--left"," RIGHT-right"," DO----ENTER","","exit game:"," ESC",NULL,};/* 先手方为1号玩家*/gPlayOrder = CHESS1;/* 棋盘数据清零, 即棋盘上各点开始的时候都没有棋子*/ for(i=0;i<19;i++)for(j=0;j<19;j++)gChessBoard[i][j]=CHESSNULL;/*光标初始位置*/gCursor.x=gCursor.y=0;/*画棋盘*/textmode(C40);DrawMap();/*显示操作键说明*/i=0;textcolor(BROWN);while(Msg[i]!=NULL){gotoxy(25,3+i);cputs(Msg[i]);i++;}/*显示当前行棋方*/ShowOrderMsg(gPlayOrder);/*光标移至棋盘的左上角点处*/gotoxy(gCursor.x+MAPXOFT,gCursor.y+MAPYOFT);}/*画棋盘*/void DrawMap(void){int i,j;clrscr();for(i=0;i<19;i++)for(j=0;j<19;j++)DrawCross(i,j);}/*画棋盘上的交叉点*/void DrawCross(int x,int y){gotoxy(x+MAPXOFT,y+MAPYOFT); /*交叉点上是一号玩家的棋子*/if(gChessBoard[x][y]==CHESS1) {textcolor(LIGHTBLUE);putch(CHESS1);return;}/*交叉点上是二号玩家的棋子*/if(gChessBoard[x][y]==CHESS2) {textcolor(LIGHTRED);putch(CHESS2);return;}textcolor(GREEN);/*左上角交叉点*/if(x==0&&y==0){putch(CROSSLU);return;}/*左下角交叉点*/if(x==0&&y==18){putch(CROSSLD);return;}/*右上角交叉点*/if(x==18&&y==0)putch(CROSSRU); return;}/*右下角交叉点*/if(x==18&&y==18) {putch(CROSSRD); return;}/*左边界交叉点*/if(x==0){putch(CROSSL); return;}/*右边界交叉点*/if(x==18){putch(CROSSR); return;}/*上边界交叉点*/if(y==0){putch(CROSSU); return;}/*下边界交叉点*/if(y==18){putch(CROSSD); return;}/*棋盘中间的交叉点*/ putch(CROSS);/*交换行棋方*/int ChangeOrder(void){if(gPlayOrder==CHESS1)gPlayOrder=CHESS2;elsegPlayOrder=CHESS1;return(gPlayOrder);}/*获取按键值*/int GetKey(void){char lowbyte;int press;while (bioskey(1) == 0);/*如果用户没有按键,空循环*/press=bioskey(0);lowbyte=press&0xff;press=press&0xff00 + toupper(lowbyte); return(press);}/*落子错误处理*/void DoError(void){sound(1200);delay(50);nosound();}/*赢棋处理*/void DoWin(int Order){sound(1500);delay(100);sound(0); delay(50);sound(800); delay(100);sound(0); delay(50);sound(1500);delay(100);sound(0); delay(50);sound(800); delay(100);sound(0); delay(50);nosound();textcolor(RED+BLINK);gotoxy(25,20);if(Order==CHESS1)cputs("PLAYER1 WIN!");elsecputs("PLAYER2 WIN!");gotoxy(25,21);cputs("\n");getch();}/*走棋*/int ChessGo(int Order,struct point Cursor){/*判断交叉点上有无棋子*/if(gChessBoard[Cursor.x][Cursor.y]==CHESSNULL) {/*若没有棋子, 则可以落子*/gotoxy(Cursor.x+MAPXOFT,Cursor.y+MAPYOFT); textcolor(LIGHTBLUE);putch(Order);gotoxy(Cursor.x+MAPXOFT,Cursor.y+MAPYOFT); gChessBoard[Cursor.x][Cursor.y]=Order;return TRUE;}elsereturn FALSE;}/*判断当前行棋方落子后是否赢棋*/int JudgeWin(int Order,struct point Cursor){int i;for(i=0;i<4;i++)/*判断在指定方向上是否有连续5个行棋方的棋子*/if(JudgeWinLine(Order,Cursor,i))return TRUE;return FALSE;}/*判断在指定方向上是否有连续5个行棋方的棋子*/int JudgeWinLine(int Order,struct point Cursor,int direction) {int i;struct point pos,dpos;const int testnum = 5;int count;switch(direction){case 0:/*在水平方向*/pos.x=Cursor.x-(testnum-1);pos.y=Cursor.y;dpos.x=1;dpos.y=0;break;case 1:/*在垂直方向*/pos.x=Cursor.x;pos.y=Cursor.y-(testnum-1);dpos.x=0;dpos.y=1;break;case 2:/*在左下至右上的斜方向*/pos.x=Cursor.x-(testnum-1);pos.y=Cursor.y+(testnum-1);dpos.x=1;dpos.y=-1;break;case 3:/*在左上至右下的斜方向*/pos.x=Cursor.x-(testnum-1);pos.y=Cursor.y-(testnum-1);dpos.x=1;dpos.y=1;break;}count=0;for(i=0;i<testnum*2+1;i++)/*????????i<testnum*2-1*/ {if(pos.x>=0&&pos.x<=18&&pos.y>=0&&pos.y<=18) {if(gChessBoard[pos.x][pos.y]==Order){count++;if(count>=testnum)return TRUE;}elsecount=0;}pos.x+=dpos.x;pos.y+=dpos.y;}return FALSE;}/*移动光标*/void MoveCursor(int Order,int press){switch(press){case PLAY1UP:if(Order==CHESS1&&gCursor.y>0)gCursor.y--;break;case PLAY1DOWN:if(Order==CHESS1&&gCursor.y<18)gCursor.y++;break;case PLAY1LEFT:if(Order==CHESS1&&gCursor.x>0)gCursor.x--;break;case PLAY1RIGHT:if(Order==CHESS1&&gCursor.x<18)gCursor.x++;break;case PLAY2UP:if(Order==CHESS2&&gCursor.y>0)gCursor.y--;break;case PLAY2DOWN:if(Order==CHESS2&&gCursor.y<18)gCursor.y++;break;case PLAY2LEFT:if(Order==CHESS2&&gCursor.x>0)gCursor.x--;break;case PLAY2RIGHT:if(Order==CHESS2&&gCursor.x<18)gCursor.x++;break;}gotoxy(gCursor.x+MAPXOFT,gCursor.y+MAPYOFT); }/*游戏结束处理*/void EndGame(void){textmode(C80);}/*显示当前行棋方*/void ShowOrderMsg(int Order){gotoxy(6,MAPYOFT+20);textcolor(LIGHTRED);if(Order==CHESS1)cputs("Player1 go!");elsecputs("Player2 go!");gotoxy(gCursor.x+MAPXOFT,gCursor.y+MAPYOFT); }/*落子正确处理*/void DoOK(void){sound(500);delay(70);sound(600);delay(50);sound(1000);delay(100);nosound();}/*检查用户的按键类别*/int CheckKey(int press){if(press==ESCAPE)return KEYEXIT;/*是退出键*/elseif( ( press==PLAY1DO && gPlayOrder==CHESS1) || ( press==PLAY2DO && gPlayOrder==CHESS2))return KEYFALLCHESS;/*是落子键*/elseif( press==PLAY1UP || press==PLAY1DOWN || press==PLAY1LEFT || press==PLAY1RIGHT || press==PLAY2UP || press==PLAY2DOWN || press==PLAY2LEFT || press==PLAY2RIGHT)return KEYMOVECURSOR;/*是光标移动键*/elsereturn KEYINVALID;/*按键无效*/}。

五子棋游戏代码

五子棋游戏代码

1、游戏实现效果图:2、游戏代码(含详细注解):import java.awt.*;import java.awt.event.*;import java.awt.Color;import static java.awt.BorderLayout.*;public class Gobang00{Frame f = new Frame("五子棋游戏");MyCanvas border = new MyCanvas();int color = 0;// 旗子的颜色标识0:白子1:黑子boolean isStart = false;// 游戏开始标志int bodyArray[][] = new int[16][16]; // 设置棋盘棋子状态0 无子1 白子2 黑子Button b1 = new Button("游戏开始");Button b2 = new Button("重置游戏");//Label WinMess = new Label(" ");//用于输出获胜信息TextField WinMess = new TextField(40);Checkbox[] ckbHB = new Checkbox[2];//用于判断白子先下,还是黑子先下CheckboxGroup ckgHB = new CheckboxGroup();public void init(){border.setPreferredSize(new Dimension(320,310));WinMess.setBounds(100, 340, 300, 30);f.add(border);//设置游戏状态,是开始游戏,还是重置游戏Panel p1 = new Panel();//用于放置b1和b2按钮,及选择框p1.add(b1);p1.add(b2);b1.addActionListener(new gameStateListener());b2.addActionListener(new gameStateListener());//设置谁先下棋// Panel p2 = new Panel();//用于放置选择组建ckbHB[0] = new Checkbox("白子先", ckgHB, false); ckbHB[1] = new Checkbox("黑子先", ckgHB, false); p1.add(ckbHB[0]);p1.add(ckbHB[1]);ckbHB[0].addItemListener(new itemListener()); ckbHB[1].addItemListener(new itemListener());//进入下棋状态,为窗口和board添加事件监听器f.addMouseListener(new mouseProcessor()); border.addMouseListener(new mouseProcessor()); Panel p2 = new Panel();//用于放置输赢信息显示框p2.add(WinMess);gameInit();f.add(p1,BorderLayout.SOUTH);f.add(p2,BorderLayout.NORTH);f.pack();f.setVisible(true);//设置窗体关闭事件f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String[] args){new Gobang00().init();}//定义事件监听器类,用于判断是开始游戏,还是重置游戏class gameStateListener implements ActionListener{public void actionPerformed(ActionEvent e){if (e.getSource() == b1){gameStart();}else{reStart();}}}public void gameStart() // 游戏开始{isStart = true;enableGame(false);b2.setEnabled(true);}public void enableGame(boolean e) // 设置组件状态{b1.setEnabled(e);//setEnabled(boolean) - 类ponent 中的方法:根据参数b 的值启用或禁用此组件。

五子棋C语言程序代码

五子棋C语言程序代码

五子棋C语言程序代码#include <graphics.h>#include <stdio.h>#include <conio.h>void drawPanel();int isWin(int,int);int color = 1; //1-红色2-白色int chessman[15][15];//主函数void main(){initgraph(620,620); //产生窗体//画棋盘drawPanel();//画棋子//1.定义鼠标事件MOUSEMSG m;HWND wnd = GetHWnd(); //定义当前窗体的句柄while(true){m = GetMouseMsg(); //获取鼠标事件对象if(m.uMsg == WM_LBUTTONDOWN){//获取点击的坐标int x = m.x;int y = m.y;//换算成二维数组中的下标int i = x/40;int j = y/40;//显示点击的坐标/*char msg[100];sprintf(msg,"%d,%d",i,j);MessageBoxA(wnd,msg,"消息",MB_OK);*/if(color==1){setfillstyle(RGB(255,0,0));fillcircle(40*i+20,40*j+20,20);chessman[i][j] = 1;}else if(color==2){setfillstyle(RGB(255,255,255));fillcircle(40*i+20,40*j+20,20);chessman[i][j] = 2;}//判断输赢result => 1int result = isWin(i,j);if(result ==1){if(color==1){MessageBoxA(wnd,_T("恭喜,红方获胜!"),"消息",MB_OK);}else if(color==2){MessageBoxA(wnd,_T("恭喜,白方获胜!"),"消息",MB_OK);}break;}//切换对方下子color = color == 1 ? 2 : 1 ;}}getch();closegraph(); //关闭窗体}int isWin(int x,int y){int count=0;//计数器int i;//横向for(i=0;i<15;i++){if(chessman[i][y]==color){count++;if(count==5)return 1;}else{count=0;}}//竖向for(i=0;i<15;i++){if(chessman[x][i]==color){count++;if(count==5)return 1;}else{count=0;}}return 0;}void drawPanel(){int i;//画横线for(i=0;i<15;i++){line(20,20+40*i,20+14*40,20+40*i);}//画竖线for(i=0;i<15;i++){line(20+40*i,20,20+40*i,20+14*40);}}。

五子棋单机版代码

五子棋单机版代码

一下代码为纯c写的单机版五子棋代码,可用vc6.0编译运行#include <stdio.h>#include <conio.h>#include <windows.h>#include <time.h>#define TEXTS 7 // 文本颜色#define CURSOR 48 // 光标颜色#define CHESSBOARD 352 // 棋盘颜色#define WHITECHESS 103 // 白棋颜色#define SELECTEDWHITE 55 // 白棋被选中时的颜色#define BLACKCHESS 96 // 黑棋颜色#define SELECTEDBLACK 48 // 黑棋被选中时的颜色#define qx1_num 27 // 防御棋形的数量#define qx2_num 26 // 攻击棋形的数量typedef struct node{ // 棋盘信息int step; // 步数,步数为0表示该位置为空int color; // 棋子的颜色} NODE;typedef struct point{ //点int x;int y;} _POINT;typedef struct qixing{ // 棋形信息char qx[8]; // 棋形int value; // 相应的权值}QIXING;HANDLE hOutput=GetStdHandle(STD_OUTPUT_HANDLE); // 得到标准输出的句柄_POINT cursor; // 游戏中,光标所在的当前位置int direction[8][2]={{0,-1},{0,1},{-1,0},{1,0},{-1,-1},{1,1},{-1,1},{1,-1}};// 向量数组,依次为左、右、上、下、左上、右下、右上、左下QIXING qx1[qx1_num]={{"x1111",200000},{"1x111",200000},{"11x11",200000}, // 连五型{"0x1110",6000},{"01x110",6000},{"101x101",6000}, // 活四型{"0x111",1100},{"x0111",1100},{"0x1011",1100},{"0x1101",1100},{"01x11",1100}, // 冲四型{"011x1",1100},{"1x011",1100},{"10x11",1100},{"11x01",1100},{"1x101",1100}, // 冲四型{"x011102",250},{"0x110",250},{"01x10",250},{"0x01102",240},{"0x101",240}, // 活三型{"0x112",20},{"01x12",10},{"011x2",20},{"1x12",10},{"0x10",20},{"0x010",5}}; // 死三活二//防御的基本棋形及权值,0为空,1为对手,2为自己,x为下棋位置QIXING qx2[qx2_num]={{"x1111",2000000},{"1x111",2000000},{"11x11",2000000}, // 连五型{"0x1110",24000},{"01x110",24000}, {"101x101",24000}, //活四型{"0x111",2000},{"x0111",1900},{"0x1011",1900},{"0x1101",2000},{"01x11",2000}, // 冲四型{"011x1",2000},{"1x011",1900},{"10x11",2000},{"1x101",2000},{"x01112",2000}, // 冲四型{"0x110",850},{"01x10",850},{"0x0110",840},{"0x101",840},//活三型{"0x112",125},{"01x12",125},{"011x2",115},{"1x12",115},{"0x10",125},{"0x010",110}};// 死三活二// 攻击的基本棋形及权值,0为空,1为自己,2为对手,x为下棋位置//----------------------------------界面部分---------------------------------void textcolor(int color){// 更改字体颜色SetConsoleTextAttribute(hOutput,color);}void gotoxy(int x, int y){// 将光标移动到指定位置COORD coordScreen = { 0, 0 };coordScreen.X=x;coordScreen.Y=y;SetConsoleCursorPosition( hOutput, coordScreen );}void printnode(NODE chessboard[][15], int x, int y)// 打印棋盘上的一个点{textcolor(CHESSBOARD);if(chessboard[x][y].step==0) {if (x==cursor.x && y==cursor.y)textcolor(CURSOR); // 如果光标在这个点,改成光标颜色switch(x){case 0:if(y==0) printf("┏"); // 左上角else if(y==14) printf("┓"); // 右上角else printf("┯"); // 上边线break;case 3:if(y==0) printf("┠"); // 左边线else if(y==3 || y==11) printf("+"); // 星位else if(y==14) printf("┨"); // 右边线else printf("┼");// 交叉点break;case 7:if(y==0) printf("┠"); // 左边线else if(y==7) printf("+"); // 星位else if(y==14) printf("┨"); // 右边线else printf("┼");// 交叉点break;case 11:if(y==0) printf("┠"); // 左边线else if(y==3 || y==11) printf("+"); // 星位else if(y==14) printf("┨"); // 右边线else printf("┼");// 交叉点break;case 14:if(y==0) printf("┗"); // 左下角else if(y==14) printf("┛"); // 右下角else printf("┷"); // 下边线break;default:if(y==0) printf("┠"); // 左边线else if(y==14) printf("┨"); // 右边线else printf("┼");// 交叉点}}else if(chessboard[x][y].color==0){ // 如果是白棋if (x==cursor.x && y==cursor.y)textcolor(SELECTEDWHITE); // 被选中的白棋else textcolor(WHITECHESS); // 未被选中的白棋printf("●");} // 打印棋子else{if (x==cursor.x && y==cursor.y)textcolor(SELECTEDBLACK); // 被选中的黑子else textcolor(BLACKCHESS); // 未被选中的黑子printf("●");} // 打印棋子}void printchessboard(NODE chessboard[][15]){// 输出整个棋盘int i,j;char letter[]={"ABCDEFGHIJKLMNO\n"};for(i=0;i<15;i++){ // 行textcolor(TEXTS); // 改为文本颜色printf("%2d",15-i); // 打印行坐标for(j=0;j<15;j++) // 列printnode(chessboard,i,j); // 打印棋盘的每一块textcolor(TEXTS);printf("\n");}textcolor(TEXTS); //改为文本颜色printf(" %s",letter); //打印列坐标printf("移动:方向键下棋:ENTER 悔棋:U 退出:F12");}void renew(NODE chessboard[][15], int x, int y){// 更新棋盘指定位置的图像COORD coordScreen; // 系统提示符位置CONSOLE_SCREEN_BUFFER_INFO csbi; // 屏幕信息if(x<0 || x>14 || y<0 || y>14) return; // 如果不在棋盘上直接返回if( !GetConsoleScreenBufferInfo( hOutput, &csbi )) // 获取屏幕信息return; // 不成功则返回coordScreen=csbi.dwCursorPosition; // 获取系统提示符位置gotoxy((y-1)*2+4,x+1); // 将系统提示符移动到棋盘的(x,y)所在位置printnode(chessboard,x,y); // 重新打印这一块SetConsoleCursorPosition( hOutput, coordScreen );// 系统提示符回复到原来位置}void showmenu(){// 输出主菜单textcolor(TEXTS);system("cls");printf("1.人机对战\n");printf("2.双人对战\n");printf("3.退出\n");printf("\n请选择[1-3]:");}void showsubmenu(){// 打印子菜单textcolor(TEXTS);system("cls");printf("1.你先手\n");printf("2.电脑先手\n");printf("3.返回上级菜单\n");printf("\n请选择[1-3]:");}int getchoose(int min, int max){// 获取选项int choose;do{choose=getch()-48;}while(choose<min || choose>max); //过滤不在min到max之间的字符printf("%d",choose); //屏幕回显return choose;}//----------------------------------控制部分---------------------------------bool quit; //是否按下了退出热键bool regret; //是否按下了悔棋热键bool getmove(NODE chessboard[][15]){// 获取光标移动,并响应// 当按下悔棋、下子、退出热键时,返回truechar c;for(;;){c=getch();if(c==-32)switch(getch()){case 72: // 上cursor.x--;if(cursor.x<0) cursor.x=0;renew(chessboard,cursor.x+1,cursor.y);renew(chessboard,cursor.x,cursor.y);break;case 80: // 下cursor.x++;if(cursor.x>14) cursor.x=14;renew(chessboard,cursor.x-1,cursor.y);renew(chessboard,cursor.x,cursor.y);break;case 75: // 左cursor.y--;if(cursor.y<0) cursor.y=0;renew(chessboard,cursor.x,cursor.y+1);renew(chessboard,cursor.x,cursor.y);break;case 77: // 右cursor.y++;if(cursor.y>14) cursor.y=14;renew(chessboard,cursor.x,cursor.y-1);renew(chessboard,cursor.x,cursor.y);break;case 134: // 退出quit=true;return true;}else if(c==13 && chessboard[cursor.x][cursor.y].step==0)return true; // 下子else if(c=='U' || c=='u'){ // 悔棋regret=true;return true;}}}void beback(NODE chessboard[][15], int step){//悔棋int i,j,tempx,tempy;if(step==1) return; // 如果才开始,直接返回if(step>2){ // 如果下了多于两步for(i=0;i<15;i++) // 搜索前两步所下的位置for(j=0;j<15;j++) {if(chessboard[i][j].step==step-1){ // 找到上一步chessboard[i][j].step=0; // 清空棋子标志renew(chessboard,i,j);} // 重绘棋盘else if(chessboard[i][j].step==step-2){ // 找到上两步chessboard[i][j].step=0; // 清空棋子标志tempx=cursor.x; // 记录光标位置tempy=cursor.y;cursor.x=i; // 将光标回复到两步前的位置cursor.y=j;renew(chessboard,i,j); // 重绘棋盘renew(chessboard,tempx,tempy); // 重绘光标原本所在处}}}else if(step==2){ //如果下了一步for(i=0;i<15;i++) //搜索上一步所下的位置for(j=0;j<15;j++)if(chessboard[i][j].step==step-1){ // 找到上一步chessboard[i][j].step=0; // 清空棋子标志renew(chessboard,i,j);} // 重绘棋盘tempx=cursor.x; // 记录光标位置tempy=cursor.y;cursor.x=7; // 将光标移回棋盘中央cursor.y=7;renew(chessboard,i,j); // 重绘棋盘renew(chessboard,tempx,tempy); // 重绘光标原本所在处}}//------------------------------判断部分-------------------------------bool inside(int x, int y){// 如果不在棋盘内返回false,否则返回trueif(x<0 || x>14 || y<0 || y>14) return false;return(true);}int line(NODE chessboard[][15], int dirt, int x, int y, int color){// 判断颜色为color的点(x,y),在dirt方向上有多少相连的同色棋子int i;for(i=0;chessboard[x+direction[dirt][0]][y+direction[dirt][1]].step>0 && chessboard[x+direction[dirt][0]][y+direction[dirt][1]].color==color;i++) { x=x+direction[dirt][0];y=y+direction[dirt][1];if(!inside(x,y)) return i;}return i;}bool win(NODE chessboard[][15], int x, int y, int color){// 判断是否有人赢棋if(line(chessboard,0,x,y,color)+line(chessboard,1,x,y,color)>3)return true;if(line(chessboard,2,x,y,color)+line(chessboard,3,x,y,color)>3)return true;if(line(chessboard,4,x,y,color)+line(chessboard,5,x,y,color)>3)return true;if(line(chessboard,6,x,y,color)+line(chessboard,7,x,y,color)>3)return true;return false;}//--------------------------------AI部分----------------------------------int attacktrend,defenttrend; // 攻击防御平衡权值bool macth1(NODE chessboard[][15], int x, int y, int dirt, int kind, int color){/* 匹配在颜色为color的点(x,y),在dirt方向上的第kind种防守棋形,成功返回true,否则返回false */int k;char c;char *p;p=strchr(qx1[kind].qx,'x');for(k=0;k<=p-qx1[kind].qx;k++) {x-=direction[dirt][0];y-=direction[dirt][1];}for(k=0;(unsigned)k<strlen(qx1[kind].qx);k++) {x+=direction[dirt][0];y+=direction[dirt][1];if(!inside(x,y)) return(false);if(chessboard[x][y].step>0 && chessboard[x][y].color==color) c='2';else if(chessboard[x][y].step>0) c='1';else c='0';if(c=='0' && qx1[kind].qx[k]=='x') continue;if(c!=qx1[kind].qx[k]) return(false);}return true;}int value_qx1(NODE chessboard[][15], int x, int y, int dirt, int color){// 计算颜色为color的点8个方向上的防守权值之和int i;for(i=0;i<qx1_num;i++)if(macth1(chessboard,x,y,dirt,i,color))return qx1[i].value;return 0;}bool macth2(NODE chessboard[][15], int x, int y, int dirt, int kind, int color){/* 匹配在颜色为color的点(x,y),在dirt方向上的第kind种进攻棋形,成功返回true,否则返回false */int k;char c;char *p;p=strchr(qx2[kind].qx,'x');for(k=0;k<=p-qx2[kind].qx;k++) {x-=direction[dirt][0];y-=direction[dirt][1];}for(k=0;(unsigned)k<strlen(qx2[kind].qx);k++) {x+=direction[dirt][0];y+=direction[dirt][1];if(!inside(x,y)) return false;if(chessboard[x][y].step>0 && chessboard[x][y].color==color) c='2';else if(chessboard[x][y].step>0) c='1';else c='0';if(c=='0' && qx2[kind].qx[k]=='x') continue;if(c!=qx2[kind].qx[k]) return false;}return true;}int value_qx2(NODE chessboard[][15], int x, int y, int dirt, int color){// 计算颜色为color的点8个方向上的进攻权值之和int i;for(i=0;i<qx2_num;i++)if(macth2(chessboard,x,y,dirt,i,color))return qx2[i].value ;return 0;}void AI(NODE chessboard[][15], int *x, int *y, int color){// AI的主要函数,将思考后的结果返回给*x和*yint max=0; // 价值的最大值int maxi,maxj; // 获得最大值时所对应的坐标int i,j,k; // 循环控制变量int probability=1; // 几率参数int value[15][15]={0}; // 棋盘上各点的价值int valueattack[15][15]={{0}}; // 棋盘上各点的进攻价值int valuedefent[15][15]={{0}}; // 棋盘上各点的防守价值for(i=0;i<15;i++) // 计算棋盘上各点的防守价值for(j=0;j<15;j++) {if(chessboard[i][j].step>0) continue;for(k=0;k<8;k++)valuedefent[i][j]+=value_qx1(chessboard,i,j,k,color);if(maxi<valuedefent[i][j])maxi=valuedefent[i][j]; // 记录防守价值的最大值}for(i=0;i<15;i++) // 计算棋盘上各点的进攻价值for(j=0;j<15;j++) {if(chessboard[i][j].step>0) continue;for(k=0;k<8;k++)valueattack[i][j]+=value_qx2(chessboard,i,j,k,(color+1) % 2);if(maxj<valuedefent[i][j])maxj=valuedefent[i][j]; // 记录进攻价值的最大值}if(rand()%(maxi+maxj+1)>maxi){ // 如果防守价值的最大值比较低attacktrend=1; // AI优先进攻defenttrend=1;}else{ // 相反attacktrend=1; // AI优先防守defenttrend=2;}for(i=0;i<15;i++) // 根据各点的进攻和防守价值for(j=0;j<15;j++){ // 计算最终价值value[i][j]=valuedefent[i][j]*defenttrend+valueattack[i][j]*attacktrend;if(max<value[i][j]){max=value[i][j]; // 记录价值的最大值maxi=i; // 以及相应的坐标maxj=j;probability=1;}else if(max==value[i][j]){ // 如果出现相同价值的最大点if(rand()%(probability+1)<probability) // 随机决定选取哪一个probability++; /* 由于前面的点容易被淘汰,所以相应提高前面的点的被选择的几率*/else{probability=1; // 选择后面的点,则几率权值回复max=value[i][j]; // 记录maxi=i;maxj=j;}}}*x=maxi; // 返回价值最大的点*y=maxj;}//-----------------------主要部分------------------------------------bool vshuman; //对手是否是人void Vs(bool human){//对局主要函数int i,j;int color=1; // 黑棋先走int lastx,lasty; // 光标的上一个位置int computer; // 电脑执黑还是执白NODE chessboard[15][15]={{0,0}}; // 棋盘if(!human){ // 对手是电脑showsubmenu(); // 选择谁是先手switch(getchoose(1,3)){case 1:computer=0;attacktrend=1; // 电脑先手则优先进攻defenttrend=1;break;case 2:computer=1; // 电脑后手则优先防御attacktrend=1;defenttrend=2;break;case 3:return; // 返回上级菜单}}for(i=0;i<15;i++) // 清空棋盘for(j=0;j<15;j++)chessboard[i][j].step=0;cursor.x=7; // 光标居中cursor.y=7;quit=false; // 清空退出标志system("cls"); // 清屏printf("\n");printchessboard(chessboard); // 打印棋盘for(i=1;i<=225;){ // 行棋主循环gotoxy(0,0); // 系统光标移到屏幕左上角textcolor(TEXTS);printf(" 第%03d手,",i);if(color==1) printf("黑棋下");else printf("白棋下");regret=false; // 清空悔棋标志if(i>1){ // 第一子必须下在棋盘中央if(color!=computer || human) getmove(chessboard); // 该人走棋else{ // 该电脑走棋lastx=cursor.x; // 记录光标位置lasty=cursor.y;AI(chessboard,&cursor.x,&cursor.y,color); // 电脑走棋renew(chessboard,lastx,lasty); // 更新棋盘}}if(quit) return; // 如果按了退出热键则返回if(regret){ // 如果按了悔棋热键则调用悔棋函数beback(chessboard,i);if(i>2) i-=2;else if(i==2){i=1; color=(color+1) % 2 ;}}else{ // 如果没有按热键,则在光标位置下子chessboard[cursor.x][cursor.y].step=i++;chessboard[cursor.x][cursor.y].color=color;renew(chessboard,cursor.x,cursor.y);color=(color+1) % 2 ;}if(win(chessboard,cursor.x,cursor.y,(color+1) % 2) && !regret){// 有人赢textcolor(TEXTS);gotoxy(0,0);printf(" ");gotoxy(0,0);if(color==1) printf(" 白棋赢了!");else printf(" 黑棋赢了!");getch();return;}}gotoxy(0,0); // 如果下了225步还没人赢棋则平局printf(" ");gotoxy(0,0);printf(" 平局!");}void main(void){// 主函数srand((unsigned)time(NULL)); // 初始化随机种子for(;;){showmenu(); // 输出主菜单switch(getchoose(1,3)){case 1:Vs(false); break;case 2:Vs(true); break;case 3: printf("\n"); return;}} }。

C语言五子棋代码

C语言五子棋代码

//五子棋小游戏纯C语言代码#include <stdio.h>#define N 14char state[N][N];void init(void);void printState(void);bool isWin(bool isBlack,int x,int y);bool isLevelWin(bool isBlack,int x,int y);bool isVerticalWin(bool isBlack,int x,int y);bool isLeftInclinedWin(bool isBlack,int x,int y);bool isRightObliqueWin(bool isBlack,int x,int y);bool isWin(bool isBlack,int x,int y)//是否有获胜{return isLevelWin(isBlack,x,y)||isVerticalWin(isBlack,x,y)||isLeftInclinedWin(isBlack,x,y)||isRightObliqueWin(isBlack,x,y);}bool isLevelWin(bool isBlack,int x,int y)//确定水平直线上是否有五子连珠{char c = isBlack ? '@':'O';int count;while(y>0 && state[x][y] == c){y--;}count =0;if(state[x][y] == c) count = 1;y++;while(y < N && state[x][y] == c){count++;if(count == 5){return true;}y++;}return false;}bool isVerticalWin(bool isBlack,int x,int y)//确定竖直直线是否有五子连珠{char c = isBlack ? '@':'O';int count;while(x>0 && state[x][y] == c){x--;}count =0;if(state[x][y] == c) count = 1;x++;while(x < N && state[x][y] == c){count++;if(count == 5){return true;}x++;}return false;}bool isLeftInclinedWin(bool isBlack,int x,int y)//确定左斜线是否有五子连珠{char c = isBlack ? '@':'O';int count;while(x>0 && y>0 && state[x][y] == c){y--;x--;}count =0;if(state[x][y] == c) count = 1;x++;y++;while(x < N && y < N && state[x][y] == c){count++;if(count == 5){return true;}x++;y++;}return false;}bool isRightObliqueWin(bool isBlack,int x,int y)//确定右斜线是否有五子连珠{char c = isBlack ? '@':'O';int count;while(x>0 && y<N && state[x][y] == c){y++;x--;}count =0;if(state[x][y] == c) count = 1;x++;y--;while(x < N && y >= 0 && state[x][y] == c){count++;if(count == 5){return true;}x++;y--;}return false;}void init(void)//开局初始化数组{int i,j;for(i=0;i<N;i++){for(j=0;j<N;j++){state[i][j] = '*';}}}void printState(void)//打印棋盘{int i,j;printf("%3c",' ');for(i=0;i<N;i++)printf("%3d",i);printf("\n");for(i=0;i<N;i++){printf("%3d",i);for(j=0;j<N;j++){printf("%3c",state[i][j]);}printf("\n");}}int main(void){int x,y;bool isBlack = true;init();printf("五子棋小游戏\n\n@代表黑子,0代表白子,*代表棋盘空白\n");printf("------------------------------------------------------\n");printState();while(1){printf("请%s 方走棋:\n",(isBlack?"黑":"白"));//请黑(白)方走棋的说明printf("输入所下位置坐标,如: 1-2\n");//走棋方法示例scanf("%d-%d",&x,&y);if(state[x][y]=='@' || state[x][y]=='O')//若此点已经存在棋子,则重新下一步棋在别处{printf("this position to have pieces\n");continue;}state[x][y] = (isBlack?'@':'O');//规定@代表黑子,0代表白子printState();//打印棋盘情况if(isWin(isBlack,x,y))//每下一步棋,判断一次是否有人获胜{printf("%s 方胜利\n",(isBlack?"黑":"白"));break;}isBlack = !isBlack;}}。

五子棋代码

五子棋代码

五子棋#include <graphics.h>#include <conio.h>#include <stdio.h>#include <string.h>#include <math.h>void kaishijiemian();void init(); //qipanvoid xiaqi();void sjx();void sljm(int win);int a[15][15]={0};void main()//主函数{initgraph(740, 480);//创建绘图界面大小kaishijiemian();//开始界面getch();}void kaishijiemian()//开始界面{initgraph(740,480);setbkcolor(RGB(84,26,8));//背景颜色cleardevice();//清屏for(int i=300;i<420;i+=2)//开始黑白棋动画{setfillcolor(WHITE);//这个函数用于设置当前的填充颜色。

solidcircle(i,200,49);//画圆Sleep(5);setfillcolor(RGB(84,26,8));//填充颜色solidcircle(i,200,49);//画圆setfillcolor(BLACK);solidcircle(740-i,200,50);Sleep(5);setfillcolor(RGB(84,26,8));solidcircle(740-i,200,50);}setfillcolor(WHITE);solidcircle(421,200,49);setfillcolor(BLACK);solidcircle(319,200,50);settextstyle(30,15,"宋体");settextcolor(RGB(255,255,255));outtextxy(290,320," 开始游戏");MOUSEMSG m; //这个结构体用于保存鼠标消息,定义如下:while(1)//鼠标操作{m=GetMouseMsg();//这个函数用于获取一个鼠标消息。

五子棋C语言代码

五子棋C语言代码

#include "graphics.h" /*图形系统头文件*/#define LEFT 0x4b00 /*光标左键值*/#define RIGHT 0x4d00 /*光标右键值*/#define DOWN 0x5000 /*光标下键值*/#define UP 0x4800 /*光标上键值*/#define ESC 0x011b /* ESC键值*/#define ENTER 0x1c0d /* 回车键值*/int a[8][8]={0},key,score1,score2;/*具体分数以及按键与存放棋子的变量*/ char playone[3],playtwo[3];/*两个人的得分转换成字符串输出*/void playtoplay(void);/*人人对战函数*/void DrawQp(void);/*画棋盘函数*/void SetPlayColor(int x);/*设置棋子第一次的颜色*/void MoveColor(int x,int y);/*恢复原来棋盘状态*/int QpChange(int x,int y,int z);/*判断棋盘的变化*/void DoScore(void);/*处理分数*/void PrintScore(int n);/*输出成绩*/void playWin(void);/*输出胜利者信息*//******主函数*********/void main(void){int gd=DETECT,gr;initgraph(&gd,&gr,"c:\\tc"); /*初始化图形系统*/DrawQp();/*画棋盘*/playtoplay();/*人人对战*/getch();closegraph();/*关闭图形系统*/}void DrawQp()/*画棋盘*/{int i,j;score1=score2=0;/*棋手一开始得分都为0*/setbkcolor(BLUE);for(i=100;i<=420;i+=40){line(100,i,420,i);/*画水平线*/line(i,100,i,420); /*画垂直线*/}setcolor(0);/*取消圆周围的一圈东西*/setfillstyle(SOLID_FILL,15);/*白色实体填充模式*/fillellipse(500,200,15,15); /*在显示得分的位置画棋*/setfillstyle(SOLID_FILL,8); /*黑色实体填充模式*/fillellipse(500,300,15,15);a[3][3]=a[4][4]=1;/*初始两个黑棋*/a[3][4]=a[4][3]=2;/*初始两个白棋*/setfillstyle(SOLID_FILL,WHITE);fillellipse(120+3*40,120+3*40,15,15);fillellipse(120+4*40,120+4*40,15,15);setfillstyle(SOLID_FILL,8);fillellipse(120+3*40,120+4*40,15,15);fillellipse(120+4*40,120+3*40,15,15);score1=score2=2; /*有棋后改变分数*/DoScore();/*输出开始分数*/}void playtoplay()/*人人对战*/{int x,y,t=1,i,j,cc=0;while(1)/*换棋手走棋*/{x=120,y=80;/*每次棋子一开始出来的坐标,x为行坐标,y为列坐标*/ while(1) /*具体一个棋手走棋的过程*/{PrintScore(1);/*输出棋手1的成绩*/PrintScore(2);/*输出棋手2的成绩*/SetPlayColor(t);/*t变量是用来判断棋手所执棋子的颜色*/fillellipse(x,y,15,15);key=bioskey(0);/*接收按键*/if(key==ESC)/*跳出游戏*/break;elseif(key==ENTER)/*如果按键确定就可以跳出循环*/{if(y!=80&&a[(x-120)/40][(y-120)/40]!=1&&a[(x-120)/40][(y-120)/40]!=2)/*如果落子位置没有棋子*/{if(t%2==1)/*如果是棋手1移动*/a[(x-120)/40][(y-120)/40]=1;else/*否则棋手2移动*/a[(x-120)/40][(y-120)/40]=2;if(!QpChange(x,y,t))/*落子后判断棋盘的变化*/{a[(x-120)/40][(y-120)/40]=0;/*恢复空格状态*/cc++;/*开始统计尝试次数*/if(cc>=64-score1-score2) /*如果尝试超过空格数则停步*/{MoveColor(x,y);fillellipse(x,y,15,15);break;}elsecontinue;/*如果按键无效*/}DoScore();/*分数的改变*/break;/*棋盘变化了,则轮对方走棋*/ }else/*已经有棋子就继续按键*/continue;}else /*四个方向按键的判断*/if(key==LEFT&&x>120)/*左方向键*/{MoveColor(x,y);fillellipse(x,y,15,15);SetPlayColor(t);x-=40;fillellipse(x,y,15,15);}elseif(key==RIGHT&&x<400&&y>80)/*右方向键*/ {MoveColor(x,y);fillellipse(x,y,15,15);SetPlayColor(t);x+=40;fillellipse(x,y,15,15);}elseif(key==UP&&y>120)/*上方向键*/{MoveColor(x,y);fillellipse(x,y,15,15);SetPlayColor(t);y-=40;fillellipse(x,y,15,15);}elseif(key==DOWN&&y<400)/*下方向键*/{MoveColor(x,y);fillellipse(x,y,15,15);SetPlayColor(t);y+=40;fillellipse(x,y,15,15);}}if(key==ESC)/*结束游戏*/break;if((score1+score2)==64||score1==0||score2==0)/*格子已经占满或一方棋子为0判断胜负*/{playWin();/*输出最后结果*/break;}t=t%2+1; /*一方走后,改变棋子颜色即轮对方走*/cc=0; /*计数值恢复为0*/} /*endwhile*/}void SetPlayColor(int t)/*设置棋子颜色*/{if(t%2==1)setfillstyle(SOLID_FILL,15);/*白色*/elsesetfillstyle(SOLID_FILL,8);/*灰色*/}void MoveColor(int x,int y)/*走了一步后恢复原来格子的状态*/{if(y<100)/*如果是从起点出发就恢复蓝色*/setfillstyle(SOLID_FILL,BLUE);else/*其他情况如果是1就恢复白色棋子,2恢复黑色棋子,或恢复蓝色棋盘*/ switch(a[(x-120)/40][(y-120)/40]){case 1:setfillstyle(SOLID_FILL,15);break; /*白色*/case 2:setfillstyle(SOLID_FILL,8);break; /*黑色*/default:setfillstyle(SOLID_FILL,BLUE); /*蓝色*/}}int QpChange(int x,int y,int t)/*判断棋盘的变化*/{int i,j,k,kk,ii,jj,yes;yes=0;i=(x-120)/40; /*计算数组元素的行下标*/j=(y-120)/40; /*计算数组元素的列下标*/SetPlayColor(t);/*设置棋子变化的颜色*//*开始往8个方向判断变化*/if(j<6)/*往右边*/{for(k=j+1;k<8;k++)if(a[i][k]==a[i][j]||a[i][k]==0)/*遇到自己的棋子或空格结束*/ break;if(a[i][k]!=0&&k<8){for(kk=j+1;kk<k&&k<8;kk++)/*判断右边*/{a[i][kk]=a[i][j]; /*改变棋子颜色*/fillellipse(120+i*40,120+kk*40,15,15);}if(kk!=j+1) /*条件成立则有棋子改变过颜色*/yes=1;}}if(j>1)/*判断左边*/{for(k=j-1;k>=0;k--)if(a[i][k]==a[i][j]||!a[i][k])break;if(a[i][k]!=0&&k>=0){for(kk=j-1;kk>k&&k>=0;kk--){a[i][kk]=a[i][j];fillellipse(120+i*40,120+kk*40,15,15);}if(kk!=j-1)yes=1;}}if(i<6)/*判断下边*/{for(k=i+1;k<8;k++)if(a[k][j]==a[i][j]||!a[k][j])break;if(a[k][j]!=0&&k<8){for(kk=i+1;kk<k&&k<8;kk++){a[kk][j]=a[i][j];fillellipse(120+kk*40,120+j*40,15,15);}if(kk!=i+1)yes=1;}}if(i>1)/*判断上边*/{for(k=i-1;k>=0;k--)if(a[k][j]==a[i][j]||!a[k][j])break;if(a[k][j]!=0&&k>=0){for(kk=i-1;kk>k&&k>=0;kk--){a[kk][j]=a[i][j];fillellipse(120+kk*40,120+j*40,15,15); }if(kk!=i-1)yes=1;}}if(i>1&&j<6)/*右上*/{for(k=i-1,kk=j+1;k>=0&&kk<8;k--,kk++) if(a[k][kk]==a[i][j]||!a[k][kk])break;if(a[k][kk]&&k>=0&&kk<8){for(ii=i-1,jj=j+1;ii>k&&k>=0;ii--,jj++){a[ii][jj]=a[i][j];fillellipse(120+ii*40,120+jj*40,15,15); }if(ii!=i-1)yes=1;}}if(i<6&&j>1)/*左下*/{for(k=i+1,kk=j-1;k<8&&kk>=0;k++,kk--) if(a[k][kk]==a[i][j]||!a[k][kk])break;if(a[k][kk]!=0&&k<8&&kk>=0){for(ii=i+1,jj=j-1;ii<k&&k<8;ii++,jj--){a[ii][jj]=a[i][j];fillellipse(120+ii*40,120+jj*40,15,15);}if(ii!=i+1)yes=1;}}if(i>1&&j>1)/*左上*/{for(k=i-1,kk=j-1;k>=0&&kk>=0;k--,kk--)if(a[k][kk]==a[i][j]||!a[k][kk])break;if(a[k][kk]!=0&&k>=0&&kk>=0){for(ii=i-1,jj=j-1;ii>k&&k>=0;ii--,jj--){a[ii][jj]=a[i][j];fillellipse(120+ii*40,120+jj*40,15,15);}if(ii!=i-1)yes=1;}}if(i<6&&j<6)/* 右下*/{for(k=i+1,kk=j+1;kk<8&&kk<8;k++,kk++)if(a[k][kk]==a[i][j]||!a[k][kk])break;if(a[k][kk]!=0&&kk<8&&k<8){for(ii=i+1,jj=j+1;ii<k&&k<8;ii++,jj++){a[ii][jj]=a[i][j];fillellipse(120+ii*40,120+jj*40,15,15);}if(ii!=i+1)yes=1;}}return yes;/*返回是否改变过棋子颜色的标记*/ }void DoScore()/*处理分数*/{int i,j;score1=score2=0;/*重新开始计分数*/for(i=0;i<8;i++)for(j=0;j<8;j++)if(a[i][j]==1)/*分别统计两个人的分数*/score1++;elseif(a[i][j]==2)score2++;}void PrintScore(int playnum)/*输出成绩*/{if(playnum==1)/*清除以前的成绩*/{setfillstyle(SOLID_FILL,BLUE);bar(550,100,640,400);}setcolor(RED);settextstyle(0,0,4);/*设置文本输出样式*/if(playnum==1)/*判断输出哪个棋手的分,在不同的位置输出*/ {sprintf(playone,"%d",score1);outtextxy(550,200,playone);}else{sprintf(playtwo,"%d",score2);outtextxy(550,300,playtwo);}setcolor(0);}void playWin()/*输出最后的胜利者结果*/{settextstyle(0,0,4);setcolor(12);if(score2>score1)/*开始判断最后的结果*/outtextxy(100,50,"black win!");elseif(score2<score1)outtextxy(100,50,"white win!");elseouttextxy(60,50,"you all win!");}。

五子棋代码

五子棋代码
else
if(ch=='y'||ch=='Y')
break;
else
printf("Please enter again:(Y/N)\n");
}
printf("welcome");
}
/*帮助提示界面*/
void help()
{
printf("HELP\n");
printf("1.INTRODUCTION\n");
printf("Gobang is played between two opponents on a board by making ");
printf("moves with black\nand white chesses.\n\n");
printf("2.WIN OF A GAME\n");
void playChess()
{
int i;
int j;
k=0;
switch(key) //判断输入的游戏键key是什么
{
case 75: //输入的是左键
y--;
if(y<0)
y=N-1;
break;
case 77: //输入的是右键
y++;
if(y>=N)
y=0;
break;
case 80: //输入的是下键
{
status[x][y]=1; //设该位置为黑棋
step++; //棋盘上棋子数加一个
exchange(); //改变下棋方
}
else if(flag==2) //如果该位置没棋,判断是否是下白棋
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

/*************************************** 程序名称:五子棋 **** 编译环境:vs2012 **** 编辑作者:往事随风<1034882113> **** 最后修改:2013-07-25 **** 项目类型:win32控制台程序 ****************************************/#include<graphics.h>#include<conio.h>// _kbhit() _getch()/****************** 宏定义区 **********************/#define BOARD_LEN 640 // 棋盘大小#define BOARD_WIDTH 640#define EXTRA_LEN 200 // 右边提示区域的长度#define SIZE 40 // 棋盘小方格大小#define ROW 14 // 棋盘为14*14/****************** 数据类型定义区******************//****************** 全局变量区**********************/IMAGE img_chessboard; // 背景IMAGE img_box_black; // 黑色棋盒IMAGE img_box_white; // 白色棋盒IMAGE img_bkbox; // 右边区域背景IMAGE img_time; // 显示时间IMAGE img_count[11]; // 十个数字和一个冒号int m_x = (BOARD_LEN - SIZE * ROW)/2; // 居中int m_y = (BOARD_WIDTH - SIZE * ROW)/2;byte gobang[ROW+1][ROW+1] = {0};// byte不能表示负数0:无子1:黑子2:白子byte type = 0; // 1: 白棋0:黑棋bool replay = true; // false 游戏结束,true代表游戏运行中DWORD b_oldtime; // 黑棋花费时间DWORD w_oldtime; // 白棋花费时间DWORD start_time; // 游戏起始时间/****************** 函数声明区**********************/void init_system();void init_img();void init_chessboard();void getMouse(POINT *point);void deal_mousemsg(POINT point);void game_win(int x,int y);void quit_game();void print_msg();void show_time(DWORD newtime);void print_time(DWORD time);/****************** 主函数区 **********************/ void main(){POINT point; // 存储坐标位置while (true){init_system();while (replay){getMouse(&point);deal_mousemsg(point);}}}/****************** 函数定义区**********************/void print_time(DWORD time){int y = 0;int minuteh = time / (600*1000); // 分钟十位time %= (600*1000);int minutel = time / (60*1000); // 分钟个位time %= (60*1000);int secondh = time / (10*1000); // 秒钟十位int secondl = time % (10*1000); // 秒钟个位int x = BOARD_LEN + 5 - m_x;if (type) // 白棋y = EXTRA_LEN + 5 - m_y;else y = BOARD_WIDTH/2+EXTRA_LEN+5 - m_y; // 黑棋putimage(x+80,y+45,&img_count[minuteh]); // 分钟十位putimage(x+95,y+45,&img_count[minutel]); // 分钟个位putimage(x+125,y+45,&img_count[secondh]); // 秒十位putimage(x+140,y+45,&img_count[secondl/1000]); // 秒个位}/* 显示倒计时 */void show_time(DWORD newtime){DWORD tmp = b_oldtime+w_oldtime + start_time; // 游戏运行的时间if (type) // 白棋{w_oldtime += newtime - tmp; // 计算白棋用的时间print_time(w_oldtime);}else// 黑棋{b_oldtime += newtime - tmp; // 计算黑棋用的时间print_time(b_oldtime);}}/* 打印右边游戏信息 */void print_msg(){outtextxy(20,50,_T("倒计时:"));putimage(80,45,&img_count[0]);putimage(95,45,&img_count[0]);putimage(110,45,&img_count[10]);putimage(125,45,&img_count[0]);putimage(140,45,&img_count[0]);outtextxy(20,80,_T("比分:"));outtextxy(80,80,_T("0"));}/* 结束游戏 */void quit_game(){closegraph();exit(0);}/* 判断胜利 */void game_win(int x,int y){int i = -5,j = -5;int count = 0;byte flag = gobang[x][y]; // 判断棋色while (count != 5 && ++i < 5) // 横{if (gobang[x+i][y] == flag)count++;else count = 0;}while (count != 5 && ++j < 5) // 竖{if (gobang[x][y+j] == flag)count++;else count = 0;}i = j = -5;while (count != 5 && ++i < 5 && ++j < 5) // 左斜{if (gobang[x+i][y+j] == flag)count++;else count = 0;}i = 5;j = -5;while (count != 5 && --i > -5 && ++j < 5) // 右斜{if (gobang[x+i][y+j] == flag)count++;else count = 0;}if (count == 5){setbkmode(TRANSPARENT); // 设置文字背景透明settextstyle(48, 0, _T("宋体"));settextcolor(RED);if (flag == 1)outtextxy(BOARD_LEN/3,BOARD_WIDTH/3,_T("BLACK WIN"));else outtextxy(BOARD_LEN/3,BOARD_WIDTH/3,_T("WHITE WIN"));HWND wnd = GetHWnd();if (MessageBox(wnd, _T("要再来一局吗?"), _T("提醒"),MB_OKCANCEL | MB_ICONQUESTION) == IDOK){replay = false;Sleep(200);}else quit_game();}}/* 画棋子 */void deal_mousemsg(POINT point){int r = SIZE/2; // 取点范围int x0 = (point.x - m_x) / SIZE + (point.x - m_x)%SIZE/r;int y0 = (point.y - m_y) / SIZE + (point.y - m_y)%SIZE/r;if (type) // 判断棋手1:白棋0:黑棋setfillcolor(WHITE);else setfillcolor(BLACK);if (x0 >= 0 && x0 <= ROW && // 判断边界y0 >= 0 && y0 <= ROW &&gobang[x0][y0] == 0) // 无子状态才下子{fillcircle(x0*SIZE,y0*SIZE,SIZE/3);gobang[x0][y0] = 1 + (1&&type); // 置为有子状态(必须位于判断输赢前) game_win(x0,y0);type = 1 ^ type; // 换手}}/* */void getMouse(POINT *point){HWND hwnd = GetHWnd(); // 获取绘图窗口句柄MOUSEMSG msg;FlushMouseMsgBuffer();while (true) // 等待鼠标点击{DWORD newtime = GetTickCount(); // 获取系统时间if (newtime - w_oldtime - b_oldtime > 1000)show_time(newtime); // 显示时间if (MouseHit()){msg = GetMouseMsg();if (msg.uMsg ==WM_LBUTTONDOWN){GetCursorPos(point); // 获取鼠标指针位置(屏幕坐标)ScreenToClient(hwnd,point); // 将鼠标指针位置转换为窗口坐标break;}}}}/* 初始化棋盘 */void init_chessboard(){int i = 0, j = 0;init_img(); // 初始化图片资源putimage(0,0,&img_chessboard); // 输出棋盘putimage(BOARD_LEN,0,&img_bkbox); // 输出右边背景putimage(BOARD_LEN,0,&img_box_white); // 输出白色棋盒putimage(BOARD_LEN,BOARD_WIDTH/2,&img_box_black); // 输出黑色棋盒setcolor(BLACK);rectangle(BOARD_LEN+5,EXTRA_LEN+5,BOARD_LEN+EXTRA_LEN-5,BOARD_WIDTH/2-5);rectangle(BOARD_LEN+5,BOARD_WIDTH/2+EXTRA_LEN+5,BOARD_LEN+EXTRA_LEN-5,BOARD_WIDTH-5);setbkmode(TRANSPARENT);setorigin(BOARD_LEN+5,EXTRA_LEN+5); // 上面的矩形白子outtextxy(20,20,_T("undefined"));print_msg();setorigin(BOARD_LEN+5,BOARD_WIDTH/2+EXTRA_LEN+5); // 下面的矩形黑子outtextxy(20,20,_T("电脑"));print_msg();setcolor(BLACK);setorigin(m_x,m_y); // 设置原点for (i = 0; i <= ROW; i++){line(0,0+i*SIZE,0+SIZE*ROW,0+i*SIZE); // 横线line(0+i*SIZE,0,0+i*SIZE,0+SIZE*ROW); // 竖线}}void init_img(){int i = 0;loadimage(&img_chessboard,_T("./res/chess_board.jpg"),BOARD_LEN,BOARD_WIDTH,true);loadimage(&img_box_white,_T("./res/box_white1.bmp"),EXTRA_LEN,EXTRA_LEN,true);loadimage(&img_box_black,_T("./res/box_black1.bmp"),EXTRA_LEN,EXTRA_LEN,true);loadimage(&img_bkbox,_T("./res/bkbox.bmp"),EXTRA_LEN,BOARD_WIDTH,true);loadimage(&img_time,_T("./res/time.bmp"),15,250,true);SetWorkingImage(&img_time);for (i = 0; i < 10; i++) // 初始化十个数字getimage(&img_count[i],0,i*25,15,25);loadimage(&img_count[10],_T("./res/dot.bmp"),15,25,true);SetWorkingImage(NULL);}void init_system(){int i = 0, j = 0;initgraph(BOARD_LEN+EXTRA_LEN+10,BOARD_WIDTH+10);init_chessboard();replay = true;ZeroMemory(gobang,(ROW+1)*(ROW+1)); // 初始化数组为0b_oldtime = 0;w_oldtime = 0;start_time = GetTickCount();}。

相关文档
最新文档