五子棋游戏代码
- 格式:doc
- 大小:33.00 KB
- 文档页数:7
#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;/*按键无效*/}。
import java.awt.*;import java.awt.event.*;import java.io.*;import .*;import java.util.*;class clientThread extends Thread {chessClient chessclient;clientThread(chessClient chessclient) {this.chessclient = chessclient;}public void acceptMessage(String recMessage) {if (recMessage.startsWith("/userlist ")) {StringTokenizer userToken = new StringTokenizer(recMessage, " ");int userNumber = 0;erList.removeAll();erChoice.removeAll();erChoice.addItem("所有人");while (userToken.hasMoreTokens()) {String user = (String) userToken.nextToken(" ");if (userNumber > 0 && !user.startsWith("[inchess]")) {erList.add(user);erChoice.addItem(user);}userNumber++;}erChoice.select("所有人");} else if (recMessage.startsWith("/yourname ")) {chessclient.chessClientName = recMessage.substring(10);chessclient.setTitle("Java五子棋客户端" + "用户名:"+ chessclient.chessClientName);} else if (recMessage.equals("/reject")) {try {chessclient.chesspad.statusText.setText("不能加入游戏");chessclient.controlpad.cancelGameButton.setEnabled(false);chessclient.controlpad.joinGameButton.setEnabled(true);chessclient.controlpad.creatGameButton.setEnabled(true);} catch (Exception ef) {chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭");}chessclient.controlpad.joinGameButton.setEnabled(true);} else if (recMessage.startsWith("/peer ")) {chessclient.chesspad.chessPeerName = recMessage.substring(6);if (chessclient.isServer) {chessclient.chesspad.chessColor = 1;chessclient.chesspad.isMouseEnabled = true;chessclient.chesspad.statusText.setText("请黑棋下子");} else if (chessclient.isClient) {chessclient.chesspad.chessColor = -1;chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子...");}} else if (recMessage.equals("/youwin")) {chessclient.isOnChess = false;chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接");chessclient.chesspad.isMouseEnabled = false;} else if (recMessage.equals("/OK")) {chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入...");} else if (recMessage.equals("/error")) {chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入\n");} else {chessclient.chatpad.chatLineArea.append(recMessage + "\n");chessclient.chatpad.chatLineArea.setCaretPosition(chessclient.chatpad.chatLineArea.getText().length());}}public void run() {String message = "";try {while (true) {message = chessclient.in.readUTF();acceptMessage(message);}} catch (IOException es) {}}}public class chessClient extends Frame implements ActionListener, KeyListener { userPad userpad = new userPad();chatPad chatpad = new chatPad();controlPad controlpad = new controlPad();chessPad chesspad = new chessPad();inputPad inputpad = new inputPad();Socket chatSocket;DataInputStream in;DataOutputStream out;String chessClientName = null;String host = null;int port = 4331;boolean isOnChat = false; // 在聊天?boolean isOnChess = false; // 在下棋?boolean isGameConnected = false; // 下棋的客户端连接?boolean isServer = false; // 如果是下棋的主机boolean isClient = false; // 如果是下棋的客户端Panel southPanel = new Panel();Panel northPanel = new Panel();Panel centerPanel = new Panel();Panel westPanel = new Panel();Panel eastPanel = new Panel();chessClient() {super("Java五子棋客户端");setLayout(new BorderLayout());host = controlpad.inputIP.getText();westPanel.setLayout(new BorderLayout());westPanel.add(userpad, BorderLayout.NORTH);westPanel.add(chatpad, BorderLayout.CENTER);westPanel.setBackground(Color.pink);inputpad.inputWords.addKeyListener(this);chesspad.host = controlpad.inputIP.getText();centerPanel.add(chesspad, BorderLayout.CENTER);centerPanel.add(inputpad, BorderLayout.SOUTH);centerPanel.setBackground(Color.pink);controlpad.connectButton.addActionListener(this);controlpad.creatGameButton.addActionListener(this);controlpad.joinGameButton.addActionListener(this);controlpad.cancelGameButton.addActionListener(this);controlpad.exitGameButton.addActionListener(this);controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(false);southPanel.add(controlpad, BorderLayout.CENTER);southPanel.setBackground(Color.pink);addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {if (isOnChat) {try {chatSocket.close();} catch (Exception ed) {}}if (isOnChess || isGameConnected) {try {chesspad.chessSocket.close();} catch (Exception ee) {}}System.exit(0);}public void windowActivated(WindowEvent ea) {}});add(westPanel, BorderLayout.WEST);add(centerPanel, BorderLayout.CENTER);add(southPanel, BorderLayout.SOUTH);pack();setSize(670, 548);setVisible(true);setResizable(false);validate();}public boolean connectServer(String serverIP, int serverPort)throws Exception {try {chatSocket = new Socket(serverIP, serverPort);in = new DataInputStream(chatSocket.getInputStream());out = new DataOutputStream(chatSocket.getOutputStream());clientThread clientthread = new clientThread(this);clientthread.start();isOnChat = true;return true;} catch (IOException ex) {chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序\n");}return false;}public void actionPerformed(ActionEvent e) {if (e.getSource() == controlpad.connectButton) {host = chesspad.host = controlpad.inputIP.getText();try {if (connectServer(host, port)) {chatpad.chatLineArea.setText("");controlpad.connectButton.setEnabled(false);controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);chesspad.statusText.setText("连接成功,请创建游戏或加入游戏");}} catch (Exception ei) {chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序\n");}}if (e.getSource() == controlpad.exitGameButton) {if (isOnChat) {try {chatSocket.close();} catch (Exception ed) {}}if (isOnChess || isGameConnected) {try {chesspad.chessSocket.close();} catch (Exception ee) {}}System.exit(0);}if (e.getSource() == controlpad.joinGameButton) {String selectedUser = erList.getSelectedItem();if (selectedUser == null || selectedUser.startsWith("[inchess]")|| selectedUser.equals(chessClientName)) {chesspad.statusText.setText("必须先选定一个有效用户");} else {try {if (!isGameConnected) {if (chesspad.connectServer(chesspad.host, chesspad.port)) {isGameConnected = true;isOnChess = true;isClient = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/joingame "+ erList.getSelectedItem() + " "+ chessClientName);}} else {isOnChess = true;isClient = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/joingame "+ erList.getSelectedItem() + " "+ chessClientName);}} catch (Exception ee) {isGameConnected = false;isOnChess = false;isClient = false;controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chatpad.chatLineArea.setText("chesspad.connectServer无法连接\n" + ee);}}}if (e.getSource() == controlpad.creatGameButton) {try {if (!isGameConnected) {if (chesspad.connectServer(chesspad.host, chesspad.port)) {isGameConnected = true;isOnChess = true;isServer = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/creatgame "+ "[inchess]" + chessClientName);}} else {isOnChess = true;isServer = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/creatgame "+ "[inchess]" + chessClientName);}} catch (Exception ec) {isGameConnected = false;isOnChess = false;isServer = false;controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);ec.printStackTrace();chatpad.chatLineArea.setText("chesspad.connectServer无法连接\n"+ ec);}}if (e.getSource() == controlpad.cancelGameButton) {if (isOnChess) {chesspad.chessthread.sendMessage("/giveup " + chessClientName);chesspad.chessVictory(-1 * chesspad.chessColor);controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chesspad.statusText.setText("请建立游戏或者加入游戏");}if (!isOnChess) {controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chesspad.statusText.setText("请建立游戏或者加入游戏");}isClient = isServer = false;}}public void keyPressed(KeyEvent e) {TextField inputWords = (TextField) e.getSource();if (e.getKeyCode() == KeyEvent.VK_ENTER) {if (erChoice.getSelectedItem().equals("所有人")) {try {out.writeUTF(inputWords.getText());inputWords.setText("");} catch (Exception ea) {chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接\n");erList.removeAll();erChoice.removeAll();inputWords.setText("");controlpad.connectButton.setEnabled(true);}} else {try {out.writeUTF("/" + erChoice.getSelectedItem()+ " " + inputWords.getText());inputWords.setText("");} catch (Exception ea) {chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接\n");erList.removeAll();erChoice.removeAll();inputWords.setText("");controlpad.connectButton.setEnabled(true);}}}}public void keyTyped(KeyEvent e) {}public void keyReleased(KeyEvent e) {}public static void main(String args[]) {chessClient chessClient = new chessClient();}}。
C语言五子棋游戏源代码标准化管理处编码[BBX968T-XBB8968-NNJ668-MM9N]#define N 10void welcome();void initqipan();void showqi(int i);void save(int p);void panduan(int p);void heqi();void over();int zouqihang();int zouqilie();/******************结构体*****************/ struct zuobiao{int x[N*N];int y[N*N];}weizhi[N*N];/******************主函数*****************/ void main(){int p=0;welcome();initqipan();for(p=1;p<=N*N;p++){weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();save(p);showqi(p);panduan(p);}if(p==N*N)heqi();over();}/******************建立棋盘*****************/ void initqipan(){int i,j;for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=0;j<N;j++){if(j==0)printf("%d",i);elseprintf("·");}printf("\n");}}/******************显示棋子*****************/ void showqi(int p){int i,j,k,m;int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=N*N;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp);a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}for(m=1;m<p;m++){while(weizhi[p].x[p]==a[m]&&weizhi[p].y[p]==b[m]) {printf("error!\n");weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();m=1;}}for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=1;j<N;j++){if(j==1)printf("%d",i);for(k=1;k<=p;k++){if(i==weizhi[k].x[k]&&j==weizhi[k].y[k]) {if(k%2==1){printf("○");break;} else if(k%2==0){printf("●");break;} }}if(k>p)printf("·");else continue;}printf("\n");}}/******************走棋行*****************/ int zouqihang(){int x;printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d",&x);while(x>N-1||x<1){printf("error!\n");printf("请输入要走棋子所在行数!\n"); printf("x=");scanf("%d",&x);}return x;}/******************走棋列*****************/ int zouqilie(){int y;printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d",&y);while(y>N-1||y<1){printf("error!\n");printf("请输入要走棋子所在列数!\n"); printf("y=");scanf("%d",&y);}return y;}/******************文件保存*****************/ void save(int i){FILE *fp;fp=fopen("wuzi_list","wb");fwrite(&weizhi[i],sizeof(struct zuobiao),1,fp);}/****************判断输赢*******************/void panduan(int p){int i,j,k[8]={1,1,1,1,1,1,1,1,};int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=p;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp); a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}/*****************判断行******************/for(i=1;i<=p;i++){if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)){k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)) {k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-3)) {k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4)) {k[0]++;continue;}else if(k[0]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[0]==5)break;k[0]=1;}else if(k[0]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-3)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4)) {k[1]++;continue;}else if(k[1]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[1]==5)break;k[1]=1;}}/**********************判断列************************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[2]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])) {k[2]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])) {k[2]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])) {k[2]++;continue;}else if(k[2]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[2]==5)break;k[2]=1;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[3]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])) {k[3]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])) {k[3]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])) {k[3]++;continue;}else if(k[3]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[3]==5)break;k[3]=1;}}/****************判断对角(左上-右下)******************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[4]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)) {k[4]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)) {k[4]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)) {k[4]++;continue;}else if(k[4]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[4]==5)break;k[4]=1;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[5]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)) {k[5]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)) {k[5]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)) {k[5]++;continue;}else if(k[5]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[5]==5)break;k[5]=1;}}/**********判断对角(左下-右上)************/for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5||k[4]==5||k[5]==5) break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[6]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)) {k[6]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3)) {k[6]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4))k[6]++;continue;}else if(k[6]==5){printf("Player 1 wins!!!\n"); }elsecontinue;}if(k[6]==5)break;k[6]=1;}else if(k[6]==5)else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[7]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)) {k[7]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3))k[7]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4)) {k[7]++;continue;}else if(k[7]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[7]==5)break;k[7]=1;}}}/****************和棋*******************/void heqi(){printf("************************************\n"); printf(" Tie!!!\n");printf("************************************\n"); }/****************游戏结束*******************/void over(){printf("************************************\n"); printf(" game over!!!\n");printf("************************************\n"); }/****************游戏开始*******************/void welcome(){printf("************************************\n"); printf(" Welcome!!!\n");printf("************************************\n"); }。
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写的单机版五子棋代码,可用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语言代码#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();//这个函数用于获取一个鼠标消息。
#include<stdio.h>int hen(char a[10][10]);int shu(char a[10][10]);int xie1(char a[10][10]);int xie2(char a[10][10]);int main(){char a[10][10];int x=0,y=0;for(y=0;y<10;y++)a[x][y]=y+'0';for(x=0,y=0;x<10;x++)a[x][y]=x+'0';for(x=1;x<10;x++)for(y=1;y<10;y++)a[x][y]='*';for(x=0;x<10;x++){for(y=0;y<10;y++)printf("%3c",a[x][y]);printf("\n");}printf("------------------------------\n");while(1){while(1){printf("请@号玩家下子\n");scanf("%d.%d",&x,&y);if(a[x][y]=='@'||a[x][y]=='O')printf("棋盘上已有棋子\n"); else{a[x][y]='@';break;}}for(x=0;x<10;x++){for(y=0;y<10;y++)printf("%3c",a[x][y]);printf("\n");}printf("------------------------------\n");if(hen(a)==1||shu(a)==1||xie1(a)==1||xie2(a)==1){printf("@玩家赢\n" );break;}while(1){printf("请O号玩家下子\n");scanf("%d.%d",&x,&y);if(a[x][y]=='@'||a[x][y]=='O')printf("棋盘上已有棋子\n"); else{a[x][y]='O';break;}}for(x=0;x<10;x++){for(y=0;y<10;y++)printf("%3c",a[x][y]);printf("\n");}printf("------------------------------\n");if(hen(a)==2||shu(a)==2||xie1(a)==2||xie2(a)==2){printf("O玩家赢了\n" );break;}}return 0;}int hen(char a[10][10])//横函数{int x,y,k=0,l=0;for(x=1;x<10;x++)for(y=1;y<10;y++){if(a[x][y]=='@')k=k+1;if(y==9)k=0;if(k==5)return 1;if(a[x][y]=='O')l=l+1;if(y==9)l=0;if(l==5)return 2;}}int shu(char a[10][10])//竖函数{int x,y,k=0,l=0;for(y=1;y<10;y++)for(x=1;x<10;x++){if(a[x][y]=='@')k=k+1;if(x==9)k=0;if(k==5)return 1;if(a[x][y]=='O')l=l+1;if(x==9)l=0;if(l==5)return 2;}}int xie1(char a[10][10])//斜函数{int x,y,m,k=0,l=0;for(m=1;m<10-4;m++)for(x=1,y=m;y<10;x++,y++){if(a[x][y]=='@')k=k+1;if(x==9)k=0;if(k==5)return 1;if(a[x][y]=='O')l=l+1;if(x==9)l=0;if(l==5)return 2;}}int xie2(char a[10][10])//斜函数{int x,y,n,k=0,l=0;for(n=1;n<10-4;n++)for(y=1,x=n;x<10;x++,y++){if(a[x][y]=='@')k=k+1;if(x==9)k=0;if(k==5)return 1;if(a[x][y]=='O')l=l+1;if(x==9)l=0;if(l==5)return 2;}}。
c语言五子棋代码#include <windows.h>#define MAX 20//绘制20X20的棋盘#define TextWidth 200//棋盘右边的宽度#define ERROR 0#define NO 0#define OK 1#define DEFAULT 0#define ICO_CUR 0x1000 //预定义光标的idint leng=1;HDC hdc,hdc1,hdc2;int xw,yw;int iGame[MAX][MAX];POINT point;//鼠标点击位置enum {Default,Player1,Player2}play; enum {Stop,Play,Paush}plays;void Init(HWND hwnd);void paint(int play,int x,int y); void chagePlayer();int Look(int x,int y,int play); void over(HWND hwnd,int play); LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);char szClassName[] = "超简单的五子棋";int WINAPI WinMain (HINSTANCE hThisInstance,HINSTANCE hPrevInstance,LPSTR lpszArgument,int nFunsterStil)//主函数{HWND hwnd;MSG messages;WNDCLASSEX wincl;wincl.hInstance = hThisInstance; wincl.lpszClassName = szClassName; wincl.lpfnWndProc = WindowProcedure; wincl.style = CS_DBLCLKS;wincl.cbSize = sizeof (WNDCLASSEX);wincl.hIcon = LoadIcon(hThisInstance,MAKEINTRESOURCE(ICO_CUR));wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);wincl.hCursor = LoadCursor (NULL, IDC_ARROW);wincl.lpszMenuName = NULL; wincl.cbClsExtra = 0;wincl.cbWndExtra = 0;wincl.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);if (!RegisterClassEx (&wincl)) return 0;hwnd = CreateWindowEx (1, szClassName,szClassName,WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,800,600,HWND_DESKTOP,NULL,hThisInstance,NULL);ShowWindow (hwnd, nFunsterStil);//该函数设置指定窗口的显示状态 while (GetMessage (&messages, NULL, 0, 0)){TranslateMessage(&messages); DispatchMessage(&messages); }return messages.wParam; }LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam,LPARAM lParam) //处理窗口事件{PAINTSTRUCT ps;static HPEN hpen,hpen1,hpen2; //设备static HBRUSH hbrush,hbrush1,hbrush2; //画刷的句柄int x,y;switch (message) //消息{case WM_KEYDOWN:switch (wParam){case VK_F2: //F2重新开始游戏Init(hwnd); //初始绘制游戏界面Rectangle(hdc,0,0,xw,yw); for(x=0;x<MAX;x++) //绘制棋盘for(y=0;y<MAX;y++) {Rectangle(hdc,x*xw/MAX,y*yw/MAX,(x+1)*xw/MAX,(y+1)*yw/MAX) ;iGame[x][y]=Default; }leng=1;plays=Play;break;case VK_F1:leng=1;plays=Play;break;}break;case WM_CREATE: //初始化窗体时调用plays=Stop;play=Player1;break;case WM_SIZE:xw=LOWORD(lParam); //获取窗体的宽度 yw=HIWORD(lParam); //获取窗体的高度 //TCHAR xx[20];//wsprintf(xx,"%d",xw); //MessageBox(hwnd,xx,xx,MB_OK);xw-=TextWidth; //xw保存棋盘的宽度InvalidateRect(hwnd,NULL,TRUE);//向窗体绘制一个矩形,支持重新绘制break;case WM_LBUTTONDOWN: //响应用户鼠标左键 //获取但前鼠标坐标point.x=LOWORD(lParam); point.y=HIWORD(lParam); //初始化设备DC Init(hwnd);//鼠标坐标换为数组坐标x=(point.x)/(xw/MAX); //定位到小狂格中去y=(point.y)/(yw/MAX);if(plays==Stop)break;if(x<MAX&&y<MAX) //未超出棋盘{if(iGame[x][y]==Default&&plays==Play)//判断但前位置是否有棋子覆盖是否是下棋模式 {leng=1;paint(play,x,y);if(Look(x,y,play))over(hwnd,play);chagePlayer();}}break;case WM_PAINT://开始绘制{hdc=BeginPaint(hwnd,&ps);Init(hwnd);Rectangle(hdc,0,0,xw,yw);for(x=0;x<MAX;x++)for(y=0;y<MAX;y++){Rectangle(hdc,x*xw/MAX,y*yw/MAX,(x+1)*xw/MAX,(y+1)*yw/MAX) ;paint(iGame[x][y],x,y);}EndPaint(hwnd,&ps);}break;case WM_DESTROY: //当用户关闭游戏PostQuitMessage (0); // 发送一个消息给message queue break;default: //什么都不做return DefWindowProc (hwnd, message, wParam, lParam);}return 0;}void Init(HWND hwnd) //初始化方法{hdc1=GetDC(hwnd);hdc2=GetDC(hwnd);//初始背景 (游戏的界面)SelectObject(hdc,CreatePen(0,1,RGB(0,0,0))); //小矩形框的边框的颜色SelectObject(hdc,CreateSolidBrush(RGB(255,218,185))); //填充的颜色 //初始玩家一图形SelectObject(hdc1,CreatePen(0,1,RGB(255,255,255))); //玩家一的棋子颜色 SelectObject(hdc1,CreateSolidBrush(RGB(255,255,255))); //填充白色 //初始玩家二图形SelectObject(hdc2,CreatePen(0,1,RGB(255,255,255))); //玩家二的棋子颜色 SelectObject(hdc2,CreateSolidBrush(RGB(0,0,0))); //填充黑色 //该背景分为两层背景,一层为游戏界面(hdc),一层为玩家的棋子(hdc1,hdc2) //SetBkMode(hdc,0);该方法好像没什么用//绘制右边操作提示区域Rectangle(hdc,xw,29,xw+200,30);//从xw开始绘制到xw+200结束(绘制长200宽为30-29的矩形)的线条TextOut(hdc,xw+45,13,"超简单的五子棋",14); //从坐标(xw+45)(13)开始绘制“超简单的五子棋”宽为14TextOut(hdc,xw+45,40,"F1 - 开始游戏",13);TextOut(hdc,xw+45,60,"F2 -重新开始游戏",16);Rectangle(hdc,xw,80,xw+200,81); TextOut(hdc,xw+45,150,"白棋为第二玩家",14);TextOut(hdc,xw+45,250,"黑棋为第二玩家",14);Rectangle(hdc,xw,330,xw+200,331); }void paint(int play,int x,int y) //画棋子{switch (play){case Player1:if(iGame[x][y]!=Default){//该地方已经有棋子了}else{Ellipse(hdc1,x*xw/MAX,y*yw/MAX,(x+1)*xw/MAX,(y+1)*yw/MAX) ;//Ellipse (圆心x坐标,圆心y坐标,起始角度,终止角度,x轴半径,y轴半径) }//绘制玩家player1的棋子iGame[x][y]=Player1; //将该地方标准已经有棋子break;case Player2:if(iGame[x][y]!=Default){}else{Ellipse(hdc2,x*xw/MAX,y*yw/MAX,(x+1)*xw/MAX,(y+1)*yw/MAX) ;}//绘制玩家player2的棋子iGame[x][y]=Player2; //将该地方标准已经有棋子break;}}void chagePlayer() //改变玩家{if(play==Player1) play=Player2; elseplay=Player1;}int Look(int x,int y,int play) // 检查模块{int i,tempx,tempy;tempx=x;tempy=y;for(i=0;i<5&&iGame[tempx][tempy]==play;tempy--,i++); if(i>=5) return OK; //向上核对(y轴)tempx=x;tempy=y;for(i=0;i<5&&iGame[tempx][tempy]==play;tempy++,i++); if(i>=5) return OK; //向下核对(y轴)tempx=x;tempy=y;for(i=0;i<5&&iGame[tempx][tempy]==play;tempx--,i++); if(i>=5) return OK; //向左核对(x轴)tempx=x;tempy=y;for(i=0;i<5&&iGame[tempx][tempy]==play;tempx++,i++); if(i>=5) return OK; //向右核对(y轴)tempx=x;tempy=y;for(i=0;i<5&&iGame[tempx][tempy]==play;tempx--,tempy--,i++); if(i>=5) return OK; //向左上核对(x,y轴的对角线向上\)tempx=x;tempy=y;for(i=0;i<5&&iGame[tempx][tempy]==play;tempx++,tempy--,i++); if(i>=5) return OK; //向右上核对(x,y轴的对角线向下\)tempx=x;tempy=y;for(i=0;i<5&&iGame[tempx][tempy]==play;tempx--,tempy++,i++); if(i>=5) return OK; //向左下核对(x,y轴的对角线向上/)tempx=x;tempy=y;for(i=0;i<5&&iGame[tempx][tempy]==play;tempx++,tempy++,i++); if(i>=5) return OK; //向右下核对(x,y轴的对角线向上/)return NO;}void over(HWND hwnd,int play) //判断胜负{switch(play){case Player1:MessageBox(hwnd,"恭喜白棋玩家获得胜利","胜利",0);SendMessage(hwnd,WM_KEYDOWN,VK_F2,NULL); //重新开始游戏 plays=Stop;break;case Player2:MessageBox(hwnd,"恭喜黑棋玩家获得胜利","胜利",0);SendMessage(hwnd,WM_KEYDOWN,VK_F2,NULL);plays=Stop;break;}}最终效果图:。
#include <stdio.h>#include <stdlib.h>#define m 30int main (void){int count;//计数器算横纵行的结果int w,h;int u;int l;int i,size;//i声明步数。
size声明int r[m][m] = {0};//数组声明(棋子位置)int x, y;//声明落子坐标int n;//声明棋盘大小nchar a[20],b[20];printf ("请输入棋盘大小n\n");//编辑棋盘直到棋盘长度宽度大于4小于30 scanf ("%d", &n);if (n<=4 || n>m){do{printf ("输入的棋盘大小:4<n<%d\n", m);scanf ("%d", &n);}while (n<=4 || n>m);}getchar ();//声明玩家printf ("请输入玩家1姓名:\n");gets(a);printf ("请输入玩家2姓名:\n");gets(b);for ( i = 1, size = n*n;i <= size; i++)//编辑棋盘{if (i%2 == 1)//如果i能被2整除,为玩家a相关信息{do//玩家a棋子信息{printf ("%s该你下棋了,第%d个棋子\n", a, i);scanf ("%d%d", &x, &y);if (x > n || x < 0)//判断坐标是否在棋盘内,如果不是则重新输入{do{printf ("0<=横坐标<=%d请重新输入横坐标\n", n);scanf ("%d", &x);}while (x>m || x<0);}if (y > n || y < 0)//判断坐标是否在棋盘内,如果不是则重新输入{do{printf ("0<=纵坐标<=%d请重新输入纵坐标\n", n);scanf ("%d", &y);}while (y < 0 || y > n);}}while ((r[x][y] == 1 && (printf ("这个位置上已经有棋子了,请重新输入\n")))|| r[x][y] == 2&& (printf ("这个位置上已经有棋子了,请重新输入\n")) );r[x][y] = 1;for (u = 0;u < n; u++)//不同情况下判断玩家a获胜方式{for (l = 0;l < n;l++){count = 0;for (w = u,h = l;r[w][h] == 1 && h < n; h++)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;//直接跳转,其余代码不在运行count = 0;for (w = u, h = l; r[w][h] == 1 && w < n; w++)count ++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}count = 0;for (w = u,h = l; r[w][h] == 1 && w < n && h<n;w++,h++)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}count = 0;for (w =u ,h =l;r[w][h] == 1 && h > 0;h--)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}}}}system("cls");for (int j = n;j>=0;j--){printf ("%-2d", j);for (int k = 0;k < n;k++)//画棋盘,声明两玩家棋子图片{if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●"); }printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k);}else if (i%2 == 0)//如果i不能被2整除,为玩家b相关信息{do{printf ("\n%s该你下棋了,第%d个棋子\n", b, i);scanf ("%d%d", &x, &y);if (x > n || x < 0){do{printf ("0<=横坐标<=%d请重新输入横坐标\n", n);scanf ("%d", &x);}while (x>n || x<0);}if (y >n|| y < 0){do{printf ("0<=纵坐标<=%d请重新输入纵坐标\n", n);scanf ("%d", &y);}while (y < 0 || y > n);}}while ((r[x][y] == 1 && (printf ("这个位置上已经有棋子了,请重新输入\n")))|| r[x][y] == 2&& (printf ("这个位置上已经有棋子了,请重新输入\n")) );r[x][y] = 2;system("cls");for (int j = n;j>=0;j--){printf ("%-2d", j);for (int k = 0;k < n;k++){if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●");}printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k); printf ("\n");count = 0;for (u = 0;u < n; u++){for (l = 0;l < n;l++){count = 0;for (w = u,h = l;r[w][h] == 2 && h < n; h++)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w = u, h = l; r[w][h] == 2 && w < n; w++)count ++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w = u,h = l; r[w][h] == 2 && w < n && h<n;w++,h++)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w =u ,h =l;r[w][h] == 2 && h > 0;h--)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}}}}}e: for (int j = n;j>=0;j--)//游戏结束界面棋盘固定重新显示{printf ("%-2d", j);for (int k = 0;k < n;k++){if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●");}printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k); printf ("\n");printf ("\a游戏愉快,Powered by Techmessager\n");//结束语句return 0;}。
package org;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Toolkit;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import javax.swing.JFrame;import javax.swing.JOptionPane;public class FiveChess extends JFrame implements MouseListener, Runnable { // 背景图片BufferedImage bgImage = null;// 保存棋子坐標int x = 0;int y = 0;// 用數組來表示所有下過的棋子// 其內容數據:0--表示沒有棋子、1--表示黑子、2--表示白子int[][] allChess = new int[19][19];// 标识下一步棋子的颜色boolean isBlack = true;// 标识游戏是否结束boolean canPlay = false;// 创建游戏信息标识String gameMessage = "黑方先行";// 创建黑白双方的游戏时间信息String blackTimeMessage = "无限制";String whiteTimeMessage = "无限制";// 保存游戲最大時間(秒)int maxTime = 0;// 保存黑白雙方游戲時間int blackTime = 0;int whiteTime = 0;// 保存黑白雙方游戲時間信息String blackMessage = "無限制";String whiteMessage = "無限制";// 創建線程,用來建立倒計時Thread t = new Thread(this);public FiveChess() {this.setTitle("五子棋");this.setSize(500, 500);this.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - 500) / 2,(Toolkit.getDefaultToolkit().getScreenSize().height - 500) / 2);this.setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);// 实例化背景图片try {bgImage = ImageIO.read(new File("F:" + File.separator + "image"+ File.separator + "background.jpg"));} catch (IOException e) {e.printStackTrace();}// 加入鼠标监听this.addMouseListener(this);t.start();// 啟動線程t.suspend();//掛起線程this.repaint();// 刷新屏幕}public void paint(Graphics g) {// 利用双缓冲技术,防止点击时屏幕闪烁。
//Java编程:五子棋游戏源代码import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;import java.io.PrintStream;import javax.swing.JComponent;import javax.swing.JPanel;/**main方法创建了ChessFrame类的一个实例对象(cf),*并启动屏幕显示显示该实例对象。
**/public class FiveChessAppletDemo {public static void main(String args[]){ChessFrame cf = new ChessFrame();cf.show();}}/**类ChessFrame主要功能是创建五子棋游戏主窗体和菜单**/class ChessFrame extends JFrame implements ActionListener { private String[] strsize={"20x15","30x20","40x30"};private String[] strmode={"人机对弈","人人对弈"};public static boolean iscomputer=true,checkcomputer=true; private int width,height;private ChessModel cm;private MainPanel mp;//构造五子棋游戏的主窗体public ChessFrame() {this.setTitle("五子棋游戏");cm=new ChessModel(1);mp=new MainPanel(cm);Container con=this.getContentPane();con.add(mp,"Center");this.setResizable(false);this.addWindowListener(new ChessWindowEvent());MapSize(20,15);JMenuBar mbar = new JMenuBar();this.setJMenuBar(mbar);JMenu gameMenu = new JMenu("游戏");mbar.add(makeMenu(gameMenu, new Object[] {"开局", "棋盘","模式", null, "退出"}, this));JMenu lookMenu =new JMenu("视图");mbar.add(makeMenu(lookMenu,new Object[] {"Metal","Motif","Windows"},this));JMenu helpMenu = new JMenu("帮助");mbar.add(makeMenu(helpMenu, new Object[] {"关于"}, this));}//构造五子棋游戏的主菜单public JMenu makeMenu(Object parent, Object items[], Object target){ JMenu m = null;if(parent instanceof JMenu)m = (JMenu)parent;else if(parent instanceof String)m = new JMenu((String)parent);elsereturn null;for(int i = 0; i < items.length; i++)if(items[i] == null)m.addSeparator();else if(items[i] == "棋盘"){JMenu jm = new JMenu("棋盘");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int j=0;j<strsize.length;j++){rmenu=makeRadioButtonMenuItem(strsize[j],target);if (j==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}else if(items[i] == "模式"){JMenu jm = new JMenu("模式");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int h=0;h<strmode.length;h++){rmenu=makeRadioButtonMenuItem(strmode[h],target);if(h==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}elsem.add(makeMenuItem(items[i], target));return m;}//构造五子棋游戏的菜单项public JMenuItem makeMenuItem(Object item, Object target){ JMenuItem r = null;if(item instanceof String)r = new JMenuItem((String)item);else if(item instanceof JMenuItem)r = (JMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}//构造五子棋游戏的单选按钮式菜单项public JRadioButtonMenuItem makeRadioButtonMenuItem( Object item, Object target){JRadioButtonMenuItem r = null;if(item instanceof String)r = new JRadioButtonMenuItem((String)item);else if(item instanceof JRadioButtonMenuItem)r = (JRadioButtonMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}public void MapSize(int w,int h){setSize(w * 20+50 , h * 20+100 );if(this.checkcomputer)this.iscomputer=true;elsethis.iscomputer=false;mp.setModel(cm);mp.repaint();}public boolean getiscomputer(){return this.iscomputer;}public void restart(){int modeChess = cm.getModeChess();if(modeChess <= 3 && modeChess >= 1){cm = new ChessModel(modeChess);MapSize(cm.getWidth(),cm.getHeight());}else{System.out.println("\u81EA\u5B9A\u4E49");}}public void actionPerformed(ActionEvent e){String arg=e.getActionCommand();try{if (arg.equals("Windows"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");else if(arg.equals("Motif"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");elseUIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel" ); SwingUtilities.updateComponentTreeUI(this);}catch(Exception ee){}if(arg.equals("20x15")){this.width=20;this.height=15;cm=new ChessModel(1);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("30x20")){this.width=30;this.height=20;cm=new ChessModel(2);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("40x30")){this.width=40;this.height=30;cm=new ChessModel(3);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人机对弈")){this.checkcomputer=true;this.iscomputer=true;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人人对弈")){this.checkcomputer=false;this.iscomputer=false;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("开局")){restart();}if(arg.equals("关于"))JOptionPane.showMessageDialog(this, "五子棋游戏测试版本", "关于", 0);if(arg.equals("退出"))System.exit(0);}}/**类ChessModel实现了整个五子棋程序算法的核心*/class ChessModel {//棋盘的宽度、高度、棋盘的模式(如20×15)private int width,height,modeChess;//棋盘方格的横向、纵向坐标private int x=0,y=0;//棋盘方格的横向、纵向坐标所对应的棋子颜色,//数组arrMapShow只有3个值:1,2,3,-5,//其中1代表该棋盘方格上下的棋子为黑子,//2代表该棋盘方格上下的棋子为白子,//3代表为该棋盘方格上没有棋子,//-5代表该棋盘方格不能够下棋子private int[][] arrMapShow;//交换棋手的标识,棋盘方格上是否有棋子的标识符private boolean isOdd,isExist;public ChessModel() {}//该构造方法根据不同的棋盘模式(modeChess)来构建对应大小的棋盘public ChessModel(int modeChess){this.isOdd=true;if(modeChess == 1){PanelInit(20, 15, modeChess);}if(modeChess == 2){PanelInit(30, 20, modeChess);}if(modeChess == 3){PanelInit(40, 30, modeChess);}}//按照棋盘模式构建棋盘大小private void PanelInit(int width, int height, int modeChess){this.width = width;this.height = height;this.modeChess = modeChess;arrMapShow = new int[width+1][height+1];for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){arrMapShow[i][j] = -5;}}}//获取是否交换棋手的标识符public boolean getisOdd(){return this.isOdd;}//设置交换棋手的标识符public void setisOdd(boolean isodd){if(isodd)this.isOdd=true;elsethis.isOdd=false;}//获取某棋盘方格是否有棋子的标识值public boolean getisExist(){return this.isExist;}//获取棋盘宽度public int getWidth(){return this.width;}//获取棋盘高度public int getHeight(){return this.height;}//获取棋盘模式public int getModeChess(){return this.modeChess;}//获取棋盘方格上棋子的信息public int[][] getarrMapShow(){return arrMapShow;}//判断下子的横向、纵向坐标是否越界private boolean badxy(int x, int y){if(x >= width+20 || x < 0)return true;return y >= height+20 || y < 0;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public boolean chessExist(int i,int j){if(this.arrMapShow[i][j]==1 || this.arrMapShow[i][j]==2)return true;return false;}//判断该坐标位置是否可下棋子public void readyplay(int x,int y){if(badxy(x,y))return;if (chessExist(x,y))return;this.arrMapShow[x][y]=3;}//在该坐标位置下棋子public void play(int x,int y){if(badxy(x,y))return;if(chessExist(x,y)){this.isExist=true;return;}elsethis.isExist=false;if(getisOdd()){setisOdd(false);this.arrMapShow[x][y]=1;}else{setisOdd(true);this.arrMapShow[x][y]=2;}}//计算机走棋/**说明:用穷举法判断每一个坐标点的四个方向的的最大棋子数,*最后得出棋子数最大值的坐标,下子**/public void computerDo(int width,int height){int max_black,max_white,max_temp,max=0;setisOdd(true);System.out.println("计算机走棋...");for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){if(!chessExist(i,j)){//算法判断是否下子max_white=checkMax(i,j,2);//判断白子的最大值max_black=checkMax(i,j,1);//判断黑子的最大值max_temp=Math.max(max_white,max_black);if(max_temp>max){max=max_temp;this.x=i;this.y=j;}}}}setX(this.x);setY(this.y);this.arrMapShow[this.x][this.y]=2;}//记录电脑下子后的横向坐标public void setX(int x){this.x=x;}//记录电脑下子后的纵向坐标public void setY(int y){this.y=y;}//获取电脑下子的横向坐标public int getX(){return this.x;}//获取电脑下子的纵向坐标public int getY(){return this.y;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public int checkMax(int x, int y,int black_or_white){int num=0,max_num,max_temp=0;int x_temp=x,y_temp=y;int x_temp1=x_temp,y_temp1=y_temp;//judge rightfor(int i=1;i<5;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge leftx_temp1=x_temp;for(int i=1;i<5;i++){x_temp1-=1;if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num<5)max_temp=num;//judge upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge downy_temp1=y_temp;for(int i=1;i<5;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge left_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1-=1;y_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge right_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge right_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge left_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;max_num=max_temp;return max_num;}//判断胜负public boolean judgeSuccess(int x,int y,boolean isodd){ int num=1;int arrvalue;int x_temp=x,y_temp=y;if(isodd)arrvalue=2;elsearrvalue=1;int x_temp1=x_temp,y_temp1=y_temp;//判断右边for(int i=1;i<6;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}//判断左边x_temp1=x_temp;for(int i=1;i<6;i++){if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断上方x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断下方y_temp1=y_temp;for(int i=1;i<6;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断左上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断右下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width) break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断右上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断左下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}if(num==5)return true;return false;}//赢棋后的提示public void showSuccess(JPanel jp){JOptionPane.showMessageDialog(jp,"你赢了,好厉害!","win",RMATION_MESSAGE);}//输棋后的提示public void showDefeat(JPanel jp){JOptionPane.showMessageDialog(jp,"你输了,请重新开始!","lost",RMATION_MESSAGE);}}/**类MainPanel主要完成如下功能:*1、构建一个面板,在该面板上画上棋盘;*2、处理在该棋盘上的鼠标事件(如鼠标左键点击、鼠标右键点击、鼠标拖动等)**/class MainPanel extends JPanelimplements MouseListener,MouseMotionListener{private int width,height;//棋盘的宽度和高度private ChessModel cm;//根据棋盘模式设定面板的大小MainPanel(ChessModel mm){cm=mm;width=cm.getWidth();height=cm.getHeight();addMouseListener(this);}//根据棋盘模式设定棋盘的宽度和高度public void setModel(ChessModel mm){cm = mm;width = cm.getWidth();height = cm.getHeight();}//根据坐标计算出棋盘方格棋子的信息(如白子还是黑子),//然后调用draw方法在棋盘上画出相应的棋子public void paintComponent(Graphics g){super.paintComponent(g);for(int j = 0; j <= height; j++){for(int i = 0; i <= width; i++){int v = cm.getarrMapShow()[i][j];draw(g, i, j, v);}}}//根据提供的棋子信息(颜色、坐标)画棋子public void draw(Graphics g, int i, int j, int v){int x = 20 * i+20;int y = 20 * j+20;//画棋盘if(i!=width && j!=height){g.setColor(Color.white);g.drawRect(x,y,20,20);}//画黑色棋子if(v == 1 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.black);g.fillOval(x-8,y-8,16,16);}//画白色棋子if(v == 2 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.white);g.fillOval(x-8,y-8,16,16);}if(v ==3){g.setColor(Color.cyan);g.drawOval(x-8,y-8,16,16);}}//响应鼠标的点击事件,根据鼠标的点击来下棋,//根据下棋判断胜负等public void mousePressed(MouseEvent evt){int x = (evt.getX()-10) / 20;int y = (evt.getY()-10) / 20;System.out.println(x+" "+y);if (evt.getModifiers()==MouseEvent.BUTTON1_MASK){cm.play(x,y);System.out.println(cm.getisOdd()+" "+cm.getarrMapShow()[x][y]);repaint();if(cm.judgeSuccess(x,y,cm.getisOdd())){cm.showSuccess(this);evt.consume();ChessFrame.iscomputer=false;}//判断是否为人机对弈if(ChessFrame.iscomputer&&!cm.getisExist()){puterDo(cm.getWidth(),cm.getHeight());repaint();if(cm.judgeSuccess(cm.getX(),cm.getY(),cm.getisOdd())){cm.showDefeat(this);evt.consume();}}}}public void mouseClicked(MouseEvent evt){}public void mouseReleased(MouseEvent evt){}public void mouseEntered(MouseEvent mouseevt){}public void mouseExited(MouseEvent mouseevent){}public void mouseDragged(MouseEvent evt){}//响应鼠标的拖动事件public void mouseMoved(MouseEvent moveevt){int x = (moveevt.getX()-10) / 20;int y = (moveevt.getY()-10) / 20;cm.readyplay(x,y);repaint();}}class ChessWindowEvent extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0);}ChessWindowEvent(){}}。
Python五子棋游戏代码五子棋游戏涉及到的内容较多,这里给出一个简化版的五子棋游戏实现。
首先需要安装pygame库,可以使用以下命令安装:bashpip install pygame接下来是五子棋游戏的代码:import pygameimport sys# 初始化pygamepygame.init()# 设置屏幕大小screen_size = (600, 600)screen = pygame.display.set_mode(screen_size)# 设置颜色white = (255, 255, 255)black = (0, 0, 0)# 加载棋盘图片board_image = pygame.image.load("board.png")# 设置棋盘大小board_size = board_image.get_rect().size# 设置棋盘坐标def get_position(x, y):return x * board_size[0], y * board_size[1]# 绘制棋盘def draw_board():for x in range(15):for y in range(15):rect = get_position(x, y)screen.blit(board_image, rect)pygame.draw.line(screen, black, get_position(x, y), get_position((x + 1) % 15, y), 2)pygame.draw.line(screen, black, get_position(x, y), get_position((x - 1) % 15, y), 2)# 主循环player = 1while True:for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()elif event.type == pygame.MOUSEBUTTONDOWN:x, y = event.posx, y = x // board_size[0], y // board_size[1]if board_image.get_at((x, y)) == (0, 0, 0):if player == 1:player = 2else:player = 1screen.fill(white)draw_board()pygame.display.flip()注意:这个示例需要你提供一张名为"board.png"的棋盘图片。
C语言游戏之五子棋源代码#include<stdio.h>#include<stdlib.h>#include<graphics.h>#include<bios.h>#include<conio.h>#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011b#define SPACE 0x3920#define BILI 20#define JZ 4#define JS 3#define N 19int box[N][N];int step_x,step_y ;int key ;int flag=1 ;void draw_box();void draw_cicle(int x,int y,int color); void change();void judgewho(int x,int y);void judgekey();int judgeresult(int x,int y);void attentoin();void attention(){char ch ;window(1,1,80,25);textbackground(LIGHTBLUE);textcolor(YELLOW);clrscr();gotoxy(15,2);printf("游戏操作规则:");gotoxy(15,4);printf("Play Rules:");gotoxy(15,6);printf("1、按左右上下方向键移动棋子");gotoxy(15,8);printf("1. Press Left,Right,Up,Down Key to move Piece");gotoxy(15,10);printf("2、按空格确定落棋子");gotoxy(15,12);printf("2. Press Space to place the Piece");gotoxy(15,14);printf("3、禁止在棋盘外按空格");gotoxy(15,16);printf("3. DO NOT press Space outside of the chessboard");gotoxy(15,18);printf("你是否接受上述的游戏规则(Y/N)");gotoxy(15,20);printf("Do you accept the above Playing Rules? [Y/N]:");while(1){gotoxy(60,20);ch=getche();if(ch=='Y'||ch=='y')break ;else if(ch=='N'||ch=='n'){window(1,1,80,25);textbackground(BLACK);textcolor(LIGHTGRAY);clrscr();exit(0);}gotoxy(51,12);printf(" ");}}void draw_box(){int x1,x2,y1,y2 ;setbkcolor(LIGHTBLUE);setcolor(YELLOW);gotoxy(7,2);printf("Left, Right, Up, Down KEY to move, Space to put, ESC-quit.");for(x1=1,y1=1,y2=18;x1<=18;x1++) line((x1+JZ)*BILI,(y1+JS)*BILI,(x 1+JZ)*BILI,(y2+JS)*BILI);for(x1=1,y1=1,x2=18;y1<=18;y1++) line((x1+JZ)*BILI,(y1+JS)*BILI,(x 2+JZ)*BILI,(y1+JS)*BILI);for(x1=1;x1<=18;x1++)for(y1=1;y1<=18;y1++)box[x1][y1]=0 ;}void draw_circle(int x,int y,int color) {setcolor(color);setlinestyle(SOLID_LINE,0,1);x=(x+JZ)*BILI ;y=(y+JS)*BILI ;circle(x,y,8);}void judgekey(){int i ;int j ;switch(key){case LEFT :if(step_x-1<0)break ;else{for(i=step_x-1,j=step_y;i>=1;i --)if(box[i][j]==0){draw_circle(step_x,step_y,LIGHTBLU E);break ;}if(i<1)break ;step_x=i ;judgewho(step_x,step_y);break ;}case RIGHT :if(step_x+1>18)break ;else{for(i=step_x+1,j=step_y;i<=18 ;i++)if(box[i][j]==0){draw_circle(step_x,step_y,LIGH TBLUE);break ;}if(i>18)break ;step_x=i ;judgewho(step_x,step_y);break ;}case DOWN :if((step_y+1)>18)break ;else{for(i=step_x,j=step_y+1;j<=18 ;j++)if(box[i][j]==0){draw_circle(step_x,step_y,LIGHTBLU E);break ;}if(j>18)break ;step_y=j ;judgewho(step_x,step_y);break ;}case UP :if((step_y-1)<0)break ;else{for(i=step_x,j=step_y-1;j>=1;j --)if(box[i][j]==0){draw_circle(step_x,step_y,LIGHTBLU E);break ;}if(j<1)break ;step_y=j ;judgewho(step_x,step_y);break ;}case ESC :break ;case SPACE :if(step_x>=1&&step_x<=18&&s tep_y>=1&&step_y<=18){if(box[step_x][step_y]==0){box[step_x][step_y]=flag ; if(judgeresult(step_x,step_y)==1){sound(1000);delay(1000);nosound();gotoxy(30,4);if(flag==1){setbkcolor(BLUE);cleardevice(); setviewport(100,100,540,380,1);/*定义一个图形窗口*/setfillstyle(1,2);/*绿色以实填充*/setcolor(YELLOW);rectangle(0,0,439,279);floodfill(50,50,14);setcolor(12);settextstyle(1,0,5);/*三重笔划字体, 水平放?5倍*/ outtextxy(20,20,"The White Win !");setcolor(15);settextstyle(3,0,5);*无衬笔划字体, 水平放大5倍*/ uttextxy(120,120,"The White Win !");setcolor(14);settextstyle(2,0,8);getch();closegraph();exit(0);}if(flag==2){setbkcolor(BLUE);cleardevice();setviewport(100,100,540,380,1);/*定义一个图形窗口*/setfillstyle(1,2);/*绿色以实填充*/setcolor(YELLOW);rectangle(0,0,439,279);floodfill(50,50,14);setcolor(12);settextstyle(1,0,8);笔划字体, 水平放大8倍*/ outtextxy(20,20,"The Red Win !");setcolor(15);settextstyle(3,0,5);/*无衬笔划字体, 水平放大5倍*/outtextxy(120,120,"The Red Win !");setcolor(14);settextstyle(2,0,8);getch();closegraph();exit(0);}}change();break ;}}elsebreak ;}}void change(){if(flag==1)flag=2 ;elseflag=1 ;}void judgewho(int x,int y){if(flag==1)draw_circle(x,y,15);if(flag==2)draw_circle(x,y,4);}int judgeresult(int x,int y){ int j,k,n1,n2 ;while(1){ n1=0 ;n2=0 ;/*水平向左数*/for(j=x,k=y;j>=1;j--){ if(box[j][k]==flag)n1++;elsebreak ;}/*水平向右数*/for(j=x,k=y;j<=18;j++) {if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){return(1);break ;}/*垂直向上数*/n1=0 ;n2=0 ;for(j=x,k=y;k>=1;k--) {if(box[j][k]==flag)n1++;elsebreak ;}/*垂直向下数*/for(j=x,k=y;k<=18;k++) {if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){return(1);break ;}/*向左上方数*/n1=0 ;n2=0 ;for(j=x,k=y;j>=1,k>=1;j--,k--){if(box[j][k]==flag)n1++;elsebreak ;}/*向右下方数*/for(j=x,k=y;j<=18,k<=18;j++,k+ +){if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){return(1);break ;}/*向右上方数*/n1=0 ;n2=0 ;for(j=x,k=y;j<=18,k>=1;j++,k--){if(box[j][k]==flag)n1++;elsebreak ;}/*向左下方数*/for(j=x,k=y;j>=1,k<=18;j--,k++){if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){ return(1);break ;}return(0);break ;} }void main(){int gdriver=VGA,gmode=VGAHI;clrscr();attention();initgraph(&gdriver,&gmode,"c:\\tc" );/* setwritemode(XOR_PUT);*/flag=1 ;draw_box();do{step_x=0 ;step_y=0 ;/*draw_circle(step_x,step_y,8); */judgewho(step_x-1,step_y-1);do{while(bioskey(1)==0);key=bioskey(0);judgekey();}while(key!=SPACE&&key!=ESC);}while(key!=ESC);closegraph();}。
i n c l u d e<> define N 10void welcome;void initqipan;void showqiint i;void saveint p;void panduanint p;void heqi;void over;int zouqihang;int zouqilie;/结构体/struct zuobiao{int xNN;int yNN;}weizhiNN;/主函数/void main{int p=0;welcome;initqipan;forp=1;p<=NN;p++{weizhip.xp=zouqihang; weizhip.yp=zouqilie; savep;showqip;panduanp;}ifp==NNheqi;over;}/建立棋盘/void initqipan{int i,j;fori=0;i<N;i++{printf"%d",i;printf" ";}printf"\n";fori=1;i<N;i++{forj=0;j<N;j++{ifj==0printf"%d",i; elseprintf"·";}printf"\n";}}/显示棋子/void showqiint p{int i,j,k,m;int aNN,bNN;FILE fp;fp=fopen"wuzi_list","rb";fori=1;i<=NN;i++{fread&weizhii,sizeofstruct zuobiao,1,fp; ai=weizhii.xi;bi=weizhii.yi;}form=1;m<p;m++{whileweizhip.xp==am&&weizhip.yp==bm{printf"error\n";weizhip.xp=zouqihang;weizhip.yp=zouqilie;m=1;}}fori=0;i<N;i++{printf"%d",i;printf" ";}printf"\n";fori=1;i<N;i++{forj=1;j<N;j++{ifj==1printf"%d",i;fork=1;k<=p;k++{ifi==weizhik.xk&&j==weizhik.yk {ifk%2==1{printf"○";break;}else ifk%2==0{printf"●";break;}}}ifk>pprintf"·";else continue;}printf"\n";}}/走棋行/int zouqihang{int x;printf"请输入要走棋子所在行数\n";printf"x=";scanf"%d",&x;whilex>N-1||x<1{printf"error\n";printf"请输入要走棋子所在行数\n"; printf"x=";scanf"%d",&x;}return x;}/走棋列/int zouqilie{int y;printf"请输入要走棋子所在列数\n";printf"y=";scanf"%d",&y;whiley>N-1||y<1{printf"error\n";printf"请输入要走棋子所在列数\n";printf"y=";scanf"%d",&y;}return y;}/文件保存/void saveint i{FILE fp;fp=fopen"wuzi_list","wb";fwrite&weizhii,sizeofstruct zuobiao,1,fp; }/判断输赢/void panduanint p{int i,j,k8={1,1,1,1,1,1,1,1,};int aNN,bNN;FILE fp;fp=fopen"wuzi_list","rb";fori=1;i<=p;i++{fread&weizhii,sizeofstruct zuobiao,1,fp; ai=weizhii.xi;bi=weizhii.yi;}/判断行/fori=1;i<=p;i++{ifi%2==1{forj=1;j<=p;j=j+2{ifai==aj&&bi==bj-1{k0++;continue;}else ifai==aj&&bi==bj-2{k0++;continue;}else ifai==aj&&bi==bj-3{k0++;continue;}else ifai==aj&&bi==bj-4{k0++;continue;}else ifk0==5{printf"Player 1 wins\n"; }elsecontinue;}ifk0==5break;k0=1;}else ifk0==5break;else ifi%2==0{forj=2;j<=p;j=j+2{ifai==aj&&bi==bj-1{k1++;continue;}else ifai==aj&&bi==bj-2 {k1++;continue;}else ifai==aj&&bi==bj-3 {k1++;continue;}else ifai==aj&&bi==bj-4{k1++;continue;}else ifk1==5{printf"Player 2 wins\n"; }elsecontinue;}ifk1==5break;k1=1;}}/判断列/fori=1;i<=p;i++{ifk0==5||k1==5break;else ifi%2==1{forj=1;j<=p;j=j+2{ifai==aj-1&&bi==bj{k2++;continue;}else ifai==aj-2&&bi==bj {k2++;continue;}else ifai==aj-3&&bi==bj {k2++;continue;}else ifai==aj-4&&bi==bj {k2++;continue;else ifk2==5{printf"Player 1 wins\n"; }elsecontinue;}ifk2==5break;k2=1;}else ifk2==5break;else ifi%2==0{forj=2;j<=p;j=j+2{ifai==aj-1&&bi==bj{k3++;continue;else ifai==aj-2&&bi==bj{k3++;continue;}else ifai==aj-3&&bi==bj{k3++;continue;}else ifai==aj-4&&bi==bj{k3++;continue;}else ifk3==5{printf"Player 2 wins\n"; }elsecontinue;}ifk3==5break;k3=1;}}/判断对角左上-右下/fori=1;i<=p;i++{ifk0==5||k1==5||k2==5||k3==5break;else ifi%2==1{forj=1;j<=p;j=j+2{ifai==aj-1&&bi==bj-1{k4++;continue;}else ifai==aj-2&&bi==bj-2 {k4++;continue;}else ifai==aj-3&&bi==bj-3{k4++;continue;}else ifai==aj-4&&bi==bj-4{k4++;continue;}else ifk4==5{printf"Player 1 wins\n"; }elsecontinue;}ifk4==5break;}else ifk2==5break;else ifi%2==0{forj=2;j<=p;j=j+2{ifai==aj-1&&bi==bj-1{k5++;continue;}else ifai==aj-2&&bi==bj-2 {k5++;continue;}else ifai==aj-3&&bi==bj-3 {k5++;continue;else ifai==aj-4&&bi==bj-4{k5++;continue;}else ifk5==5{printf"Player 2 wins\n";}elsecontinue;}ifk5==5break;k5=1;}}/判断对角左下-右上/fori=1;i<=p;i++{ifk0==5||k1==5||k2==5||k3==5||k4==5||k5==5else ifi%2==1{forj=1;j<=p;j=j+2{ifai==aj+1&&bi==bj-1{k6++;continue;}else ifai==aj+2&&bi==bj-2 {k6++;continue;}else ifai==aj+3&&bi==bj-3 {k6++;continue;}else ifai==aj+4&&bi==bj-4 {k6++;continue;}else ifk6==5{printf"Player 1 wins\n"; }elsecontinue;}ifk6==5break;k6=1;}else ifk6==5break;else ifi%2==0{forj=2;j<=p;j=j+2{ifai==aj+1&&bi==bj-1{k7++;continue;}else ifai==aj+2&&bi==bj-2{k7++;continue;}else ifai==aj+3&&bi==bj-3{k7++;continue;}else ifai==aj+4&&bi==bj-4{k7++;continue;}else ifk7==5{printf"Player 2 wins\n"; }elsecontinue;}ifk7==5break;k7=1;}}}/和棋/void heqi{printf"\n";printf" Tie\n";printf"\n";}/游戏结束/void over{printf"\n";printf" game over\n"; printf"\n";}/游戏开始/void welcome{printf"\n";printf" Welcome\n"; printf"\n";}。