五子棋小游戏代码(c语言编的五子棋源代码)
本文目录
- c语言编的五子棋源代码
- 求五子棋C源代码
- 如何用C++编写五子棋
- 用JAVA做五子棋源代码
- 求五子棋Java代码旁边就注释 让我看的清楚明白一些,要详细的解释和思路
- 急需基于eclipse的JAVA小游戏源代码!!!
- 请帮忙分析一下java五子棋中的这段源代码
- 怎么Java实现鼠标点击的五子棋啊 各位大侠 帮帮忙
- 急需用eclipse写的小游戏代码 比如贪吃蛇,五子棋,猜数字,俄罗斯方块等的小游戏代码
- 用eclipse编写一个基于java的五子棋(与电脑对弈)
c语言编的五子棋源代码
#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;/*用于记录棋盘上各点的状态*//**********************************************************//**********************************************************//*主函数*/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=CHESSNULL; /*光标初始位置*/ gCursor.x=gCursor.y=0; /*画棋盘*/ textmode(C40); DrawMap(); /*显示操作键说明*/ i=0; textcolor(BROWN); while(Msg!=NULL) { gotoxy(25,3+i); cputs(Msg); 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==CHESS1) { textcolor(LIGHTBLUE); putch(CHESS1); return; } /*交叉点上是二号玩家的棋子*/ if(gChessBoard==CHESS2) { textcolor(LIGHTBLUE); 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; else gPlayOrder=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!"); else cputs("PLAYER2 WIN!"); gotoxy(25,21); cputs("\n"); getch();}/*走棋*/int ChessGo(int Order,struct point Cursor){ /*判断交叉点上有无棋子*/ if(gChessBoard==CHESSNULL) { /*若没有棋子, 则可以落子*/ gotoxy(Cursor.x+MAPXOFT,Cursor.y+MAPYOFT); textcolor(LIGHTBLUE); putch(Order); gotoxy(Cursor.x+MAPXOFT,Cursor.y+MAPYOFT); gChessBoard=Order; return TRUE; } else return 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==Order) { count++; if(count》=testnum) return TRUE; } else count=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!"); else cputs("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;/*是退出键*/ else if ( ( press==PLAY1DO && gPlayOrder==CHESS1) || ( press==PLAY2DO && gPlayOrder==CHESS2) ) return KEYFALLCHESS;/*是落子键*/ else if ( press==PLAY1UP || press==PLAY1DOWN || press==PLAY1LEFT || press==PLAY1RIGHT || press==PLAY2UP || press==PLAY2DOWN || press==PLAY2LEFT || press==PLAY2RIGHT ) return KEYMOVECURSOR;/*是光标移动键*/ else return KEYINVALID;/*按键无效*/}
求五子棋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 19 int box; 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? :"); 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,(x1+JZ)*BILI,(y2+JS)*BILI); for(x1=1,y1=1,x2=18;y1《=18;y1++) line((x1+JZ)*BILI,(y1+JS)*BILI,(x2+JZ)*BILI,(y1+JS)*BILI); for(x1=1;x1《=18;x1++) for(y1=1;y1《=18;y1++) box=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==0) { draw_circle(step_x,step_y,LIGHTBLUE); 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==0) { draw_circle(step_x,step_y,LIGHTBLUE); 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==0) { draw_circle(step_x,step_y,LIGHTBLUE); 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==0) { draw_circle(step_x,step_y,LIGHTBLUE); 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&&step_y》=1&&step_y《=18) { if(box==0) { box=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倍*/ outtextxy(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 ; } } else break ; } } void change() { if(flag==1) flag=2 ; else flag=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==flag) n1++; else break ; } /*水平向右数*/ for(j=x,k=y;j《=18;j++) { if(box==flag) n2++; else break ; } if(n1+n2-1》=5) { return(1); break ; } /*垂直向上数*/ n1=0 ; n2=0 ; for(j=x,k=y;k》=1;k--) { if(box==flag) n1++; else break ; } /*垂直向下数*/ for(j=x,k=y;k《=18;k++) { if(box==flag) n2++; else break ; } 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==flag) n1++; else break ; } /*向右下方数*/ for(j=x,k=y;j《=18,k《=18;j++,k++) { if(box==flag) n2++; else break ; } 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==flag) n1++; else break ; } /*向左下方数*/ for(j=x,k=y;j》=1,k《=18;j--,k++) { if(box==flag) n2++; else break ; } 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(); }
如何用C++编写五子棋
通过C++语言来实现一个以windows控制台为展示平台的简单版五子棋程序,其中通过键盘输入来控制游戏中的行为(光标移动、落子、确认)。
规则要求某一方在横竖斜方向连续存在五个或五个以上本人所执棋子获得为获胜。当我们要扒一个已存在的程序时(有的是五子棋的程序,可以在互联网里找到很多)。
我们可以从他的UI入手,通过我们所观察到的,所感受到,所使用到的服务,来对软件进行分析,从而获得以上流程,但我们一旦需要将需求变为代码时,我们的设计就要考虑的更多了。
我们可以使用两个int类型的值来表示:白子- 1,黑子- 2,那么我们只要在棋盘中更改光标所在位置元素的值为1或2就可以了。
我们回顾一下光标移动的代码,我们会发现,中进行落子后,我们光标再次移动有可能会改变已记录的落子信息,为了使光标与棋子不冲突,我们使用两个图层,表示两个相同的棋盘。
用JAVA做五子棋源代码
java网络五子棋下面的源代码分为4个文件; chessClient.java:客户端主程序。 chessInterface.java:客户端的界面。 chessPad.java:棋盘的绘制。 chessServer.java:服务器端。 可同时容纳50个人同时在线下棋,聊天。 没有加上详细注释,不过绝对可以运行,j2sdk1.4下通过。 /********************************************************************************************* 1.chessClient.java **********************************************************************************************/ import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; 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; chessclient.userpad.userList.removeAll(); chessclient.inputpad.userChoice.removeAll(); chessclient.inputpad.userChoice.addItem("所有人"); while(userToken.hasMoreTokens()) { String user=(String)userToken.nextToken(" "); if(userNumber》0 && !user.startsWith("")) { chessclient.userpad.userList.add(user); chessclient.inputpad.userChoice.addItem(user); } userNumber++; } chessclient.inputpad.userChoice.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=userpad.userList.getSelectedItem(); if(selectedUser==null || selectedUser.startsWith("") || 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 "+userpad.userList.getSelectedItem()+" "+chessClientName); } } else { isOnChess=true; isClient=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/joingame "+userpad.userList.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 "+""+chessClientName); } } else { isOnChess=true; isServer=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/creatgame "+""+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(inputpad.userChoice.getSelectedItem().equals("所有人")) { try { out.writeUTF(inputWords.getText()); inputWords.setText(""); } catch(Exception ea) { chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n"); userpad.userList.removeAll(); inputpad.userChoice.removeAll(); inputWords.setText(""); controlpad.connectButton.setEnabled(true); } } else { try { out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText()); inputWords.setText(""); } catch(Exception ea) { chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n"); userpad.userList.removeAll(); inputpad.userChoice.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(); } } /****************************************************************************************** 下面是:chessInteface.java ******************************************************************************************/ import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; class userPad extends Panel { List userList=new List(10); userPad() { setLayout(new BorderLayout()); for(int i=0;i《50;i++) { userList.add(i+"."+"没有用户"); } add(userList,BorderLayout.CENTER); } } class chatPad extends Panel { TextArea chatLineArea=new TextArea("",18,30,TextArea.SCROLLBARS_VERTICAL_ONLY); chatPad() { setLayout(new BorderLayout()); add(chatLineArea,BorderLayout.CENTER); } } class controlPad extends Panel { Label IPlabel=new Label("IP",Label.LEFT); TextField inputIP=new TextField("localhost",10); Button connectButton=new Button("连接主机"); Button creatGameButton=new Button("建立游戏"); Button joinGameButton=new Button("加入游戏"); Button cancelGameButton=new Button("放弃游戏"); Button exitGameButton=new Button("关闭程序"); controlPad() { setLayout(new FlowLayout(FlowLayout.LEFT)); setBackground(Color.pink); add(IPlabel); add(inputIP); add(connectButton); add(creatGameButton); add(joinGameButton); add(cancelGameButton); add(exitGameButton); } } class inputPad extends Panel { TextField inputWords=new TextField("",40); Choice userChoice=new Choice(); inputPad() { setLayout(new FlowLayout(FlowLayout.LEFT)); for(int i=0;i《50;i++) { userChoice.addItem(i+"."+"没有用户"); } userChoice.setSize(60,24); add(userChoice); add(inputWords); } } /********************************************************************************************** 下面是:chessPad.java **********************************************************************************************/ import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; class chessThread extends Thread { chessPad chesspad; chessThread(chessPad chesspad) { this.chesspad=chesspad; } public void sendMessage(String sndMessage) { try { chesspad.outData.writeUTF(sndMessage); } catch(Exception ea) { System.out.println("chessThread.sendMessage:"+ea); } } public void acceptMessage(String recMessage) { if(recMessage.startsWith("/chess ")) { StringTokenizer userToken=new StringTokenizer(recMessage," "); String chessToken; String chessOpt={"-1","-1","0"}; int chessOptNum=0; while(userToken.hasMoreTokens()) { chessToken=(String)userToken.nextToken(" "); if(chessOptNum》=1 && chessOptNum《=3) { chessOpt=chessToken; } chessOptNum++; } chesspad.netChessPaint(Integer.parseInt(chessOpt)); } else if(recMessage.startsWith("/yourname ")) { chesspad.chessSelfName=recMessage.substring(10); } else if(recMessage.equals("/error")) { chesspad.statusText.setText("错误:没有这个用户,请退出程序,重新加入"); } else { //System.out.println(recMessage); } } public void run() { String message=""; try { while(true) { message=chesspad.inData.readUTF(); acceptMessage(message); } } catch(IOException es) { } } } class chessPad extends Panel implements MouseListener,ActionListener { int chessPoint_x=-1,chessPoint_y=-1,chessColor=1; int chessBlack_x; int chessBlack_y; int chessWhite_x; int chessWhite_y; int chessBlackCount=0,chessWhiteCount=0; int chessBlackWin=0,chessWhiteWin=0; boolean isMouseEnabled=false,isWin=false,isInGame=false; TextField statusText=new TextField("请先连接服务器"); Socket chessSocket; DataInputStream inData; DataOutputStream outData; String chessSelfName=null; String chessPeerName=null; String host=null; int port=4331; chessThread chessthread=new chessThread(this); chessPad() { setSize(440,440); setLayout(null); setBackground(Color.pink); addMouseListener(this); add(statusText); statusText.setBounds(40,5,360,24); statusText.setEditable(false); } public boolean connectServer(String ServerIP,int ServerPort) throws Exception { try { chessSocket=new Socket(ServerIP,ServerPort); inData=new DataInputStream(chessSocket.getInputStream()); outData=new DataOutputStream(chessSocket.getOutputStream()); chessthread.start(); return true; } catch(IOException ex) { statusText.setText("chessPad:connectServer:无法连接 \n"); } return false; } public void chessVictory(int chessColorWin) { this.removeAll(); for(int i=0;i《=chessBlackCount;i++) { chessBlack_x=0; chessBlack_y=0; } for(int i=0;i《=chessWhiteCount;i++) { chessWhite_x=0; chessWhite_y=0; } chessBlackCount=0; chessWhiteCount=0; add(statusText); statusText.setBounds(40,5,360,24); if(chessColorWin==1) { chessBlackWin++; statusText.setText("黑棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待白棋下子..."); } else if(chessColorWin==-1) { chessWhiteWin++; statusText.setText("白棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待黑棋下子..."); } } public void getLocation(int a,int b,int color) { if(color==1) { chessBlack_x=a*20; chessBlack_y=b*20; chessBlackCount++; } else if(color==-1) { chessWhite_x=a*20; chessWhite_y=b*20; chessWhiteCount++; } } public boolean checkWin(int a,int b,int checkColor) { int step=1,chessLink=1,chessLinkTest=1,chessCompare=0; if(checkColor==1) { chessLink=1; for(step=1;step《=4;step++) { for(chessCompare=0;chessCompare《=chessBlackCount;chessCompare++) { if(((a+step)*20==chessBlack_x)) { chessLink=chessLink+1; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } for(step=1;step《=4;step++) { for(chessCompare=0;chessCompare《=chessBlackCount;chessCompare++) { if(((a-step)*20==chessBlack_x)) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } chessLink=1; chessLinkTest=1; for(step=1;step《=4;step++) { for(chessCompare=0;chessCompare《=chessBlackCount;chessCompare++) { if((a*20==chessBlack_x)) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } for(step=1;step《=4;step++) { for(chessCompare=0;chessCompare《=chessBlackCount;chessCompare++) { if((a*20==chessBlack_x)) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } chessLink=1; chessLinkTest=1; for(step=1;step《=4;step++) { for(chessCompare=0;chessCompare《=chessBlackCount;chessCompare++) { if(((a-step)*20==chessBlack_x)) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } for(step=1;step《=4;step++) { for(chessCompare=0;chessCompare《=chessBlackCount;chessCompare++) { if(((a+step)*20==chessBlack_x)) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } chessLink=1; chessLinkTest=1; for(step=1;step《=4;step++) { for(chessCompare=0;chessCompare《=chessBlackCount;chessCompare++) { if(((a+step)*20==chessBlack_x)) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } for(step=1;step《=4;step++) { for(chessCompare=0;chessCompare《=chessBlackCount;chessCompare++) { if(((a-step)*20==chessBlack_x)) { chessLink++; if(chessLink==5) { return(true); } }
求五子棋Java代码旁边就注释 让我看的清楚明白一些,要详细的解释和思路
import java.applet.*; import t.*; import t.event.*; import java.applet.Applet; import t.Color; //这一段import就不说了,下面要用到的就import进来public class wuziqi extends Applet implements ActionListener,MouseListener,MouseMotionListener,ItemListener //继承Applet表明是个applet,后面的接口必须要实现每个接口的所有方法{ int color_Qizi=0;//旗子的颜色标识 0:白子 1:黑子 int intGame_Start=0;//游戏开始标志 0未开始 1游戏中 int intGame_Body; //设置棋盘棋子状态 0 无子 1 白子 2 黑子
急需基于eclipse的JAVA小游戏源代码!!!
单人版五子棋,不用导入,直接新建一个mywindow类就行,然后把一下代码粘贴就Ok了。或者,直接用dos就可以了。。---------------------import java.awt.*;import java.awt.event.*;import javax.swing.*;class mypanel extends Panel implements MouseListener{ int chess; boolean Is_Black_True; mypanel() { Is_Black_True = true; for(int i = 0;i 《 11;i++) { for(int j = 0;j 《 11;j++) { chess = 0; } } addMouseListener(this); setBackground(Color.BLUE); setBounds(0, 0, 360, 360); setVisible(true); } public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); if(x 《 25 || x 》 330 + 25 ||y 《 25 || y 》 330+25) { return; } if(chess != 0) { return; } if(Is_Black_True == true) { chess = 1; Is_Black_True = false; repaint(); Justisewiner(); return; } if(Is_Black_True == false) { chess = 2; Is_Black_True = true; repaint(); Justisewiner(); return; } } void Drawline(Graphics g) { for(int i = 30;i 《= 330;i += 30) { for(int j = 30;j 《= 330; j+= 30) { g.setColor(Color.WHITE); g.drawLine(i, j, i, 330); } } for(int j = 30;j 《= 330;j += 30) { g.setColor(Color.WHITE); g.drawLine(30, j, 330, j); } } void Drawchess(Graphics g) { for(int i = 0;i 《 11;i++) { for(int j = 0;j 《 11;j++) { if(chess == 1) { g.setColor(Color.BLACK); g.fillOval((i + 1) * 30 - 8, (j + 1) * 30 - 8, 16, 16); } if(chess == 2) { g.setColor(Color.WHITE); g.fillOval((i + 1) * 30 - 8, (j + 1) * 30 - 8, 16, 16); } } } } void Justisewiner() { int black_count = 0; int white_count = 0; int i = 0; for(i = 0;i 《 11;i++)//横向判断 { for(int j = 0;j 《 11;j++) { if(chess == 1) { black_count++; if(black_count == 5) { JOptionPane.showMessageDialog(this, "黑棋胜利"); Clear_Chess(); return; } } else { black_count = 0; } if(chess == 2) { white_count++; if(white_count == 5) { JOptionPane.showMessageDialog(this, "白棋胜利"); Clear_Chess(); return; } } else { white_count = 0; } } } for(i = 0;i 《 11;i++)//竖向判断 { for(int j = 0;j 《 11;j++) { if(chess == 1) { black_count++; if(black_count == 5) { JOptionPane.showMessageDialog(this, "黑棋胜利"); Clear_Chess(); return; } } else { black_count = 0; } if(chess == 2) { white_count++; if(white_count == 5) { JOptionPane.showMessageDialog(this, "白棋胜利"); Clear_Chess(); return; } } else { white_count = 0; } } }for(i = 0;i 《 7;i++)//左向右斜判断 { for(int j = 0;j 《 7;j++) { for(int k = 0;k 《 5;k++) { if(chess == 1) { black_count++; if(black_count == 5) { JOptionPane.showMessageDialog(this, "黑棋胜利"); Clear_Chess(); return; } } else { black_count = 0; } if(chess == 2) { white_count++; if(white_count == 5) { JOptionPane.showMessageDialog(this, "白棋胜利"); Clear_Chess(); return; } } else { white_count = 0; } } } } for(i = 4;i 《 11;i++)//右向左斜判断 { for(int j = 6;j 》= 0;j--) { for(int k = 0;k 《 5;k++) { if(chess == 1) { black_count++; if(black_count == 5) { JOptionPane.showMessageDialog(this, "黑棋胜利"); Clear_Chess(); return; } } else { black_count = 0; } if(chess == 2) { white_count++; if(white_count == 5) { JOptionPane.showMessageDialog(this, "白棋胜利"); Clear_Chess(); return; } } else { white_count = 0; } } } } } void Clear_Chess() { for(int i=0;i《11;i++) { for(int j=0;j《11;j++) { chess=0; } } repaint(); } public void paint(Graphics g) { Drawline(g); Drawchess(g); } public void mouseExited(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseReleased(MouseEvent e){} public void mouseClicked(MouseEvent e){} }class myframe extends Frame implements WindowListener{ mypanel panel; myframe() { setLayout(null); panel = new mypanel(); add(panel); panel.setBounds(0,23, 360, 360); setTitle("单人版五子棋"); setBounds(200, 200, 360, 383); setVisible(true); addWindowListener(this); } public void windowClosing(WindowEvent e) { System.exit(0); } public void windowDeactivated(WindowEvent e){} public void windowActivated(WindowEvent e){} public void windowOpened(WindowEvent e){} public void windowClosed(WindowEvent e){} public void windowIconified(WindowEvent e){} public void windowDeiconified(WindowEvent e){}}public class mywindow{ public static void main(String argc ) { myframe f = new myframe(); }}
请帮忙分析一下java五子棋中的这段源代码
public class AutoPlay { int x, y; // 定义坐标轴, X 和 y /** * 方法:自动玩 * 这是一个自动下子的方法,先根据玩家给出的第一下子点,它开始自动延展 * @param chesspad * 代表棋盘的二维数组 * @param a * @param b */ void autoPlay(int chesspad, int a, int b) { /* * x + 1 = 向右1 * x - 1 = 向左1 * y + 1 = 向下1 * y - 1 = 向上1 */ int randomNumber = (int) (Math.random() * 8) + 1; // 生成一个 1 - 8 之间的随机数 switch (randomNumber) { // 通过生成的随机数,进行分支选择 case 1: // 如果等于 1 // 如果 a - 1 和 b -1 这个位置为 0 ,则说明这个位置 没有棋子占据 if (chesspad == 0) { x = a - 1; // 向左一位 y = b - 1; // 向上一位 // 下子 // 如果 a - 2和 b -2 这个位置为 0 ,则说明这个位置 没有棋子占据 } else if (chesspad == 0) { x = a - 2; // 向左二位 y = b - 2; // 向上二位 // 下子 } else { // 否则 x = a - 3; // 向左三位 y = b - 3; // 向上三位 // 下子 } break; // 执行完上面的选择代码退出 case 2: // 如果 a - 1 和 b 这个位置为 0 ,则说明这个位置 没有棋子占据 if (chesspad == 0) { x = a - 1; // 向左一位 y = b; // 下子 // 如果 a - 2 和 b 这个位置为 0 ,则说明这个位置 没有棋子占据 } else if (chesspad == 0) { x = a - 2; // 向左二位 y = b; // 下子 } else { x = a - 3; // 向左三位 y = b; // 下子 } break; // 执行完上面的选择代码退出 case 3: // 如果 a - 1 和 b + 1这个位置为 0 ,则说明这个位置 没有棋子占据 if (chesspad == 0) { x = a - 1; // 向左一位 y = b + 1; // 向下一位 // 下子 } else if (chesspad == 0) { x = a - 2; // 向左二位 y = b + 2; // 向下二位 // 下子 } else { x = a - 3; // 向左三位 y = b + 3; // 向左三位 // 下子 } break; // 执行完上面的选择代码退出 case 4: if (chesspad == 0) { x = a; // 不左不右 y = b + 1; // 向左一位 // 下子 } else if (chesspad == 0) { x = a; // 不左不右 y = b + 2; // 向左二位 // 下子 } else { x = a; // 不左不右 y = b + 3; // 向左三位 // 下子 } break; // 执行完上面的选择代码退出 case 5: if (chesspad == 0) { x = a + 1; // 向右一位 y = b + 1; // 向下一位 // 下子 } else if (chesspad == 0) { x = a + 2; // 向右二位 y = b + 2; // 向下二位 // 下子 } else { x = a + 3; // 向右三位 y = b + 3; // 向下三位 // 下子 } break; // 执行完上面的选择代码退出 case 6: if (chesspad == 0) { x = a + 1; // 向右一位 y = b; //不上不下 // 下子 } else if (chesspad == 0) { x = a + 2; // 向右二位 y = b; //不上不下 // 下子 } else { x = a + 3; // 向右三位 y = b; //不上不下 // 下子 } break; // 执行完上面的选择代码退出 case 7: if (chesspad == 0) { x = a + 1; // 向右一位 y = b - 1; // 向上一位 // 下子 } else if (chesspad == 0) { x = a + 2; // 向右二位 y = b - 2; // 向上二位 } else { x = a + 3; // 向右三位 y = b - 3; // 向上三位 } break; // 执行完上面的选择代码退出 case 8: if (chesspad == 0) { x = a; y = b - 1; // 向上二位 // 下子 } else if (chesspad == 0) { x = a; y = b - 2; // 向上二位 // 下子 } else { x = a; y = b + 3; // 向上三位 // 下子 } break; // 执行完上面的选择代码退出 } }}我的 Hi 在线,如果有什么不明白,可以Hi我。
怎么Java实现鼠标点击的五子棋啊 各位大侠 帮帮忙
import java.awt.*;import java.awt.event.*;import java.awt.color.*;class wuzi { public static void main(String args) { frame myFrame =new frame("五子棋"); }} class frame extends Frame implements ActionListener{ MenuBar mbar=new MenuBar(); Menu mgame=new Menu("选项"); Menu mhelp=new Menu("帮助"); MenuItem mstart=new MenuItem("开始 "); MenuItem mclose=new MenuItem("结束"); MenuItem mabout=new MenuItem("关于"); myCanvas canvas; frame(String t) { super(t); canvas = new myCanvas(this); mgame.add(mstart); mgame.add(mclose); mhelp.add(mabout); mgame.addActionListener(this); mstart.addActionListener(this); mclose.addActionListener(this); mhelp.addActionListener(this); mabout.addActionListener(this); mbar.add(mgame); mbar.add(mhelp); this.setMenuBar(mbar); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } } ); this.add(canvas); this.pack(); this.show(); this.setLocation(380,100); this.setResizable(false); } public void actionPerformed(ActionEvent e) { if(e.getSource()==mstart) { repaint(); } else if(e.getSource()==mclose){ this.dispose(); System.exit(0); } if(e.getSource()==mabout){ about frm=new about(); } pack(); } } class chessman{ private boolean isExist; private boolean isColor; public chessman(boolean isExist){ this.isExist = isExist ; } boolean getChessExist() { return isExist; } boolean getChessColor() { return isColor; } void setChessExist(boolean m){ isExist = m; } void setChessColor(boolean m) { //设置棋的颜色 isColor = m; } } class myCanvas extends Canvas implements MouseListener { frame myFrame; //保存棋子 private chessman chessMan; int mx,my;//获取位置 int x,y; boolean state = true; myCanvas(frame myFrame) { this.myFrame = myFrame; setBackground(Color.cyan); addMouseListener(this); for(int i=0;i《19;i++) for(int j=0;j《19;j++) chessMan = new chessman(false); } public void start() { for(int i=0;i《19;i++) for(int j=0;j《19;j++) chessMan.setChessExist(false); } public void paint(Graphics g) {//画线 Dimension size = this.getSize(); g.drawRect(0,0,size.width-1,size.height-1); g.draw3DRect(1,1,size.width-3,size.height-3,true); for(int i=0;i《19;i++) g.drawLine(30,i*24+30,462,i*24+30); for(int j=0;j《19;j++) g.drawLine(j*24+30,30,j*24+30,462); x=(int)((mx-20)/24); y=(int)((my-20)/24); //计算落子位置 if(!chessMan.getChessExist()&&(mx》=18||my》=18)){ chessMan.setChessExist(true); chessMan.setChessColor(state); state = !state; } for(int i =0;i《19;i++) for(int j=0;j《19;j++){ if(chessMan.getChessExist()) { if(chessMan.getChessColor()==true){ g.setColor(Color.black); //默认黑棋先下 } else{ g.setColor(Color.white); } g.fillOval(j*24+21,i*24+21,18,18); // whowin(x, y) ; } } } /* public void whowin(int x, int y) { int m1 = 0, m2 = 0, m3 = 0, m4 = 0; for (int i = 1; i 《 5; i++) {//判断-------向左------- if (x - i 》 0 && chessMan) { m1++; } } for (int j = 1; j 《 5; j++) {//判断-------向右------- if (x + j 《 20 && chessMan) { m1++; } } //判断输赢------shu线 for (int i = 1; i 《 5; i++) {//判断-------向下----------- if (y + i 《 20 && chessMan) { m2++; } } for (int i = 1; i 《 5; i++) {//判断-------向上------------ if (y - i 》 0 && chessMan) { m2++; } }//判断输赢------\线 for (int i = 1; i 《 5; i++) {//判断-------向左上-------------if (x - i 》 0 && y - i 》 0 && chessMan) { m3++; } } for (int i = 1; i 《 5; i++) {//判断-------向右下------------- if (x + i 《 20 && y + i 《 20 && chessMan) { m3++; } } //判断输赢------/线 for (int i = 1; i 《 5; i++) {//判断-------向左下------------ if (x - i 》 0 && y + i 《 20 && chessMan) { m4++; } } for (int i = 1; i 《 5; i++) {//判断-------向右上-------------- if (y - i 》 0 && x + i 《 20 && chessMan) { m4++; } } //***************最后判断输赢******************** if (m1 》 3 || m2 》 3 || m3 》 3 || m4 》 3) { if (chessMan == ) {//----因为下棋后将棋子颜色改为对方的颜色,所以这里互相调一下--- JOptionPane.showMessageDialog(this, "hei-----win"); isgamealive = 0; } if (chessMan == false) { JOptionPane.showMessageDialog(this, "bai-----win"); isgamealive = 0; } } }*/ public Dimension getPreferredSize() { return new Dimension(492,492); //返回图形大小 } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseClicked(MouseEvent e){ mx = e.getX(); my = e.getY(); repaint(); } }class about extends Frame implements WindowListener //设置关于{ about() { this.setSize(300,170); this.setTitle("关于五子棋游戏"); this.addWindowListener(this); this.setVisible(true); this.setLocation(400,200); this.setResizable(false); this.setLayout(new FlowLayout()); Label text1 =new Label(); Label text2 =new Label(); Label text3=new Label(); text1.setText("游戏介绍:"); text1.setFont(new Font("黑体",Font.ITALIC,25)); text1.setAlignment(text1.CENTER); text1.setVisible(true); text2.setText("横排,竖排,斜排,谁先放到5个就赢。"); text2.setFont(new Font("黑体",Font.PLAIN,15)); text2.setAlignment(text1.LEFT); text2.setVisible(true); text3.setText("制作者:0957207吴君"); text3.setFont(new Font("楷体",Font.PLAIN,15)); text3.setVisible(true); this.add(text1,"North"); this.add(text2,"West"); this.add(text3,"South"); this.show(true); } public void windowActivated(WindowEvent e){} public void windowClosed(WindowEvent e){ } public void windowClosing(WindowEvent e){ this.dispose(); } public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} }
急需用eclipse写的小游戏代码 比如贪吃蛇,五子棋,猜数字,俄罗斯方块等的小游戏代码
新建一个project,新建一个类把代码贴进去,找到运行(run)这个按钮,按了就能运行,找不到的话快捷键是Ctrl + F11import java.awt.Color;import java.awt.Component;import java.awt.Graphics;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.ArrayList;import javax.swing.BorderFactory;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;public class SnakeGame { public static void main(String args) { SnakeFrame frame = new SnakeFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}// ----------记录状态的线程class StatusRunnable implements Runnable { public StatusRunnable(Snake snake, JLabel statusLabel, JLabel scoreLabel) { this.statusLabel = statusLabel; this.scoreLabel = scoreLabel; this.snake = snake; } public void run() { String sta = ""; String spe = ""; while (true) { switch (snake.status) { case Snake.RUNNING: sta = "Running"; break; case Snake.PAUSED: sta = "Paused"; break; case Snake.GAMEOVER: sta = "GameOver"; break; } statusLabel.setText(sta); scoreLabel.setText("" + snake.score); try { Thread.sleep(100); } catch (Exception e) { } } } private JLabel scoreLabel; private JLabel statusLabel; private Snake snake;}// ----------蛇运动以及记录分数的线程class SnakeRunnable implements Runnable { public SnakeRunnable(Snake snake, Component component) { this.snake = snake; this.component = component; } public void run() { while (true) { try { snake.move(); component.repaint(); Thread.sleep(snake.speed); } catch (Exception e) { } } } private Snake snake; private Component component;}class Snake { boolean isRun;// ---------是否运动中 ArrayList《Node》 body;// -----蛇体 Node food;// --------食物 int derection;// --------方向 int score; int status; int speed; public static final int SLOW = 500; public static final int MID = 300; public static final int FAST = 100; public static final int RUNNING = 1; public static final int PAUSED = 2; public static final int GAMEOVER = 3; public static final int LEFT = 1; public static final int UP = 2; public static final int RIGHT = 3; public static final int DOWN = 4; public Snake() { speed = Snake.SLOW; score = 0; isRun = false; status = Snake.PAUSED; derection = Snake.RIGHT; body = new ArrayList《Node》(); body.add(new Node(60, 20)); body.add(new Node(40, 20)); body.add(new Node(20, 20)); makeFood(); } // ------------判断食物是否被蛇吃掉 // -------如果食物在蛇运行方向的正前方,并且与蛇头接触,则被吃掉 private boolean isEaten() { Node head = body.get(0); if (derection == Snake.RIGHT && (head.x + Node.W) == food.x && head.y == food.y) return true; if (derection == Snake.LEFT && (head.x - Node.W) == food.x && head.y == food.y) return true; if (derection == Snake.UP && head.x == food.x && (head.y - Node.H) == food.y) return true; if (derection == Snake.DOWN && head.x == food.x && (head.y + Node.H) == food.y) return true; else return false; } // ----------是否碰撞 private boolean isCollsion() { Node node = body.get(0); // ------------碰壁 if (derection == Snake.RIGHT && node.x == 280) return true; if (derection == Snake.UP && node.y == 0) return true; if (derection == Snake.LEFT && node.x == 0) return true; if (derection == Snake.DOWN && node.y == 380) return true; // --------------蛇头碰到蛇身 Node temp = null; int i = 0; for (i = 3; i 《 body.size(); i++) { temp = body.get(i); if (temp.x == node.x && temp.y == node.y) break; } if (i 《 body.size()) return true; else return false; } // -------在随机的地方产生食物 public void makeFood() { Node node = new Node(0, 0); boolean isInBody = true; int x = 0, y = 0; int X = 0, Y = 0; int i = 0; while (isInBody) { x = (int) (Math.random() * 15); y = (int) (Math.random() * 20); X = x * Node.W; Y = y * Node.H; for (i = 0; i 《 body.size(); i++) { if (X == body.get(i).x && Y == body.get(i).y) break; } if (i 《 body.size()) isInBody = true; else isInBody = false; } food = new Node(X, Y); } // ---------改变运行方向 public void changeDerection(int newDer) { if (derection % 2 != newDer % 2)// -------如果与原来方向相同或相反,则无法改变 derection = newDer; } public void move() { if (isEaten()) {// -----如果食物被吃掉 body.add(0, food);// --------把食物当成蛇头成为新的蛇体 score += 10; makeFood();// --------产生食物 } else if (isCollsion())// ---------如果碰壁或自身 { isRun = false; status = Snake.GAMEOVER;// -----结束 } else if (isRun) {// ----正常运行(不吃食物,不碰壁,不碰自身) Node node = body.get(0); int X = node.x; int Y = node.y; // ------------蛇头按运行方向前进一个单位 switch (derection) { case 1: X -= Node.W; break; case 2: Y -= Node.H; break; case 3: X += Node.W; break; case 4: Y += Node.H; break; } body.add(0, new Node(X, Y)); // ---------------去掉蛇尾 body.remove(body.size() - 1); } }}// ---------组成蛇身的单位,食物class Node { public static final int W = 20; public static final int H = 20; int x; int y; public Node(int x, int y) { this.x = x; this.y = y; }}// ------画板class SnakePanel extends JPanel { Snake snake; public SnakePanel(Snake snake) { this.snake = snake; } public void paintComponent(Graphics g) { super.paintComponent(g); Node node = null; for (int i = 0; i 《 snake.body.size(); i++) {// ---红蓝间隔画蛇身 if (i % 2 == 0) g.setColor(Color.blue); else g.setColor(Color.yellow); node = snake.body.get(i); g.fillRect(node.x, node.y, node.H, node.W);// *******************试用********************* } node = snake.food; g.setColor(Color.red); g.fillRect(node.x, node.y, node.H, node.W); }}class SnakeFrame extends JFrame { private JLabel statusLabel; private JLabel speedLabel; private JLabel scoreLabel; private JPanel snakePanel; private Snake snake; private JMenuBar bar; JMenu gameMenu; JMenu helpMenu; JMenu speedMenu; JMenuItem newItem; JMenuItem pauseItem; JMenuItem beginItem; JMenuItem helpItem; JMenuItem aboutItem; JMenuItem slowItem; JMenuItem midItem; JMenuItem fastItem; public SnakeFrame() { init(); ActionListener l = new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getSource() == pauseItem) snake.isRun = false; if (e.getSource() == beginItem) snake.isRun = true; if (e.getSource() == newItem) { newGame(); } // ------------菜单控制运行速度 if (e.getSource() == slowItem) { snake.speed = Snake.SLOW; speedLabel.setText("Slow"); } if (e.getSource() == midItem) { snake.speed = Snake.MID; speedLabel.setText("Mid"); } if (e.getSource() == fastItem) { snake.speed = Snake.FAST; speedLabel.setText("Fast"); } } }; pauseItem.addActionListener(l); beginItem.addActionListener(l); newItem.addActionListener(l); aboutItem.addActionListener(l); slowItem.addActionListener(l); midItem.addActionListener(l); fastItem.addActionListener(l); addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { // ------------方向键改变蛇运行方向 case KeyEvent.VK_DOWN:// snake.changeDerection(Snake.DOWN); break; case KeyEvent.VK_UP:// snake.changeDerection(Snake.UP); break; case KeyEvent.VK_LEFT:// snake.changeDerection(Snake.LEFT); break; case KeyEvent.VK_RIGHT:// snake.changeDerection(Snake.RIGHT); break; // 空格键,游戏暂停或继续 case KeyEvent.VK_SPACE:// if (snake.isRun == true) { snake.isRun = false; snake.status = Snake.PAUSED; break; } if (snake.isRun == false) { snake.isRun = true; snake.status = Snake.RUNNING; break; } } } public void keyReleased(KeyEvent k) { } public void keyTyped(KeyEvent k) { } }); } private void init() { speedLabel = new JLabel(); snake = new Snake(); setSize(380, 460); setLayout(null); this.setResizable(false); bar = new JMenuBar(); gameMenu = new JMenu("Game"); newItem = new JMenuItem("New Game"); gameMenu.add(newItem); pauseItem = new JMenuItem("Pause"); gameMenu.add(pauseItem); beginItem = new JMenuItem("Continue"); gameMenu.add(beginItem); helpMenu = new JMenu("Help"); aboutItem = new JMenuItem("About"); helpMenu.add(aboutItem); speedMenu = new JMenu("Speed"); slowItem = new JMenuItem("Slow"); fastItem = new JMenuItem("Fast"); midItem = new JMenuItem("Middle"); speedMenu.add(slowItem); speedMenu.add(midItem); speedMenu.add(fastItem); bar.add(gameMenu); bar.add(helpMenu); bar.add(speedMenu); setJMenuBar(bar); statusLabel = new JLabel(); scoreLabel = new JLabel(); snakePanel = new JPanel(); snakePanel.setBounds(0, 0, 300, 400); snakePanel.setBorder(BorderFactory.createLineBorder(Color.darkGray)); add(snakePanel); statusLabel.setBounds(300, 25, 60, 20); add(statusLabel); scoreLabel.setBounds(300, 20, 60, 20); add(scoreLabel); JLabel temp = new JLabel("状态"); temp.setBounds(310, 5, 60, 20); add(temp); temp = new JLabel("分数"); temp.setBounds(310, 105, 60, 20); add(temp); temp = new JLabel("速度"); temp.setBounds(310, 55, 60, 20); add(temp); speedLabel.setBounds(310, 75, 60, 20); add(speedLabel); } private void newGame() { this.remove(snakePanel); this.remove(statusLabel); this.remove(scoreLabel); speedLabel.setText("Slow"); statusLabel = new JLabel(); scoreLabel = new JLabel(); snakePanel = new JPanel(); snake = new Snake(); snakePanel = new SnakePanel(snake); snakePanel.setBounds(0, 0, 300, 400); snakePanel.setBorder(BorderFactory.createLineBorder(Color.darkGray)); Runnable r1 = new SnakeRunnable(snake, snakePanel); Runnable r2 = new StatusRunnable(snake, statusLabel, scoreLabel); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); add(snakePanel); statusLabel.setBounds(310, 25, 60, 20); add(statusLabel); scoreLabel.setBounds(310, 125, 60, 20); add(scoreLabel); }}
用eclipse编写一个基于java的五子棋(与电脑对弈)
基于java的五子棋:
主要功能代码如下:
import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Main extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L; JButton; int; int; int; public Main(){ this.setTitle("五子棋"); this.setBounds(100,10,1000,1000); this.setLayout(new GridLayout(30,30)); int i,j; for(i=0;i《=39;i++){ for(j=0;j《=39;j++){ state=0; value=0; } } for(i=5;i《=34;i++){ for (j=5;j《=34;j++){ point=new JButton(""); this.add(point); point.addActionListener(this); } } this.setVisible(true); } public void actionPerformed(ActionEvent e) { int i,j; for(i=5;i《=34;i++){ for(j=5;j《=34;j++){ if(e.getSource()==point){ point.setBackground(Color.RED); state=1; point.setEnabled(false); value=0; } } } public static void main(String args)throws NullPointerException{ new Main(); } else if(((state==0))|| ((state==0))|| ((state==0))|| ((state==0))|| //空红空 ((state==0))|| ((state==0))|| ((state==0))|| ((state==0))|| ((state==2))|| ((state==2))|| ((state==2))|| ((state==2))|| //空红红蓝型 ((state==2))|| ((state==2))|| ((state==2))|| ((state==2))){ value=2; return value; } else if(((state==0))|| ((state==0))|| ((state==0))|| ((state==0))|| ((state==0))|| ((state==0))|| ((state==0))|| ((state==0))|| ((state==1))|| ((state==1))|| ((state==1))|| ((state==1))|| ((state==1))|| ((state==1))|| ((state==1))|| ((state==1))){ value=1; return value; } else{ value=0; return value; } } public int value){ int max,i,j,l,k; l=0;k=0; max=0; for(i=5;i《34;i++){ for(j=5;j《34;j++){ if(max《value){ max=value; place=i; place=j; } } } return place; }}
运行结果如下图所示:
本文相关文章:
![少儿五子棋:初学者如何从零开始自学五子棋?孩子五岁,如何教她学五子棋啊](/static/images/nopic/22.jpg)
少儿五子棋:初学者如何从零开始自学五子棋?孩子五岁,如何教她学五子棋啊
2024年6月25日 12:33
![斗地主记忆力训练(打斗地主和下五子棋哪个更锻炼逻辑思维能力)](/static/images/nopic/10.jpg)
斗地主记忆力训练(打斗地主和下五子棋哪个更锻炼逻辑思维能力)
2024年6月19日 23:27
![不用下载的五子棋小游戏(请问我要用Android studio做一个五子棋的小游戏怎么配置开发环境)](/static/images/nopic/5.jpg)
不用下载的五子棋小游戏(请问我要用Android studio做一个五子棋的小游戏怎么配置开发环境)
2024年2月23日 22:45
![冒险岛的五子棋跟记忆大考验是怎么开的?洛克王国想成为商人的条件 记忆大考验100 怎么完成](/static/images/nopic/18.jpg)
冒险岛的五子棋跟记忆大考验是怎么开的?洛克王国想成为商人的条件 记忆大考验100 怎么完成
2024年2月12日 12:05
更多文章:
![我新开了魔域一级VIP,怎么才能绑定其他的区啊?魔域最近新开的是哪个区](/static/images/nopic/23.jpg)
我新开了魔域一级VIP,怎么才能绑定其他的区啊?魔域最近新开的是哪个区
2024年1月1日 00:20
![requesttimedout是什么意思(PING中出现request timed out 什么意思)](/static/images/nopic/4.jpg)
requesttimedout是什么意思(PING中出现request timed out 什么意思)
2023年11月3日 12:55
![我是新手玩家,能推荐下剑灵什么角色比较好么?剑来中剑灵有多强](/static/images/nopic/6.jpg)
我是新手玩家,能推荐下剑灵什么角色比较好么?剑来中剑灵有多强
2023年11月29日 22:00
![qq飞车沁园春(qq飞车侧身漂移练了好久也不会,尤其是沁园春..)](/static/images/nopic/27.jpg)
qq飞车沁园春(qq飞车侧身漂移练了好久也不会,尤其是沁园春..)
2024年5月7日 10:19
![大团结小说下载?求大神,,给我txt 大团结,要闪闪发光的 地址 zdcgykid](/static/images/nopic/26.jpg)
大团结小说下载?求大神,,给我txt 大团结,要闪闪发光的 地址 zdcgykid
2024年6月28日 06:27