中国象棋源代码Java程序

合集下载

Pythonpygame实现中国象棋单机版源码

Pythonpygame实现中国象棋单机版源码

Pythonpygame实现中国象棋单机版源码Python中国象棋单机版⿏标点击操作;两天制作,较为粗糙,很多效果还未实现。

# -*- coding: utf-8 -*-"""Created on Sun Jun 13 15:41:56 2021@author: Administrator"""import pygamefrom pygame.locals import *import sysimport mathpygame.init()screen=pygame.display.set_mode((450,550))pygame.display.set_caption('中国象棋')img_board=pygame.image.load('F:/images/中国象棋/board.png')img_redSoldier=pygame.image.load('F:/images/中国象棋/chess_redSoldier.png')img_redCannon=pygame.image.load('F:/images/中国象棋/chess_redCannon.png')img_redCar=pygame.image.load('F:/images/中国象棋/chess_redCar.png')img_redHorse=pygame.image.load('F:/images/中国象棋/chess_redHorse.png')img_redElephant=pygame.image.load('F:/images/中国象棋/chess_redElephant.png')img_redAttendant=pygame.image.load('F:/images/中国象棋/chess_redAttendant.png')img_chief=pygame.image.load('F:/images/中国象棋/chess_chief.png')img_blackSoldier=pygame.image.load('F:/images/中国象棋/chess_blackSoldier.png')img_blackCannon=pygame.image.load('F:/images/中国象棋/chess_blackCannon.png')img_blackCar=pygame.image.load('F:/images/中国象棋/chess_blackCar.png')img_blackHorse=pygame.image.load('F:/images/中国象棋/chess_blackHorse.png')img_blackElephant=pygame.image.load('F:/images/中国象棋/chess_blackElephant.png')img_blackAttendant=pygame.image.load('F:/images/中国象棋/chess_blackAttendant.png')img_general=pygame.image.load('F:/images/中国象棋/chess_general.png')screen.blit(img_board,(0,0))pygame.display.update()red_chess=[[0,6],[2,6],[4,6],[6,6],[8,6],[1,7],[7,7],[0,9],[1,9],[2,9],[3,9],[4,9],[5,9],[6,9],[7,9],[8,9]]black_chess=[[0,3],[2,3],[4,3],[6,3],[8,3],[1,2],[7,2],[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0]]#画棋⼦def draw_chess():for i in range(len(red_chess)):if 0<=i<=4:screen.blit(img_redSoldier,(red_chess[i][0]*50,red_chess[i][1]*50))elif 5<=i<=6:screen.blit(img_redCannon,(red_chess[i][0]*50,red_chess[i][1]*50))elif i==7 or i==15:screen.blit(img_redCar,(red_chess[i][0]*50,red_chess[i][1]*50))elif i==8 or i==14:screen.blit(img_redHorse,(red_chess[i][0]*50,red_chess[i][1]*50))elif i==9 or i==13:screen.blit(img_redElephant,(red_chess[i][0]*50,red_chess[i][1]*50))elif i==10 or i==12:screen.blit(img_redAttendant,(red_chess[i][0]*50,red_chess[i][1]*50))else:screen.blit(img_chief,(red_chess[i][0]*50,red_chess[i][1]*50))for i in range(len(black_chess)):if 0<=i<=4:screen.blit(img_blackSoldier,(black_chess[i][0]*50,black_chess[i][1]*50))elif 5<=i<=6:screen.blit(img_blackCannon,(black_chess[i][0]*50,black_chess[i][1]*50))elif i==7 or i==15:screen.blit(img_blackCar,(black_chess[i][0]*50,black_chess[i][1]*50))elif i==8 or i==14:screen.blit(img_blackHorse,(black_chess[i][0]*50,black_chess[i][1]*50))elif i==9 or i==13:screen.blit(img_blackElephant,(black_chess[i][0]*50,black_chess[i][1]*50))elif i==10 or i==12:screen.blit(img_blackAttendant,(black_chess[i][0]*50,black_chess[i][1]*50))else:screen.blit(img_general,(black_chess[i][0]*50,black_chess[i][1]*50))pygame.display.update()#返回1表⽰正常移动,返回2表⽰有⼦被吃,返回0表⽰拒绝移动#兵移动规则,红兵chess1为red_chess,chess2为black_chessdef soldier_rule(chess1,chess2,current_pos,next_pos):if chess1==red_chess:pos,index=[5,6],1elif chess1==black_chess:pos,index=[3,4],-1if current_pos[1] in pos:if current_pos[0]==next_pos[0] and current_pos[1]==next_pos[1]+index and next_pos not in chess1: for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]current_pos=next_posreturn [current_pos,1]else:if current_pos[0]==next_pos[0] and current_pos[1]==next_pos[1]+index and next_pos not in chess1: for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]current_pos=next_posreturn [current_pos,1]elif current_pos[1]==next_pos[1] and current_pos[0]+1==next_pos[0] and next_pos not in chess1: for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]current_pos=next_posreturn [current_pos,1]elif current_pos[1]==next_pos[1] and current_pos[0]-1==next_pos[0] and next_pos not in chess1: for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]current_pos=next_posreturn [current_pos,1]#车移动规则,红车前两个参数为red_chess、black_chess,⿊车前两个参数为black_chess、red_chess def car_rule(chess1,chess2,current_pos,next_pos):if next_pos not in chess1 and current_pos[0]==next_pos[0]:a,b=current_pos,next_posif a[1]>b[1]:a,b=b,afor i in range(a[1]+1,b[1]):if [a[0],i] in black_chess+red_chess:return 0for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]current_pos=next_posreturn [current_pos,1]elif next_pos not in chess1 and current_pos[1]==next_pos[1]:a,b=current_pos,next_posif a[0]>b[0]:a,b=b,afor i in range(a[0]+1,b[0]):if [i,a[1]] in black_chess+red_chess:return 0for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]current_pos=next_posreturn [current_pos,1]#炮移动规则def cannon_rule(chess1,chess2,current_pos,next_pos):if next_pos not in chess1 and current_pos[0]==next_pos[0]:num=0a,b=current_pos,next_posif a[1]>b[1]:a,b=b,afor i in range(a[1]+1,b[1]):if [a[0],i] in black_chess+red_chess:num+=1if num==1:for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]return 0elif num==0:current_pos=next_posreturn [current_pos,1]else:return 0elif next_pos not in chess1 and current_pos[1]==next_pos[1]:num=0a,b=current_pos,next_posif a[0]>b[0]:a,b=b,afor i in range(a[0]+1,b[0]):if [i,a[1]] in black_chess+red_chess:num+=1if num==1:for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]return 0elif num==0:current_pos=next_posreturn [current_pos,1]else:return 0#马移动规则,红马chess为black_chessdef horse_rule(chess,current_pos,next_pos):index=[[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1]]leg=[[1,0],[0,-1],[0,-1],[-1,0],[-1,0],[0,1],[0,1],[1,0]]if next_pos not in red_chess+black_chess:for i in range(len(index)):if current_pos[0]+index[i][0]==next_pos[0] and current_pos[1]+index[i][1]==next_pos[1]: if [current_pos[0]+leg[i][0],current_pos[1]+leg[i][1]] not in black_chess+red_chess: current_pos=next_posreturn [current_pos,1]elif next_pos in chess:for i in range(len(index)):if current_pos[0]+index[i][0]==next_pos[0] and current_pos[1]+index[i][1]==next_pos[1]: if [current_pos[0]+leg[i][0],current_pos[1]+leg[i][1]] not in black_chess+red_chess: for i in range(len(chess)):if chess[i]==next_pos:chess[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]#象移动规则,红相chess为black_chessdef elephant_rule(chess,current_pos,next_pos):index=[[2,-2],[-2,-2],[-2,2],[2,2]]leg=[[1,-1],[-1,-1],[-1,1],[1,1]]if chess==black_chess:pos=[5,7,9]elif chess==red_chess:pos=[0,2,4]if next_pos not in red_chess+black_chess and next_pos[1] in pos:for i in range(len(index)):if current_pos[0]+index[i][0]==next_pos[0] and current_pos[1]+index[i][1]==next_pos[1]: if [current_pos[0]+leg[i][0],current_pos[1]+leg[i][1]] not in black_chess+red_chess:current_pos=next_posreturn [current_pos,1]elif next_pos in chess and next_pos[1] in pos:for i in range(len(index)):if current_pos[0]+index[i][0]==next_pos[0] and current_pos[1]+index[i][1]==next_pos[1]: if [current_pos[0]+leg[i][0],current_pos[1]+leg[i][1]] not in black_chess+red_chess: for i in range(len(chess)):if chess[i]==next_pos:chess[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]#⼠移动规则def attendant_rule(chess1,chess2,current_pos,next_pos):if chess1==red_chess:pos1=[[3,9],[3,7],[5,7],[5,9]]pos2=[4,8]elif chess1==black_chess:pos1=[[3,0],[3,2],[5,2],[5,0]]pos2=[4,1]if current_pos in pos1 and next_pos==pos2 and next_pos not in chess1:if next_pos not in chess2:current_pos=next_posreturn [current_pos,1]else:for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]elif current_pos==pos2 and next_pos in pos1 and next_pos not in chess1:if next_pos not in chess2:current_pos=next_posreturn [current_pos,1]else:for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]#将帅移动规则def boss_rule(chess1,chess2,current_pos,next_pos,j_pos):if chess1==red_chess:pos=[7,8,9]elif chess1==black_chess:pos=[0,1,2]flag=0if next_pos not in chess1:if next_pos[0]==j_pos[0]:for i in range(j_pos[1]+1,next_pos[1]):if [j_pos[0],j_pos[1]+i] in black_chess+red_chess:flag=1breakif flag==0:return 0if next_pos not in chess1 and 3<=next_pos[0]<=5 and next_pos[1] in pos:if next_pos not in chess2:if current_pos[0]==next_pos[0]:if current_pos[1]+1==next_pos[1] or current_pos[1]-1==next_pos[1]:current_pos=next_posreturn [current_pos,1]elif current_pos[1]==next_pos[1]:if current_pos[0]+1==next_pos[0] or current_pos[0]-1==next_pos[0]:current_pos=next_posreturn [current_pos,1]else:if current_pos[0]==next_pos[0]:if current_pos[1]+1==next_pos[1] or current_pos[1]-1==next_pos[1]:for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]elif current_pos[1]==next_pos[1]:if current_pos[0]+1==next_pos[0] or current_pos[0]-1==next_pos[0]:for i in range(len(chess2)):if chess2[i]==next_pos:chess2[i]=[-1,-1]current_pos=next_posreturn [current_pos,2]#棋⼦移动def move(chess1,chess2,next_pos):x=0if i in range(5): #兵x=soldier_rule(chess1,chess2,chess1[i],next_pos)if x!=None and x!=0:chess1[i]=x[0]print(chess1[i])screen.blit(img_board,(0,0))draw_chess()elif i==5 or i==6: #炮x=cannon_rule(chess1,chess2,chess1[i],next_pos)if x!=None and x!=0:chess1[i]=x[0]print(chess1[i])screen.blit(img_board,(0,0))draw_chess()elif i==7 or i==15: #⾞x=car_rule(chess1,chess2,chess1[i],next_pos)if x!=None and x!=0:chess1[i]=x[0]print(chess1[i])screen.blit(img_board,(0,0))draw_chess()elif i==8 or i==14: #⾺x=horse_rule(chess2,chess1[i],next_pos)if x!=None and x!=0:chess1[i]=x[0]print(chess1[i])screen.blit(img_board,(0,0))draw_chess()elif i==9 or i==13: #相x=elephant_rule(chess2,chess1[i],next_pos)if x!=None and x!=0:chess1[i]=x[0]print(chess1[i])screen.blit(img_board,(0,0))draw_chess()elif i==10 or i==12: #仕x=attendant_rule(chess1,chess2,chess1[i],next_pos)if x!=None and x!=0:chess1[i]=x[0]print(chess1[i])screen.blit(img_board,(0,0))draw_chess()else: #帥x=boss_rule(chess1,chess2,chess1[i],next_pos,chess2[11]) if x!=None and x!=0:chess1[i]=x[0]print(chess1[i])screen.blit(img_board,(0,0))draw_chess()return xwhite=(255,255,255)black=(0,0,0)def draw_text(text,x,y,size):pygame.font.init()fontObj=pygame.font.SysFont('SimHei',size )textSurfaceObj=fontObj.render(text, True, white,black)textRectObj=textSurfaceObj.get_rect()textRectObj.center=(x,y)screen.blit(textSurfaceObj, textRectObj)pygame.display.update()#判断游戏是否结束def game_over():if red_chess[11]==[-1,-1]:draw_text('⿊⽅胜利',225,525,15)return 1elif black_chess[11]==[-1,-1]:draw_text('红⽅胜利',225,525,15)return 1if __name__=='__main__':all_pos,progress=[],[]for i in range(10):for j in range(9):all_pos.append([j,i])draw_text('红⽅先⾛',225,525,15)chess_kind=0while True:draw_chess()for event in pygame.event.get():if event.type==QUIT:pygame.quit()sys.exit()elif event.type==MOUSEBUTTONDOWN:pos=pygame.mouse.get_pos()print(pos)if chess_kind==0:chess1,chess2=red_chess,black_chesselif chess_kind==1:chess1,chess2=black_chess,red_chessfor i in range(len(chess1)):if chess1[i][0]*50<pos[0]<(chess1[i][0]+1)*50 and chess1[i][1]*50<pos[1]<(chess1[i][1]+1)*50: flag=Falsewhile True:for event in pygame.event.get():if event.type==MOUSEBUTTONDOWN:pos=pygame.mouse.get_pos()next_pos=[pos[0]//50,pos[1]//50]flag=Truebreakif flag==True:breakprogress.append(move(chess1,chess2,next_pos))if progress[-1]!=None and progress[-1]!=0:if chess_kind==0:chess_kind=1elif chess_kind==1:chess_kind=0if chess_kind==1:draw_text('轮到⿊⽅',225,525,15)elif chess_kind==0:draw_text('轮到红⽅',225,525,15)if game_over()==1:while True:for event in pygame.event.get():if event.type==QUIT:pygame.quit()sys.exit()break棋盘图⽚:棋⼦图⽚:运⾏效果:到此这篇关于Python pygame实现中国象棋单机版源码的⽂章就介绍到这了,更多相关pygame实现中国象棋内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

java课程设计---中国象棋对弈系统

java课程设计---中国象棋对弈系统

目录摘要 (1)关键字 (1)正文 (2)1、程序设计说明 (2)1.1 程序的设计及实现 (2)1.1.1搜索引擎的实现(engine包) (2)1.1.2信息传输机制(message包) (3)1.1.3棋子(pieces包) (3)1.2 主控模块(main包) (3)2、运行结果 (5)3、设计体会 (6)附件 (7)程序代码 (7)参考文献资料 (41)1中国象棋对弈系统Java语言程序设计实验报告实验项目名称:中国象棋对弈系统作者姓名与单位:李非计算机101摘要:本文主要是运用java实现具有一定功能的中国象棋对弈系统软件,主要功能如下:a、象棋对弈:红方先走,然后黑方再走,红黑交替,直到一方获胜。

b、新游戏:任何时候可以重新开始一盘新的对弈。

c、悔棋:当走错棋的时候可以悔棋。

d、信息提示:提示当前信息状态。

e、简单的帮助文档:象棋规则介绍、软件的简单介绍和编制说明关键词:java、中国象棋对弈系统2正文:一程序设计说明1.1程序的设计及实现本系统主要有以下4个模块,每个模块对应一个程序包:1、engine:搜索引擎包,系统的核心部分。

2、message:网络对战过程中各种消息及其传递机制的类实现包。

3、main:主界面实现包。

4、pieces:棋子及其相关类实现包。

现就各个包中的要点给与说明。

1.1.1 搜索引擎的实现(engine包)(1) BitBoard.java:位棋盘的实现,见2.4节。

(2) CCEvalue.java:评价函数知识类。

本程序使用开源软件“梦入神蛋”的快速评价函数。

该函数包含子力价值和棋子所在位置的奖励值。

子力价值分别是:帅-0, 仕- 40, 象-40, 马-88, 车-200, 炮-96, 兵-9。

帅是无价的,用0表示。

以马为例,位置的奖励值如下:0,-3,5,4,2,2,5,4,2,2,-3,2,4,6,10,12,20,10,8,2,2,4,6,10,13,11,12,11,15,2,0,5,7,7,14,15,19,15,9,8,2,-10,4,10,15,16,12,11,6,2,0,5,7,7,14,15,19,15,9,8,2,4,6,10,13,11,12,11,15,2,-3,2,4,6,10,12,20,10,8,2,0,-3,5,4,2,2,5,4,2,2上面的每行代表棋盘的一条纵线。

java课程设计中国象棋

java课程设计中国象棋

象棋程序设计1.课程设计目的Java语言是当今流行的网络编程语言,它具有面向对象、跨平台、分布应用等特点。

面向对象的开发方法是当今世界最流行的开发方法,它不仅具有更贴近自然的语义,而且有利于软件的维护和继承,很好的融合了“面向对象”、“跨平台”和“编程简洁”等特性。

随着Java语言的不断发展,它的应用前景将更为宽阔。

本课程设计主要是使用Swing这个Java自带的图形开发工具实现中国象棋棋子及棋盘的绘制,并根据相应的象棋规则,实现在电脑上虚拟出可以供两个人对弈的象棋游戏,从而达到了进一步巩固课堂上所学到的知识,深刻把握Java语言的重要概念及其面向对象的特性,熟练的应用面向对象的思想和设计方法解决实际问题的能力的目的。

2.设计方案论证2.1程序功能象棋是中国一种流传十分广泛的游戏。

下棋双方根据自己对棋局形式的理解和对棋艺规律的掌握,调动车马,组织兵力,协调作战在棋盘--这块特定的战场上进行着象征性的军事战斗。

本程序的功能就是将棋盘和棋子在电脑上模拟出来,双方可以通过鼠标对己方棋子的操作进行对弈。

2.2设计思路象棋,人人会走,把己方的棋子按不同棋子的规则放在棋盘合适的位置上。

象棋包含三个要素:棋盘、棋子和规则。

在本象棋程序的设计上,也大致遵循这三个要素,但是细化为四个方面:棋盘、棋盘上可以走棋的落子点、棋子和象棋规则。

棋盘其实就是一张棋盘的图形,我们要在计算机上的棋盘上落子并不像在现实生活中那么容易,这里说的棋盘充其量只是背景,真正落子的地方必须是我们在图形界面上设定的落子点,不同棋子只能按照各自的规则在这些设定的位置上摆放、搏杀。

2.3设计方法根据前面的细化,程序中分别设计了四个类对应棋盘、落子点、棋子和象棋规则这四个方面。

四个类几乎包括了程序的全部,程序框图如下图所示:图1 程序功能框图2.4详细设计 2.4.1棋子类ChessSwing 中并没有棋子这个组建类,所以我们必须设计一个组件,棋子其实就是圆形 的JLabel ,但Swing 中的JLabel 组件是方形的,没关系,利用JLabel 我们可以创建 圆形的JLabel 组件——Chess 。

中国象棋(代码)

中国象棋(代码)

中国象棋(web版源代码)程序:using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Data.SqlClient;namespace WebApplication1{public partial class WebForm1 : System.Web.UI.Page{int tru = 20;int fals = 40;public ImageButton[,] _Image=new ImageButton[11,10];//将上一次点击点的坐标保存到数据库中的lastx和lastypublic void SaveToLast(){if (Session["user"].ToString() == "red" &&_GetUserState(Session["user"].ToString()) == 20){int x, y, lastx, lasty;x = Getpointx();y = Getpointy();lastx = x;lasty = y;Updatalastx(lastx);Updatalasty(lasty);}if (Session["user"].ToString() == "black" &&_GetUserState(Session["user"].ToString()) == 20){int x, y, lastx, lasty;x = Getpointx();y = Getpointy();lastx = x;lasty = y;Updatalastx(lastx);Updatalasty(lasty);}}//将棋盘上所有棋子图片显示到棋盘上private void _Drawqizi(){//_Init();int i,j,k;if (_GetUserState("red") != 0 && _GetUserState("black") != 0){if (Session["user"].ToString() == "red"){for (i = 1; i <= 10; i++)for (j = 1; j <= 9; j++){k = _GetDataQipan(i, j);_Image[i, j].ImageUrl = _GetImageAdd(k);}}if (Session["user"].ToString() == "black"){for (i = 1; i <= 10; i++)for (j = 1; j <= 9; j++){k = _GetDataQipan(i, j);_Image[11 - i, 10 - j].ImageUrl =_GetImageAdd(k);}}}//初始化:对_Image[,]赋值,对ImageButton进行编号private void _Init(){_Image[1, 1] = ImageButton1; _Image[1, 2] = ImageButton2; _Image[1, 3] = ImageButton3; _Image[1, 4] = ImageButton4; _Image[1, 5] = ImageButton5; _Image[1, 6] = ImageButton6; _Image[1, 7] = ImageButton7; _Image[1, 8] = ImageButton8; _Image[1, 9] = ImageButton9;_Image[2, 1] = ImageButton11; _Image[2, 2] = ImageButton12; _Image[2, 3] = ImageButton13; _Image[2, 4] = ImageButton14; _Image[2, 5] = ImageButton15; _Image[2, 6] = ImageButton16; _Image[2, 7] = ImageButton17; _Image[2, 8] = ImageButton18; _Image[2, 9] = ImageButton19;_Image[3, 1] = ImageButton21; _Image[3, 2] = ImageButton22; _Image[3, 3] = ImageButton23; _Image[3, 4] = ImageButton24; _Image[3, 5] = ImageButton25; _Image[3, 6] = ImageButton26; _Image[3, 7] = ImageButton27; _Image[3, 8] = ImageButton28; _Image[3, 9] = ImageButton29;_Image[4, 1] = ImageButton31; _Image[4, 2] = ImageButton32; _Image[4, 3] = ImageButton33; _Image[4, 4] = ImageButton34; _Image[4, 5] = ImageButton35; _Image[4, 6] = ImageButton36; _Image[4, 7] = ImageButton37; _Image[4, 8] = ImageButton38; _Image[4, 9] = ImageButton39;_Image[5, 1] = ImageButton41; _Image[5, 2] = ImageButton42; _Image[5, 3] = ImageButton43; _Image[5, 4] = ImageButton44; _Image[5, 5] = ImageButton45; _Image[5, 6] = ImageButton46; _Image[5, 7] = ImageButton47; _Image[5, 8] = ImageButton48; _Image[5, 9] = ImageButton49;_Image[6, 1] = ImageButton51; _Image[6, 2] = ImageButton52; _Image[6, 3] = ImageButton53; _Image[6, 4] = ImageButton54; _Image[6, 5] = ImageButton55; _Image[6, 6] = ImageButton56; _Image[6, 7] = ImageButton57; _Image[6, 8] = ImageButton58; _Image[6, 9] = ImageButton59;_Image[7, 1] = ImageButton61; _Image[7, 2] = ImageButton62; _Image[7, 3] = ImageButton63; _Image[7, 4] = ImageButton64; _Image[7, 5] = ImageButton65; _Image[7, 6] = ImageButton66; _Image[7, 7] = ImageButton67; _Image[7, 8] = ImageButton68; _Image[7, 9] = ImageButton69;_Image[8, 1] = ImageButton71; _Image[8, 2] = ImageButton72; _Image[8, 3] = ImageButton73; _Image[8, 4] = ImageButton74; _Image[8, 5] = ImageButton75; _Image[8, 6] = ImageButton76; _Image[8, 7] = ImageButton77; _Image[8, 8] = ImageButton78; _Image[8, 9] = ImageButton79;_Image[9, 1] = ImageButton81; _Image[9, 2] = ImageButton82; _Image[9, 3] = ImageButton83; _Image[9, 4] = ImageButton84; _Image[9, 5] = ImageButton85; _Image[9, 6] = ImageButton86; _Image[9, 7] = ImageButton87; _Image[9, 8] = ImageButton88; _Image[9, 9] = ImageButton89;_Image[10, 1] = ImageButton91; _Image[10, 2] = ImageButton92; _Image[10, 3] = ImageButton93; _Image[10, 4] = ImageButton94; _Image[10, 5] = ImageButton95; _Image[10, 6] = ImageButton96; _Image[10, 7] = ImageButton97; _Image[10, 8] = ImageButton98; _Image[10, 9] = ImageButton99;int i, j;for (i = 1; i <= 10; i++)for (j = 1; j <= 9; j++){_Image[i, j].ImageUrl = "~/image/back.gif";}}//初始化棋盘,将两方棋子放好位private void _InitQizi(){int i = 0, j = 0, k = 0;int[] initqipandata = new int[37];for (i = 1; i <= 10; i++)for (j = 1; j <= 9; j++){_UpdataQipan(i, j, k);}for (i = 0; i <= 36; i++)initqipandata[i] = i;_UpdataQipan(1, 1, initqipandata[8]); _UpdataQipan(1, 2, initqipandata[6]); _UpdataQipan(1, 3, initqipandata[4]); _UpdataQipan(1, 4, initqipandata[2]); _UpdataQipan(1, 5, initqipandata[1]); _UpdataQipan(1,6, initqipandata[3]); _UpdataQipan(1, 7, initqipandata[5]); _UpdataQipan(1, 8, initqipandata[7]); _UpdataQipan(1, 9, initqipandata[9]); _UpdataQipan(3, 2, initqipandata[10]); _UpdataQipan(3, 8, initqipandata[11]); _UpdataQipan(4, 1, initqipandata[12]); _UpdataQipan(4, 3, initqipandata[13]);_UpdataQipan(4, 5, initqipandata[14]); _UpdataQipan(4, 7,initqipandata[15]); _UpdataQipan(4, 9, initqipandata[16]);_UpdataQipan(10, 1, initqipandata[28]); _UpdataQipan(10, 2, initqipandata[26]); _UpdataQipan(10, 3, initqipandata[24]);_UpdataQipan(10, 4, initqipandata[22]); _UpdataQipan(10, 5,initqipandata[21]); _UpdataQipan(10, 6, initqipandata[23]);_UpdataQipan(10, 7, initqipandata[25]); _UpdataQipan(10, 8,initqipandata[27]); _UpdataQipan(10, 9, initqipandata[29]); _UpdataQipan(8, 2, initqipandata[30]); _UpdataQipan(8, 8, initqipandata[31]);_UpdataQipan(7, 1, initqipandata[32]); _UpdataQipan(7, 3,initqipandata[33]); _UpdataQipan(7, 5, initqipandata[34]); _UpdataQipan(7, 7, initqipandata[35]); _UpdataQipan(7, 9, initqipandata[36]);}//获取棋子图片地址private string _GetImageAdd(int xxx){string x="" ;SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("select add_image from qizi where(no_qizi='"+xxx+"');", myconn);myconn.Open();SqlDataReader sr = cmd.ExecuteReader();if (sr.Read())x = sr["add_image"].ToString();//Session["add_image"] = x;myconn.Close();return x;}//获取点击后的图片地址private string _GetImageDownAdd(int xxx){string x ="";SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("select add_image_down from qizi where(no_qizi='" + xxx + "')", myconn);myconn.Open();SqlDataReader sr = cmd.ExecuteReader();if (sr.Read())x = sr["add_image_down"].ToString();myconn.Close();return x;}//读取鼠标点击点的坐标private int Getpointx(){int x = 0;SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("select x from zuobiao", myconn);myconn.Open();SqlDataReader sr = cmd.ExecuteReader();if (sr.Read()){x = int.Parse(sr["x"].ToString());}myconn.Close();return x;}private int Getpointy( ){int x = 0;SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("select y from zuobiao", myconn);myconn.Open();SqlDataReader sr = cmd.ExecuteReader();if (sr.Read()){x = int.Parse(sr["y"].ToString());}myconn.Close();return x;}private int Getpointlastx( ){int x = 0;SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("select lastx from zuobiao", myconn);myconn.Open();SqlDataReader sr = cmd.ExecuteReader();if (sr.Read()){x = int.Parse(sr["lastx"].ToString());}myconn.Close();return x;}private int Getpointlasty( ){int x = 0;SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("select lasty from zuobiao", myconn);myconn.Open();SqlDataReader sr = cmd.ExecuteReader();if (sr.Read()){x = int.Parse(sr["lasty"].ToString());}myconn.Close();return x;}//写入鼠标点击点的坐标private void Updatax(int xxx){SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("update zuobiao set x='" + xxx + "'", myconn);myconn.Open();int aa = cmd.ExecuteNonQuery();myconn.Close();}private void Updatay(int yyy){SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("update zuobiao set y='" + yyy + "'", myconn);myconn.Open();int aa = cmd.ExecuteNonQuery();myconn.Close();}private void Updatalastx(int lastxxx){SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("update zuobiao set lastx='"+lastxxx +"'" , myconn);myconn.Open();int aa = cmd.ExecuteNonQuery();myconn.Close();}private void Updatalasty(int lastyyy){SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("update zuobiao set lasty='"+ lastyyy +"'", myconn);myconn.Open();int aa = cmd.ExecuteNonQuery();myconn.Close();}//以上四个函数的集合,达到一次写入四个坐标值的目的private void _UpdataaZuobiao(int xxx, int yyy, int lastxxx, int lastyyy){Updatax(xxx);Updatay(yyy);Updatalastx(lastxxx);Updatalasty(lastyyy);}//保存当前坐标值到x和yprivate void _UpdatZuobiaoXY(int xxx, int yyy){if (Session["user"].ToString() == "red" &&_GetUserState(Session["user"].ToString()) == 20){Updatax(xxx);Updatay(yyy);}if (Session["user"].ToString() == "black" &&_GetUserState(Session["user"].ToString()) == 20){Updatax(xxx);Updatay(yyy);}}//读取棋盘上的棋子信息private int _GetDataQipan(int xxx, int yyy){int i,data=0;i = (xxx - 1) * 9 + yyy;SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("select data_qipan from qipan where(position='"+i+"')", myconn);myconn.Open();SqlDataReader sr = cmd.ExecuteReader();if (sr.Read())data = int.Parse(sr["data_qipan"].ToString());myconn.Close();return data;}//将棋子信息写入棋盘private void _UpdataQipan(int xxx, int yyy,int data){int i;i = (xxx - 1) * 9 + yyy;SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("update qipan set data_qipan=" + data + "where (position='"+i+"')", myconn);myconn.Open();int aa = cmd.ExecuteNonQuery();myconn.Close();}//读出用户此时状态private int _GetUserState(string id){int data = 0;SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("select state from yonghu where(id='" + id + "')", myconn);myconn.Open();SqlDataReader sr = cmd.ExecuteReader();if (sr.Read())data = int.Parse(sr["state"].ToString());myconn.Close();return data;}//读出用户输赢状态 0表示在进行游戏 20表示赢 40表示输private int _GetUserWin(string id){int data = 0;SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("select winner from yonghu where(id='" + id + "')", myconn);myconn.Open();SqlDataReader sr = cmd.ExecuteReader();if (sr.Read())data = int.Parse(sr["winner"].ToString());myconn.Close();return data;}//写入用户状态private void _UpdataUserState(string id,int sta){SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("update yonghu set state="+ sta + "where (id='" + id + "')", myconn);myconn.Open();int aa = cmd.ExecuteNonQuery();myconn.Close();}//写入用户输赢状态 0表示在进行游戏 20表示赢 40表示输private void _UpdataUserWin(string id, int sta){SqlConnection myconn = newSqlConnection(ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRIN G"].ConnectionString);SqlCommand cmd = new SqlCommand("update yonghu set winner=" + sta + "where (id='" + id + "')", myconn);myconn.Open();int aa = cmd.ExecuteNonQuery();myconn.Close();}protected void Page_Load(object sender, EventArgs e){_Init();// _Test();}//测试程序函数private void _Test(){_UpdataUserState("red",tru);_UpdataUserState("black", tru);}private bool_IsAbleToPut()//********************************************************需要传递x,y,laastx,lasty{if (Session["user"].ToString() == "red" &&_GetUserState(Session["user"].ToString()) == 40)return false;if (Session["user"].ToString() == "black" &&_GetUserState(Session["user"].ToString()) == 40)return false;int x, y, lastx, lasty;int qipandata,lastqipandata;x = Getpointx();y = Getpointy();lastx = Getpointlastx();lasty = Getpointlasty();if (Session["user"].ToString() == "black"){x = 11 - x;y = 10 - y;lastx = 11 - lastx;lasty = 10 - lasty;}qipandata = _GetDataQipan(x, y);lastqipandata = _GetDataQipan(lastx, lasty);// if (lastqipandata==0)// return false;if(Session["user"].ToString() == "red"&&(lastqipandata <= 20 || qipandata >=20))//****************************************************************现以红方为对象return false;if (Session["user"].ToString() == "black" && ((lastqipandata == 0 || lastqipandata >= 20) || (qipandata > 0 && qipandata <= 20)))return false;int i, j, c;//将|帅if (lastqipandata == 1 || lastqipandata == 21){if ((x - lastx) * (y - lasty) != 0) return false;if(Math.Abs(x - lastx) > 1 || Math.Abs(y - lasty) > 1) return false;if (y < 4 || y > 6 || (x > 3 && x < 8)) return false;return true;}//士|仕if (lastqipandata == 2 || lastqipandata == 3 || lastqipandata == 22 || lastqipandata == 23){if ((x - lastx) * (y - lasty) == 0) return false;if(Math.Abs(x - lastx) > 1 || Math.Abs(y - lasty) > 1) return false;if (y < 4 || y > 6 || (x > 3 && x < 8)) return false;return true;}//象|相if (lastqipandata == 4 || lastqipandata == 5 || lastqipandata == 24 || lastqipandata == 25){if ((x - lastx) * (y - lasty) == 0) return false;if (Math.Abs(x - lastx) != 2 || Math.Abs(y - lasty) != 2) return false;if(Session["user"].ToString() == "red"&& x < 6) return false;if (Session["user"].ToString() == "black" && x > 5) return false;i = 0; j = 0;//i,j必须有初始值if (x - lastx == 2){i = x - 1;}if (x - lastx == -2){i = x + 1;}if (y - lasty == 2){j = y - 1;}if (y - lasty == -2){j = y + 1;}if (_GetDataQipan(i, j) != 0) return false;return true;}//马if (lastqipandata == 6 || lastqipandata == 7 || lastqipandata == 26 || lastqipandata == 27){if (Math.Abs(x - lastx) * Math.Abs(y - lasty) != 2)return false;if (x - lastx == 2){if (_GetDataQipan(x - 1, lasty) != 0)return false;}if (x - lastx == -2){if (_GetDataQipan(x + 1, lasty) != 0)return false;}if (y - lasty == 2){if (_GetDataQipan(lastx, y - 1) != 0)return false;}if (y - lasty == -2){if (_GetDataQipan(lastx, y + 1) != 0)return false;}return true;}//车if (lastqipandata == 8 || lastqipandata == 9 || lastqipandata == 28 || lastqipandata == 29){//判断是否直线if ((x - lastx) * (y - lasty) != 0) return false;//判断是否隔有棋子if (x != lastx){if (lastx > x) { int t = x; x = lastx; lastx = t; }for (i = lastx; i <= x; i += 1){if (i != x && i != lastx){if (_GetDataQipan(i, y) != 0)return false;}}}if (y != lasty){if (lasty > y) { int t = y; y = lasty; lasty = t; }for (j = lasty; j <= y; j += 1){if (j != y && j != lasty){if (_GetDataQipan(x, j) != 0)return false;}}}return true;}//炮if (lastqipandata == 10 || lastqipandata == 11 || lastqipandata == 30 || lastqipandata == 31){bool swapflagx = false;bool swapflagy = false;if ((x - lastx) * (y - lasty) != 0) return false;c = 0;if (x != lastx){if (lastx > x) { int t = x; x = lastx; lastx = t; swapflagx = true; }for (i = lastx; i <= x; i += 1){if (i != x && i != lastx){if (_GetDataQipan(i, y) != 0)c = c + 1;//IsAbleToPut = False: Exit Function}}}if (y != lasty){if (lasty > y) { int t = y; y = lasty; lasty = t; swapflagy = true; }for (j = lasty; j <= y; j += 1){if (j != y && j != lasty){if (_GetDataQipan(x, j) != 0)c = c + 1;//IsAbleToPut = False: Exit Function}}}if (c > 1) return false; //与目标处间隔1个以上棋子if (c == 0) //与目标处无间隔棋子{if(swapflagx == true) { int t = x; x = lastx; lastx = t; }if(swapflagy == true) { int t = y; y = lasty; lasty = t; }if (_GetDataQipan(x, y) != 0) return false;}if (c == 1)//与目标处间隔1个棋子{if(swapflagx == true) { int t = x; x = lastx; lastx = t; }if(swapflagy == true) { int t = y; y = lasty; lasty = t; }// if ((IsMyChess(qipan[x, y]) || qipan[x, y] == 0))//return false;//***********ismychess************************************************** ***************************if (qipandata == 0)return false;}return true;}//卒|兵if (lastqipandata == 12 || lastqipandata == 13 || lastqipandata == 14 || lastqipandata == 15 || lastqipandata == 16 || lastqipandata == 32 || lastqipandata == 33 || lastqipandata == 34 || lastqipandata == 35 || lastqipandata == 36){if ((x - lastx) * (y - lasty) != 0)return false;if(Math.Abs(x - lastx) > 1 || Math.Abs(y - lasty) > 1)return false;if (Session["user"].ToString() == "red" && (x >= 6 && (y - lasty) != 0)) return false;if(Session["user"].ToString() == "black"&& (x <= 5 && (y - lasty) != 0)) return false;if(Session["user"].ToString() == "red"&& (x - lastx > 0)) return false;if(Session["user"].ToString() == "black"&& (x - lastx < 0)) return false;return true;}return false;}//移动棋子private void _MoveChess()//********************************************************需要传递x,y,laastx,lasty{//如果能移动则移动棋子if (_IsAbleToPut()){int x, y, lastx, lasty,qipandata, lastqipandata, tr;tr = 0;x = Getpointx();y = Getpointy();lastx = Getpointlastx();lasty = Getpointlasty();if (Session["user"].ToString() == "black"){x = 11 - x;y = 10 - y;lastx = 11 - lastx;lasty = 10 - lasty;}qipandata = _GetDataQipan(x, y);lastqipandata = _GetDataQipan(lastx, lasty);_UpdataQipan(x, y, lastqipandata);_UpdataQipan(lastx, lasty, tr);if (Session["user"].ToString() == "red"){_UpdataUserState("red", fals);_UpdataUserState("black", tru);}if (Session["user"].ToString() == "black"){_UpdataUserState("red", tru);_UpdataUserState("black", fals);}if (qipandata == 1){Response.Write("<script language=javascript>alert('恭喜您,您赢啦');</script>");_UpdataUserState("red", fals);_UpdataUserState("black", fals);Button6.Enabled = true;_UpdataUserWin("red",20);_UpdataUserWin("black", 40);}if (qipandata == 21){Response.Write("<script language=javascript>alert('恭喜您,您赢啦');</script>");_UpdataUserState("red", fals);_UpdataUserState("black", fals);Button6.Enabled = true;_UpdataUserWin("red", 40);_UpdataUserWin("black", 20);}_UpdataaZuobiao(0, 0, 0, 0);}//如果不能移动则更换已方被点击棋子的背景图片}protected void ImageButton1_Click1(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 1; y = 1; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton2_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 1; y = 2; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton3_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 1; y = 3; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton4_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 1; y = 4; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton5_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 1; y = 5; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton6_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 1; y = 6; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton7_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 1; y = 7; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton8_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 1; y = 8; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton9_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 1; y = 9; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton11_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 2; y = 1; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton12_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 2; y = 2; _UpdatZuobiaoXY(x, y);_MoveChess(); _Drawqizi();}protected void ImageButton13_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 2; y = 3; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton14_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 2; y = 4; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton15_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 2; y = 5; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton16_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 2; y = 6; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton17_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 2; y = 7; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton18_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 2; y = 8; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton19_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 2; y = 9; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton21_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 3; y = 1; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton22_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 3; y = 2; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton23_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 3; y = 3; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton24_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 3; y = 4; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton25_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 3; y = 5; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton26_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 3; y = 6; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton27_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 3; y = 7; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton28_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 3; y = 8; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton29_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 3; y = 9; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton31_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 4; y = 1; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton32_Click(object sender,ImageClickEventArgs e){int x, y; SaveToLast(); x = 4; y = 2; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton33_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 4; y = 3; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton34_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 4; y = 4; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton35_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 4; y = 5; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton36_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 4; y = 6; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}protected void ImageButton37_Click(object sender, ImageClickEventArgs e){int x, y; SaveToLast(); x = 4; y = 7; _UpdatZuobiaoXY(x, y); _MoveChess(); _Drawqizi();}。

中国象棋源代码Java程序

中国象棋源代码Java程序

import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.io.*;public class Chess{public static void main(String args[]){new ChessMainFrame("中国象棋:观棋不语真君子,棋死无悔大丈夫");}}class ChessMainFrame extends JFrame implements ActionListener,MouseListener,Runnable{//玩家JLabel play[] = new JLabel[32];//棋盘JLabel image;//窗格Container con;//工具栏JToolBar jmain;//重新开始JButton anew;//悔棋JButton repent;//退出JButton exit;//当前信息JLabel text;//保存当前操作Vector Var;//规则类对象(使于调用方法)ChessRule rule;/**** 单击棋子** chessManClick = true 闪烁棋子并给线程响应** chessManClick = false 吃棋子停止闪烁并给线程响应*/boolean chessManClick;/**** 控制玩家走棋** chessPlayClick=1 黑棋走棋** chessPlayClick=2 红棋走棋默认红棋** chessPlayClick=3 双方都不能走棋*/int chessPlayClick=2;//控制棋子闪烁的线程Thread tmain;//把第一次的单击棋子给线程响应static int Man,i;ChessMainFrame(){new ChessMainFrame("中国象棋");}/**** 构造函数** 初始化图形用户界面*/ChessMainFrame(String Title){//获行客格引用con = this.getContentPane();con.setLayout(null);//实例化规则类rule = new ChessRule();Var = new Vector();//创建工具栏jmain = new JToolBar();text = new JLabel("欢迎使用象棋对弈系统");//当鼠标放上显示信息text.setToolTipText("信息提示");anew = new JButton(" 新游戏 ");anew.setToolTipText("重新开始新的一局");exit = new JButton(" 退出 ");exit.setToolTipText("退出象棋程序程序");repent = new JButton(" 悔棋 ");repent.setToolTipText("返回到上次走棋的位置");//把组件添加到工具栏jmain.setLayout(new GridLayout(0,4));jmain.add(anew);jmain.add(repent);jmain.add(exit);jmain.add(text);jmain.setBounds(0,0,558,30);con.add(jmain);//添加棋子标签drawChessMan();//注册按扭监听anew.addActionListener(this);repent.addActionListener(this);exit.addActionListener(this);//注册棋子移动监听for (int i=0;i<32;i++){con.add(play[i]);play[i].addMouseListener(this);}//添加棋盘标签con.add(image = new JLabel(new ImageIcon("image\\Main.GIF")));image.setBounds(0,30,558,620);image.addMouseListener(this);//注册窗体关闭监听this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent we){System.exit(0);}});//窗体居中Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();Dimension frameSize = this.getSize();if (frameSize.height > screenSize.height){frameSize.height = screenSize.height;}if (frameSize.width > screenSize.width){frameSize.width = screenSize.width;}this.setLocation((screenSize.width - frameSize.width) / 2 - 280 ,(screenSize.height - frameSize.height ) / 2 - 350);//设置this.setIconImage(new ImageIcon("image\\红将.GIF").getImage());this.setResizable(false);this.setTitle(Title);this.setSize(558,670);this.show();}/**** 添加棋子方法*/public void drawChessMan(){//流程控制int i,k;//图标Icon in;//黑色棋子//车in = new ImageIcon("image\\黑车.GIF");for (i=0,k=24;i<2;i++,k+=456){play[i] = new JLabel(in);play[i].setBounds(k,56,55,55);play[i].setName("车1");}//马in = new ImageIcon("image\\黑马.GIF");for (i=4,k=81;i<6;i++,k+=342){play[i] = new JLabel(in);play[i].setBounds(k,56,55,55);play[i].setName("马1");}//相in = new ImageIcon("image\\黑象.GIF");for (i=8,k=138;i<10;i++,k+=228){play[i] = new JLabel(in);play[i].setBounds(k,56,55,55);play[i].setName("象1");}//士in = new ImageIcon("image\\黑士.GIF"); for (i=12,k=195;i<14;i++,k+=114){ play[i] = new JLabel(in);play[i].setBounds(k,56,55,55);play[i].setName("士1");}//卒in = new ImageIcon("image\\黑卒.GIF"); for (i=16,k=24;i<21;i++,k+=114){ play[i] = new JLabel(in);play[i].setBounds(k,227,55,55);play[i].setName("卒1" + i);}//炮in = new ImageIcon("image\\黑炮.GIF"); for (i=26,k=81;i<28;i++,k+=342){ play[i] = new JLabel(in);play[i].setBounds(k,170,55,55);play[i].setName("炮1" + i);}//将in = new ImageIcon("image\\黑将.GIF"); play[30] = new JLabel(in);play[30].setBounds(252,56,55,55);play[30].setName("将1");//红色棋子//车in = new ImageIcon("image\\红车.GIF"); for (i=2,k=24;i<4;i++,k+=456){play[i] = new JLabel(in);play[i].setBounds(k,569,55,55);play[i].setName("车2");}//马in = new ImageIcon("image\\红马.GIF"); for (i=6,k=81;i<8;i++,k+=342){play[i] = new JLabel(in);play[i].setBounds(k,569,55,55);play[i].setName("马2");}//相in = new ImageIcon("image\\红象.GIF"); for (i=10,k=138;i<12;i++,k+=228){ play[i] = new JLabel(in);play[i].setBounds(k,569,55,55);play[i].setName("象2");}//士in = new ImageIcon("image\\红士.GIF"); for (i=14,k=195;i<16;i++,k+=114){ play[i] = new JLabel(in);play[i].setBounds(k,569,55,55);play[i].setName("士2");}//兵in = new ImageIcon("image\\红卒.GIF"); for (i=21,k=24;i<26;i++,k+=114){ play[i] = new JLabel(in);play[i].setBounds(k,398,55,55);play[i].setName("卒2" + i);}//炮in = new ImageIcon("image\\红炮.GIF"); for (i=28,k=81;i<30;i++,k+=342){ play[i] = new JLabel(in);play[i].setBounds(k,455,55,55);play[i].setName("炮2" + i);}//帅in = new ImageIcon("image\\红将.GIF"); play[31] = new JLabel(in);play[31].setBounds(252,569,55,55);play[31].setName("帅2");}/**** 线程方法控制棋子闪烁*/public void run(){while (true){//单击棋子第一下开始闪烁if (chessManClick){play[Man].setVisible(false);//时间控制try{tmain.sleep(200);}catch(Exception e){}play[Man].setVisible(true);}//闪烁当前提示信息以免用户看不见else {text.setVisible(false);//时间控制try{tmain.sleep(250);}catch(Exception e){}text.setVisible(true);}try{tmain.sleep(350);}catch (Exception e){}}}/**** 单击棋子方法*/public void mouseClicked(MouseEvent me){System.out.println("Mouse");//当前坐标int Ex=0,Ey=0;//启动线程if (tmain == null){tmain = new Thread(this);tmain.start();}//单击棋盘(移动棋子)if (me.getSource().equals(image)){//该红棋走棋的时候if (chessPlayClick == 2 && play[Man].getName().charAt(1) == '2'){Ex = play[Man].getX();Ey = play[Man].getY();//移动卒、兵if (Man > 15 && Man < 26){rule.armsRule(Man,play[Man],me);}//移动炮else if (Man > 25 && Man < 30){rule.cannonRule(play[Man],play,me);}//移动车else if (Man >=0 && Man < 4){rule.cannonRule(play[Man],play,me);}//移动马else if (Man > 3 && Man < 8){rule.horseRule(play[Man],play,me);}//移动相、象else if (Man > 7 && Man < 12){rule.elephantRule(Man,play[Man],play,me);}//移动仕、士else if (Man > 11 && Man < 16){rule.chapRule(Man,play[Man],play,me);}//移动将、帅else if (Man == 30 || Man == 31){rule.willRule(Man,play[Man],play,me);}//是否走棋错误(是否在原地没有动)if (Ex == play[Man].getX() && Ey == play[Man].getY()){text.setText(" 红棋走棋");chessPlayClick=2;}else {text.setText(" 黑棋走棋");chessPlayClick=1;}}//if//该黑棋走棋的时候else if (chessPlayClick == 1 && play[Man].getName().charAt(1) == '1'){Ex = play[Man].getX();Ey = play[Man].getY();//移动卒、兵if (Man > 15 && Man < 26){rule.armsRule(Man,play[Man],me);}//移动炮else if (Man > 25 && Man < 30){rule.cannonRule(play[Man],play,me);}//移动车else if (Man >=0 && Man < 4){rule.cannonRule(play[Man],play,me);}//移动马else if (Man > 3 && Man < 8){rule.horseRule(play[Man],play,me);}//移动相、象else if (Man > 7 && Man < 12){rule.elephantRule(Man,play[Man],play,me);}//移动仕、士else if (Man > 11 && Man < 16){rule.chapRule(Man,play[Man],play,me);}//移动将、帅else if (Man == 30 || Man == 31){rule.willRule(Man,play[Man],play,me);}//是否走棋错误(是否在原地没有动)if (Ex == play[Man].getX() && Ey == play[Man].getY()){ text.setText(" 黑棋走棋");chessPlayClick=1;}else {text.setText(" 红棋走棋");chessPlayClick=2;}}//else if//当前没有操作(停止闪烁)chessManClick=false;}//if//单击棋子else{//第一次单击棋子(闪烁棋子)if (!chessManClick){for (int i=0;i<32;i++){//被单击的棋子if (me.getSource().equals(play[i])){//告诉线程让该棋子闪烁Man=i;//开始闪烁chessManClick=true;break;}}//for}//if//第二次单击棋子(吃棋子)else if (chessManClick){//当前没有操作(停止闪烁)chessManClick=false;for (i=0;i<32;i++){//找到被吃的棋子if (me.getSource().equals(play[i])){//该红棋吃棋的时候if (chessPlayClick == 2 && play[Man].getName().charAt(1) == '2'){Ex = play[Man].getX();Ey = play[Man].getY();//卒、兵吃规则if (Man > 15 && Man < 26){rule.armsRule(play[Man],play[i]);}//炮吃规则else if (Man > 25 && Man < 30){rule.cannonRule(0,play[Man],play[i],play,me);}//车吃规则else if (Man >=0 && Man < 4){rule.cannonRule(1,play[Man],play[i],play,me);}//马吃规则else if (Man > 3 && Man < 8){rule.horseRule(play[Man],play[i],play,me);}//相、象吃规则else if (Man > 7 && Man < 12){rule.elephantRule(play[Man],play[i],play);}//士、仕吃棋规则else if (Man > 11 && Man < 16){rule.chapRule(Man,play[Man],play[i],play);}//将、帅吃棋规则else if (Man == 30 || Man == 31){rule.willRule(Man,play[Man],play[i],play);play[Man].setVisible(true);}//是否走棋错误(是否在原地没有动)if (Ex == play[Man].getX() && Ey == play[Man].getY()){text.setText(" 红棋走棋");chessPlayClick=2;break;}else{text.setText(" 黑棋走棋");chessPlayClick=1;break;}}//if//该黑棋吃棋的时候else if (chessPlayClick == 1 &&play[Man].getName().charAt(1) == '1'){Ex = play[Man].getX();Ey = play[Man].getY();//卒吃规则if (Man > 15 && Man < 26){rule.armsRule(play[Man],play[i]);}//炮吃规则else if (Man > 25 && Man < 30){rule.cannonRule(0,play[Man],play[i],play,me);}//车吃规则else if (Man >=0 && Man < 4){rule.cannonRule(1,play[Man],play[i],play,me);}//马吃规则else if (Man > 3 && Man < 8){rule.horseRule(play[Man],play[i],play,me);}//相、象吃规则else if (Man > 7 && Man < 12){rule.elephantRule(play[Man],play[i],play);}//士、仕吃棋规则else if (Man > 11 && Man < 16){rule.chapRule(Man,play[Man],play[i],play);}//将、帅吃棋规则else if (Man == 30 || Man == 31){rule.willRule(Man,play[Man],play[i],play);play[Man].setVisible(true);}//是否走棋错误(是否在原地没有动)if (Ex == play[Man].getX() && Ey == play[Man].getY()){text.setText(" 黑棋走棋");chessPlayClick=1;break;}else {text.setText(" 红棋走棋");chessPlayClick=2;break;}}//else if}//if}//for//是否胜利if (!play[31].isVisible()){JOptionPane.showConfirmDialog(this,"黑棋胜利","玩家一胜利",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE);//双方都不可以在走棋了chessPlayClick=3;text.setText(" 黑棋胜利");}//ifelse if (!play[30].isVisible()){JOptionPane.showConfirmDialog(this,"红棋胜利","玩家二胜利",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE);chessPlayClick=3;text.setText(" 红棋胜利");}//else if}//else}//else}public void mousePressed(MouseEvent me){}public void mouseReleased(MouseEvent me){}public void mouseEntered(MouseEvent me){}public void mouseExited(MouseEvent me){}/**** 定义按钮的事件响应*/public void actionPerformed(ActionEvent ae) { //重新开始按钮if (ae.getSource().equals(anew)){int i,k;//重新排列每个棋子的位置//黑色棋子//车for (i=0,k=24;i<2;i++,k+=456){play[i].setBounds(k,56,55,55);}//马for (i=4,k=81;i<6;i++,k+=342){play[i].setBounds(k,56,55,55);}//相for (i=8,k=138;i<10;i++,k+=228){play[i].setBounds(k,56,55,55);}//士for (i=12,k=195;i<14;i++,k+=114){play[i].setBounds(k,56,55,55);}//卒for (i=16,k=24;i<21;i++,k+=114){ play[i].setBounds(k,227,55,55); }//炮for (i=26,k=81;i<28;i++,k+=342){ play[i].setBounds(k,170,55,55); }//将play[30].setBounds(252,56,55,55);//红色棋子//车for (i=2,k=24;i<4;i++,k+=456){ play[i].setBounds(k,569,55,55); }//马for (i=6,k=81;i<8;i++,k+=342){ play[i].setBounds(k,569,55,55); }//相for (i=10,k=138;i<12;i++,k+=228){ play[i].setBounds(k,569,55,55); }//士for (i=14,k=195;i<16;i++,k+=114){ play[i].setBounds(k,569,55,55); }//兵for (i=21,k=24;i<26;i++,k+=114){ play[i].setBounds(k,398,55,55); }//炮for (i=28,k=81;i<30;i++,k+=342){ play[i].setBounds(k,455,55,55); }//帅play[31].setBounds(252,569,55,55);chessPlayClick = 2;text.setText(" 红棋走棋");for (i=0;i<32;i++){play[i].setVisible(true);}//清除Vector中的容Var.clear();}//悔棋按钮else if (ae.getSource().equals(repent)){try{//获得setVisible属性值String S = (String)Var.get(Var.size()-4);//获得X坐标int x = Integer.parseInt((String)Var.get(Var.size()-3));//获得Y坐标int y = Integer.parseInt((String)Var.get(Var.size()-2));//获得索引int M = Integer.parseInt((String)Var.get(Var.size()-1));//赋给棋子play[M].setVisible(true);play[M].setBounds(x,y,55,55);if (play[M].getName().charAt(1) == '1'){text.setText(" 黑棋走棋");chessPlayClick = 1;}else{text.setText(" 红棋走棋");chessPlayClick = 2;}//删除用过的坐标Var.remove(Var.size()-4);Var.remove(Var.size()-3);Var.remove(Var.size()-2);Var.remove(Var.size()-1);//停止旗子闪烁chessManClick=false;}catch(Exception e){}}//退出else if (ae.getSource().equals(exit)){int j=JOptionPane.showConfirmDialog(this,"真的要退出吗?","退出",JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE);if (j == JOptionPane.YES_OPTION){System.exit(0);}}}/*定义中国象棋规则的类*/class ChessRule {/**卒子的移动规则*/public void armsRule(int Man,JLabel play,MouseEvent me){ //黑卒向下if (Man < 21){//向下移动、得到终点的坐标模糊成合法的坐标if ((me.getY()-play.getY()) > 27 && (me.getY()-play.getY()) < 86 && (me.getX()-play.getX()) < 55 && (me.getX()-play.getX()) > 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(play.getX(),play.getY()+57,55,55);}//向右移动、得到终点的坐标模糊成合法的坐标、必须过河else if (play.getY() > 284 && (me.getX() - play.getX()) >= 57 && (me.getX() - play.getX()) <= 112){play.setBounds(play.getX()+57,play.getY(),55,55);}//向左移动、得到终点的坐标模糊成合法的坐标、必须过河else if (play.getY() > 284 && (play.getX() - me.getX()) >= 2 && (play.getX() - me.getX()) <=58){//模糊坐标play.setBounds(play.getX()-57,play.getY(),55,55);}}//红卒向上else{//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));//向上移动、得到终点的坐标模糊成合法的坐标if ((me.getX()-play.getX()) >= 0 && (me.getX()-play.getX()) <= 55 && (play.getY()-me.getY()) >27 && play.getY()-me.getY() < 86){play.setBounds(play.getX(),play.getY()-57,55,55);}//向右移动、得到终点的坐标模糊成合法的坐标、必须过河else if (play.getY() <= 341 && (me.getX() - play.getX()) >= 57 && (me.getX() - play.getX()) <= 112){play.setBounds(play.getX()+57,play.getY(),55,55);}//向左移动、得到终点的坐标模糊成合法的坐标、必须过河else if (play.getY() <= 341 && (play.getX() - me.getX()) >= 3 && (play.getX() - me.getX()) <=58){play.setBounds(play.getX()-57,play.getY(),55,55);}}}//卒移动结束/**卒吃棋规则*/public void armsRule(JLabel play1,JLabel play2){//向右走if ((play2.getX() - play1.getX()) <= 112 && (play2.getX() - play1.getX()) >= 57 && (play1.getY() - play2.getY()) < 22 && (play1.getY() - play2.getY()) > -22 && play2.isVisible() && play1.getName().charAt(1)!=play2.getName().charAt(1)){//黑棋要过河才能右吃棋if (play1.getName().charAt(1) == '1' && play1.getY() > 284 && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}//红棋要过河才左能吃棋else if (play1.getName().charAt(1) == '2' && play1.getY() < 341 && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}}//向左走else if ((play1.getX() - play2.getX()) <= 112 && (play1.getX() - play2.getX()) >= 57 && (play1.getY() - play2.getY()) < 22 && (play1.getY() - play2.getY()) > -22 && play2.isVisible() && play1.getName().charAt(1)!=play2.getName().charAt(1)){//黑棋要过河才能左吃棋if (play1.getName().charAt(1) == '1' && play1.getY() > 284 && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}//红棋要过河才能右吃棋else if (play1.getName().charAt(1) == '2' && play1.getY() < 341 && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}}//向上走else if (play1.getX() - play2.getX() >= -22 && play1.getX() - play2.getX() <= 22 && play1.getY() - play2.getY() >= -112 && play1.getY() - play2.getY() <= 112){//黑棋不能向上吃棋if (play1.getName().charAt(1) == '1' && play1.getY() < play2.getY() && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}//红棋不能向下吃棋else if (play1.getName().charAt(1) == '2' && play1.getY() > play2.getY() && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}}//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play1.isVisible()));Var.add(String.valueOf(play1.getX()));Var.add(String.valueOf(play1.getY()));Var.add(String.valueOf(Man));//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play2.isVisible()));Var.add(String.valueOf(play2.getX()));Var.add(String.valueOf(play2.getY()));Var.add(String.valueOf(i));}//卒吃结束/**炮、车移动规则*/public void cannonRule(JLabel play,JLabel playQ[],MouseEventme){//起点和终点之间是否有棋子int Count = 0;//上、下移动if (play.getX() - me.getX() <= 0 && play.getX() - me.getX() >= -55){//指定所有模糊Y坐标for (int i=56;i<=571;i+=57){//移动的Y坐标是否有指定坐标相近的if (i - me.getY() >= -27 && i - me.getY() <= 27){//所有的棋子for (int j=0;j<32;j++){//找出在同一条竖线的所有棋子、并不包括自己if (playQ[j].getX() - play.getX() >= -27 && playQ[j].getX() - play.getX() <= 27 && playQ[j].getName()!=play.getName() && playQ[j].isVisible()){//从起点到终点(从左到右)for (int k=play.getY()+57;k<i;k+=57){//大于起点、小于终点的坐标就可以知道中间是否有棋子if (playQ[j].getY() < i && playQ[j].getY() > play.getY()){//中间有一个棋子就不可以从这条竖线过去Count++;break;}}//for//从起点到终点(从右到左)for (int k=i+57;k<play.getY();k+=57){//找起点和终点的棋子if (playQ[j].getY() < play.getY() && playQ[j].getY() > i){Count++;break;}}//for}//if}//for//起点和终点没有棋子就可以移动了if (Count == 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(play.getX(),i,55,55);break;}}//if}//for}//if//左、右移动else if (play.getY() - me.getY() >=-27 && play.getY() - me.getY() <= 27){//指定所有模糊X坐标for (int i=24;i<=480;i+=57){//移动的X坐标是否有指定坐标相近的if (i - me.getX() >= -55 && i-me.getX() <= 0){//所有的棋子for (int j=0;j<32;j++){//找出在同一条横线的所有棋子、并不包括自己if (playQ[j].getY() - play.getY() >= -27 && playQ[j].getY() - play.getY() <= 27 && playQ[j].getName()!=play.getName() && playQ[j].isVisible()){//从起点到终点(从上到下)for (int k=play.getX()+57;k<i;k+=57){//大于起点、小于终点的坐标就可以知道中间是否有棋子if (playQ[j].getX() < i && playQ[j].getX() > play.getX()){//中间有一个棋子就不可以从这条横线过去Count++;break;}}//for//从起点到终点(从下到上)for (int k=i+57;k<play.getX();k+=57){//找起点和终点的棋子if (playQ[j].getX() < play.getX() && playQ[j].getX() > i){Count++;break;}}//for}//if}//for//起点和终点没有棋子if (Count == 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(i,play.getY(),55,55);break;}}//if}//for}//else}//炮、车移动方法结束/**炮、车吃棋规则*/public void cannonRule(int Chess,JLabel play,JLabel playTake,JLabel playQ[],MouseEvent me){//起点和终点之间是否有棋子int Count = 0;//所有的棋子for (int j=0;j<32;j++){//找出在同一条竖线的所有棋子、并不包括自己if (playQ[j].getX() - play.getX() >= -27 && playQ[j].getX() - play.getX() <= 27 && playQ[j].getName()!=play.getName() && playQ[j].isVisible()){//自己是起点被吃的是终点(从上到下)for (int k=play.getY()+57;k<playTake.getY();k+=57){//大于起点、小于终点的坐标就可以知道中间是否有棋子if (playQ[j].getY() < playTake.getY() && playQ[j].getY() > play.getY()){//计算起点和终点的棋子个数Count++;break;}}//for//自己是起点被吃的是终点(从下到上)for (int k=playTake.getY();k<play.getY();k+=57){//找起点和终点的棋子if (playQ[j].getY() < play.getY() && playQ[j].getY() > playTake.getY()){Count++;break;}}//for}//if//找出在同一条竖线的所有棋子、并不包括自己else if (playQ[j].getY() - play.getY() >= -10 && playQ[j].getY() - play.getY() <= 10 && playQ[j].getName()!=play.getName() && playQ[j].isVisible()){//自己是起点被吃的是终点(从左到右)for (int k=play.getX()+50;k<playTake.getX();k+=57){//大于起点、小于终点的坐标就可以知道中间是否有棋子if (playQ[j].getX() < playTake.getX() && playQ[j].getX() > play.getX()){Count++;break;}}//for//自己是起点被吃的是终点(从右到左)for (int k=playTake.getX();k<play.getX();k+=57){//找起点和终点的棋子if (playQ[j].getX() < play.getX() && playQ[j].getX() > playTake.getX()){Count++;break;}}//for}//if}//for//起点和终点之间要一个棋子是炮的规则、并不能吃自己的棋子if (Count == 1 && Chess == 0 && playTake.getName().charAt(1) != play.getName().charAt(1)){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(playTake.isVisible()));Var.add(String.valueOf(playTake.getX()));Var.add(String.valueOf(playTake.getY()));Var.add(String.valueOf(i));playTake.setVisible(false);play.setBounds(playTake.getX(),playTake.getY(),55,55);}//起点和终点之间没有棋子是车的规则、并不能吃自己的棋子else if (Count ==0 && Chess == 1 && playTake.getName().charAt(1) != play.getName().charAt(1)){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(playTake.isVisible()));Var.add(String.valueOf(playTake.getX()));Var.add(String.valueOf(playTake.getY()));Var.add(String.valueOf(i));playTake.setVisible(false);play.setBounds(playTake.getX(),playTake.getY(),55,55);}}//炮、车吃棋方法结束/**马移动规则*/public void horseRule(JLabel play,JLabel playQ[],MouseEvent me){ //保存坐标和障碍int Ex=0,Ey=0,Move=0;//上移、左边if (play.getX() - me.getX() >= 2 && play.getX() - me.getX() <= 57 && play.getY() - me.getY() >= 87 && play.getY() - me.getY() <= 141){ //合法的Y坐标for (int i=56;i<=571;i+=57){//移动的Y坐标是否有指定坐标相近的if (i - me.getY() >= -27 && i - me.getY() <= 27){Ey = i;break;}}//合法的X坐标for (int i=24;i<=480;i+=57){//移动的X坐标是否有指定坐标相近的if (i - me.getX() >= -55 && i-me.getX() <= 0){Ex = i;break;}}//正前方是否有别的棋子for (int i=0;i<32;i++){if (playQ[i].isVisible() && play.getX() - playQ[i].getX() == 0 && play.getY() - playQ[i].getY() == 57 ){Move = 1;break;}}//可以移动该棋子if (Move == 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(Ex,Ey,55,55);}}//if//左移、上边else if (play.getY() - me.getY() >= 27 && play.getY() - me.getY() <= 86 && play.getX() - me.getX() >= 70 && play.getX() - me.getX() <= 130){//Yfor (int i=56;i<=571;i+=57){if (i - me.getY() >= -27 && i - me.getY() <= 27){Ey = i;}}//Xfor (int i=24;i<=480;i+=57){if (i - me.getX() >= -55 && i-me.getX() <= 0){Ex = i;}}//正左方是否有别的棋子for (int i=0;i<32;i++){if (playQ[i].isVisible() && play.getY() - playQ[i].getY() == 0 && play.getX() - playQ[i].getX() == 57 ){Move = 1;break;}}if (Move == 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(Ex,Ey,55,55);}}//else//下移、右边else if (me.getY() - play.getY() >= 87 && me.getY() - play.getY() <= 141 && me.getX() - play.getX() <= 87 && me.getX() - play.getX() >= 2 ){//Yfor (int i=56;i<=571;i+=57){if (i - me.getY() >= -27 && i - me.getY() <= 27){Ey = i;}}//Xfor (int i=24;i<=480;i+=57){if (i - me.getX() >= -55 && i-me.getX() <= 0){Ex = i;}}//正下方是否有别的棋子for (int i=0;i<32;i++){if (playQ[i].isVisible() && play.getX() - playQ[i].getX() == 0 && playQ[i].getY() - play.getY() == 57 ){Move = 1;break;}}if (Move == 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(Ex,Ey,55,55);}}//else//上移、右边else if (play.getY() - me.getY() >= 87 && play.getY() - me.getY() <= 141 && me.getX() - play.getX() <= 87 && me.getX() - play.getX() >= 30 ){//合法的Y坐标for (int i=56;i<=571;i+=57){if (i - me.getY() >= -27 && i - me.getY() <= 27){。

联网式-中国象棋VB源代码 萨云轩 工作室

联网式-中国象棋VB源代码 萨云轩  工作室

Option ExplicitPublic bIsNet As BooleanConst FF_EMP = -1Const FF_SIDE1 = 0Const FF_SIDE2 = 1Dim local_side As IntegerDim pos_side As IntegerDim Chess_On As IntegerConst FF_US_INITALL = 0Const FF_US_INITNET = 1Const FF_US_INITLOCAL = 2Const FF_US_NET_CON = 3Const FF_US_USE_CON = 4Dim b_Server As BooleanDim b_isCon As BooleanPublic m_Set As StringDim m_BeSet As String'USER STA TEEnum FF_UA_STA TEFF_UA_INITFF_UA_WAITINGFF_UA_USEFF_UA_INV ALIDEnd EnumDim m_State As FF_UA_STA TEPrivate Sub TransSide(ByRef side As Integer) If side = FF_SIDE1 Thenside = FF_SIDE2Elseside = FF_SIDE1End IfEnd SubPrivate Sub TransState(method As Integer) main.WindowState = vbNormalSelect Case methodCase FF_US_INITALLInitalBoardm_State = FF_UA_INV ALIDc_MunNew.V isible = Falsec_MunLoad.Enabled = Truec_eState.Text = ""c_eMsg.Text = ""c_CmdSay.Enabled = Falsec_MunShow.Checked = bIsNetpos_side = FF_SIDE1Chess_On = FF_EMPc_spChessOn.V isible = Falsec_sUse.Closeb_isCon = FalseCase FF_US_INITNETfrm_net.V isible = Truemain.Width = 8835pic_noclick.Visible = Truepic_click.Visible = Falsec_sColor.FillColor = &H8000000Fc_CmdCon.Enabled = TrueCase FF_US_INITLOCALfrm_net.V isible = Falsemain.Width = 5880pic_noclick.Visible = Falsepic_click.Visible = Truec_sColor.FillColor = vbRedlocal_side = FF_SIDE1Case FF_US_NET_CONc_CmdSay.Enabled = Trueb_isCon = Truec_CmdCon.Enabled = Falsec_eState.Text = "网络连接成功" Case FF_US_USE_CONm_State = FF_UA_USEc_MunLoad.Enabled = Falsec_MunNew.V isible = Falsec_eState.Text = "开始"End SelectEnd SubPrivate Sub InitalBoard()Dim i As IntegerDim x_step, d_step As Integerx_step = 0d_step = -1For i = 0 To 8c_chess(i).Top = 0c_chess(i).Left = 2595 + x_step * d_stepc_chess(i + 16).Top = 5400c_chess(i + 16).Left = c_chess(i).LeftIf (i / 2 = Int(i / 2)) Then x_step = x_step + 600d_step = -d_stepNext iFor i = 0 To 1c_chess(i + 9).Top = 1200c_chess(i + 9).Left = 795 + i * 3600c_chess(i + 25).Top = 4200c_chess(i + 25).Left = c_chess(i + 9).LeftNext iFor i = 0 To 4c_chess(i + 11).Top = 1800c_chess(i + 11).Left = 195 + i * 1200c_chess(i + 27).Top = 3600c_chess(i + 27).Left = c_chess(i + 11).LeftNext iFor i = 0 To 31c_chess(i).V isible = TrueNext iEnd SubPrivate Function DuiJiang() As BooleanDim i, count, temp As IntegerIf Not c_chess(0).Left = c_chess(16).Left ThenDuiJiang = FalseExit FunctionEnd Iftemp = Sgn(c_chess(16).Top - c_chess(0).Top)count = 0For i = c_chess(0).Top / 600 + temp To c_chess(16).Top / 600 - temp Step temp If FindChessInPos((c_chess(0).Left - 195) / 600, i) > -1 Then count = count + 1 Next iIf count = 0 ThenDuiJiang = TrueExit FunctionEnd IfDuiJiang = FalseEnd FunctionPrivate Sub Die(ByV al chess_die As Integer)If chess_die = 0 ThenMsgBox "黑方输了", vbOKOnly, App.LegalTrademarksElseMsgBox "红方输了", vbOKOnly, App.LegalTrademarksEnd IfIf bIsNet = True ThenInitalBoardm_State = FF_UA_INITc_MunNew.V isible = Truec_MunLoad.Enabled = Truec_eState.Text = ""c_eMsg.Text = ""c_CmdSay.Enabled = Truec_MunShow.Checked = bIsNetpos_side = FF_SIDE1Chess_On = FF_EMPc_spChessOn.V isible = Falsefrm_net.V isible = Truepic_noclick.Visible = Truepic_click.Visible = Falsec_sColor.FillColor = &H8000000FElseTransState FF_US_INITALLTransState FF_US_INITLOCALEnd IfEnd SubPrivate Function GoChess(ByV al chess As Integer, ByV al x_off As Integer _ , ByV al y_off As Integer) As BooleanDim use_side As IntegerDim x_begin, y_begin As IntegerDim Distent As SingleDim i As IntegerIf chess > 15 Thenuse_side = FF_SIDE2Elseuse_side = FF_SIDE1End Ifx_begin = (c_chess(chess).Left - 195) / 600y_begin = (c_chess(chess).Top) / 600Distent = Sqr((x_off - x_begin) ^ 2 + (y_off - y_begin) ^ 2)Select Case Int((chess - use_side * 16 + 1) / 2)Case 0 'jianIf Distent > 1 Then GoTo errhandleIf x_off < 3 Or x_off > 5 Then GoTo errhandleIf GetSelf(chess, y_off) > 2 Then GoTo errhandlec_chess(chess).Left = x_off * 600 + 195If DuiJiang = True ThenMsgBox "Can Not this col", vbOKOnly, App.LegalTrademarksc_chess(chess).Left = x_begin * 600 + 195GoTo errhandleEnd IfCase 1 'shiIf Distent < 1.4 Or Distent > 1.5 Then GoTo errhandleIf x_off < 3 Or x_off > 5 Then GoTo errhandleIf GetSelf(chess, y_off) > 2 Then GoTo errhandleCase 2 'xiangIf Distent < 2.8 Or Distent > 2.9 Then GoTo errhandleIf GetSelf(chess, y_off) > 4 Then GoTo errhandleIf FindChessInPos((x_off + x_begin) / 2, (y_begin + y_off) / 2) > -1 Then GoTo errhandle Case 3 'maIf Distent < 2.2 Or Distent > 2.3 Then GoTo errhandleIf FindChessInPos(x_off - Sgn(x_off - x_begin), y_off - Sgn(y_off - y_begin)) > -1 Then GoTo errhandleCase 4 'cheIf (Not x_begin = x_off) And (Not y_begin = y_off) Then GoTo errhandleIf x_begin = x_off ThenFor i = y_begin + Sgn(y_off - y_begin) To y_off - Sgn(y_off - y_begin) Step Sgn(y_off - y_begin)If Not FindChessInPos(x_off, i) = -1 Then GoTo errhandleNext iEnd IfIf y_begin = y_off ThenFor i = x_begin + Sgn(x_off - x_begin) To x_off - Sgn(x_off - x_begin) Step Sgn(x_off - x_begin)If Not FindChessInPos(i, y_off) = -1 Then GoTo errhandleNext iEnd IfCase 5 'paoIf (Not x_begin = x_off) And (Not y_begin = y_off) Then GoTo errhandleIf x_begin = x_off ThenFor i = y_begin + Sgn(y_off - y_begin) To y_off Step Sgn(y_off - y_begin) If Not FindChessInPos(x_off, i) = -1 Then GoTo errhandleNext iEnd IfIf y_begin = y_off ThenFor i = x_begin + Sgn(x_off - x_begin) To x_off Step Sgn(x_off - x_begin) If Not FindChessInPos(i, y_off) = -1 Then GoTo errhandleNext iEnd IfCase Else 'bingIf Distent > 1 Then GoTo errhandleIf GetSelf(chess, y_off) < GetSelf(chess, y_begin) Then GoTo errhandleIf GetSelf(chess, y_off) < 5 And (Not x_off = x_begin) Then GoTo errhandle End Selectc_chess(chess).Left = x_off * 600 + 195c_chess(chess).Top = y_off * 600If bIsNet = False ThenTransSide local_sideIf c_sColor.FillColor = vbRed Thenc_sColor.FillColor = vbBlueElsec_sColor.FillColor = vbRedEnd IfElsepic_click.Visible = Not pic_click.Visiblepic_noclick.Visible = Not pic_click.VisibleEnd IfTransSide pos_sideGoChess = TrueExit Functionerrhandle:GoChess = FalseEnd FunctionPrivate Function FindChessInPos(ByV al X As Integer, ByV al Y As Integer) As Integer Dim i As IntegerFor i = 0 To 31If c_chess(i).V isible = True And c_chess(i).Top / 600 = Y And (c_chess(i).Left - 195) / 600 = X ThenFindChessInPos = iExit FunctionEnd IfNext iFindChessInPos = -1End FunctionPrivate Sub TransBoard()Dim i, x_off, y_off As IntegerFor i = 0 To 31x_off = (c_chess(i).Left - 195) / 600x_off = 8 - x_offy_off = c_chess(i).Top / 600y_off = 9 - y_offc_chess(i).Left = x_off * 600 + 195c_chess(i).Top = y_off * 600Next iEnd SubPrivate Function GetSelf(ByV al chess As Integer, ByV al Y As Integer) As IntegerDim temp_side As IntegerIf bIsNet = True Thentemp_side = Int(chess / 16)If Not local_side = temp_side ThenGetSelf = 9 - YElseGetSelf = YEnd IfElseIf chess > 15 ThenGetSelf = 9 - YElseGetSelf = YEnd IfEnd IfEnd FunctionPrivate Sub c_chess_Click(Index As Integer)If (bIsNet = True) And (Not m_State = FF_UA_USE) Then Exit SubIf Not pos_side = local_side Then Exit SubDim i As IntegerDim count As IntegerDim x_off, y_off, x_begin, y_begin As Integerx_off = (c_chess(Index).Left - 195) / 600y_off = (c_chess(Index).Top) / 600If Not Int(Index / 16) = local_side ThenChess_On = Indexc_spChessOn.Left = c_chess(Chess_On).Left - 60c_spChessOn.Top = c_chess(Chess_On).Top - 60c_spChessOn.V isible = TrueElseIf Chess_On = FF_EMP Then Exit SubIf GoChess(Chess_On, x_off, y_off) = True ThenIf bIsNet = True And m_State = FF_UA_USE Then c_sUse.SendData _"Post " + Chr(Chess_On + 65) + Chr(x_off + 48) + Chr(y_off + 48) c_chess(Index).V isible = FalseIf Index = 0 Or Index = 16 ThenDie IndexExit SubEnd IfChess_On = FF_EMPc_spChessOn.V isible = FalseElseIf Chess_On = 9 Or Chess_On = 10 Or Chess_On = 25 Or Chess_On = 25 Or Chess_On = 26 Thenx_begin = (c_chess(Chess_On).Left - 195) / 600y_begin = (c_chess(Chess_On).Top) / 600count = 0If (Not x_begin = x_off) And (Not y_begin = y_off) Then Exit SubIf x_begin = x_off ThenFor i = y_begin + Sgn(y_off - y_begin) To y_off - Sgn(y_off - y_begin) Step Sgn(y_off - y_begin)If Not FindChessInPos(x_off, i) = -1 Then count = count + 1Next iEnd IfIf y_begin = y_off ThenFor i = x_begin + Sgn(x_off - x_begin) To x_off - Sgn(x_off - x_begin) Step Sgn(x_off - x_begin)If Not FindChessInPos(i, y_off) = -1 Then count = count + 1Next iEnd IfEnd IfEnd IfIf count = 1 ThenIf bIsNet = True And m_State = FF_UA_USE Then c_sUse.SendData _ "Post " + Chr(Chess_On + 65) + Chr(x_off + 48) + Chr(y_off + 48) c_chess(Chess_On).Top = c_chess(Index).Topc_chess(Chess_On).Left = c_chess(Index).Leftc_chess(Index).V isible = FalseIf Index = 0 Or Index = 16 ThenDie IndexExit SubEnd IfChess_On = FF_EMPc_spChessOn.V isible = FalseIf bIsNet = False ThenTransSide local_sideIf c_sColor.FillColor = vbRed Thenc_sColor.FillColor = vbBlueElsec_sColor.FillColor = vbRedEnd IfElsepic_click.Visible = Not pic_click.Visiblepic_noclick.Visible = Not pic_noclick.VisibleEnd IfTransSide pos_sideEnd IfEnd IfEnd SubPrivate Sub c_cmdReset_Click()Load f_Gnetf_Gnet.Show vbModal, mainTransState FF_US_INITALLIf bIsNet = True ThenTransState FF_US_INITNETElseTransState FF_US_INITLOCALEnd IfEnd SubPrivate Sub c_MunExit_Click()Unload MeEnd SubPrivate Sub c_MunLoad_Click()On Error GoTo calcelhandlec_cdgFile.DialogTitle = "Load"c_cdgFile.ShowOpenDim i, x_off, y_off, temp As IntegerDim message As Stringmessage = "Load "Open c_cdgFile.FileName For Input As #2Input #2, local_side, pos_sidemessage = message + Chr(local_side + 65)message = message + Chr(pos_side + 65)If local_side = FF_SIDE1 Thenc_sColor.FillColor = vbRedElsec_sColor.FillColor = vbBlueEnd IfIf local_side = pos_side Thenpic_noclick.Visible = Falsepic_click.Visible = TrueElsepic_click.Visible = Falsepic_noclick.Visible = TrueEnd IfFor i = 0 To 31Input #2, temp, y_off, x_offmessage = message + Chr(temp + 65) + Chr(x_off + 48) + Chr(y_off + 48) c_chess(i).Left = x_off * 600 + 195c_chess(i).Top = y_off * 600If temp = 0 Thenc_chess(i).V isible = FalseElsec_chess(i).V isible = TrueEnd IfNext iClose #2c_MunLoad.Enabled = Falsemessage = message + " Eold"If bIsNet = True Thenc_sUse.SendData messageEnd Ifm_State = FF_UA_USEExit Subcalcelhandle:Close #2End SubPrivate Sub c_MunNew_Click()If b_isCon = False Or b_Server = False Then Exit SubMsgBox "请选单双让对方猜先", vbOKOnly, App.LegalTrademarks Load f_Gfstf_Gfst.Show vbModal, mainc_sUse.SendData "Gues " + m_Setc_MunNew.V isible = FalseEnd SubPrivate Sub c_MunSave_Click()On Error GoTo calcelhandlec_cdgFile.DialogTitle = "Save"c_cdgFile.ShowSaveDim i As IntegerOpen c_cdgFile.FileName For Output As #1Print #1, local_side, pos_sideFor i = 0 To 31If c_chess(i).V isible = True ThenPrint #1, 1, (c_chess(i).Top / 600), ((c_chess(i).Left - 195) / 600) ElsePrint #1, 0, (c_chess(i).Top / 600), ((c_chess(i).Left - 195) / 600) End IfNext iExit Subcalcelhandle:Close #1End SubPrivate Sub c_MunShow_Click()c_MunShow.Checked = Not c_MunShow.Checkedfrm_net.V isible = c_MunShow.CheckedIf frm_net.V isible = True Thenmain.Width = 8835Elsemain.Width = 5880End IfEnd SubPrivate Sub c_pboard_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) If (bIsNet = True) And (Not m_State = FF_UA_USE) Then Exit SubIf Not pos_side = local_side Then Exit SubIf Chess_On = FF_EMP Then Exit SubIf X < 195 Or Y < 0 Then Exit SubIf X > 9 * 600 + 195 Or Y > 10 * 600 Then Exit SubDim x_off, y_off As Integerx_off = Int((X - 195) / 600)y_off = Int(Y / 600)If X - (x_off * 600 + 195) > 475 Or Y - y_off * 600 > 475 Then Exit SubIf GoChess(Chess_On, x_off, y_off) = False Then Exit SubIf bIsNet = True And m_State = FF_UA_USE Then c_sUse.SendData _"Post " + Chr(Chess_On + 65) + Chr(x_off + 48) + Chr(y_off + 48)Chess_On = FF_EMPc_spChessOn.V isible = FalseEnd SubPrivate Sub Form_Load()On Error GoTo errhandleTransState FF_US_INITALLIf bIsNet = True ThenTransState FF_US_INITNETc_sListen.ListenElseTransState FF_US_INITLOCALEnd IfExit Suberrhandle:MsgBox "System Wrong", vbOKOnly, App.LegalTrademarksEndEnd SubPrivate Sub c_CmdCon_Click()On Error GoTo errhandlec_sUse.LocalPort = 0c_sUse.RemotePort = 6112c_sUse.RemoteHost = c_eAddr.Textc_sUse.Connectc_CmdCon.Enabled = FalseExit Suberrhandle:MsgBox "Net wrong, Click <Connect> for a while", vbOKOnly, App.LegalTrademarksEnd SubPrivate Sub c_sListen_ConnectionRequest(ByV al requestID As Long)If b_isCon = True Or (Not c_sUse.State = 0) Then Exit Subc_sUse.LocalPort = 0c_sUse.Accept requestIDTransState FF_US_NET_CONb_Server = TrueEnd SubPrivate Sub c_sListen_Error(ByV al Number As Integer, Description As String, ByV al Scode As Long, ByV al Source As String, ByV al HelpFile As String, ByV al HelpContext As Long, CancelDisplay As Boolean)MsgBox Description, vbOKOnly, App.LegalTrademarksEndEnd SubPrivate Sub c_sUse_Close()MsgBox "连接已经关闭!!", vbOKOnly, App.LegalTrademarksTransState FF_US_INITALLTransState FF_US_INITNETc_eAddr.Text = c_sUse.RemoteHostIPEnd SubPrivate Sub c_sUse_Connect()c_sUse.SendData "Init"b_Server = FalseTransState FF_US_NET_CONm_State = FF_UA_INITEnd SubPrivate Sub c_sUse_DataArrival(ByV al bytesTotal As Long)If bIsNet = False Then Exit SubDim message As StringDim x_off, y_off, i, temp As Integerc_sUse.GetData message, vbString, bytesTotalSelect Case Left(message, 4)Case "Msag"c_eMsg.Text = Right(message, Len(message) - 5)Case "Init"If (Not m_State = FF_UA_INV ALID) Or (b_Server = False) Then _ GoTo Errorhandlec_eState.Text = c_sUse.RemoteHost + "@" + c_sUse.RemoteHostIP + "来了"m_State = FF_UA_INITc_MunNew.V isible = TrueCase "Gues"If (Not m_State = FF_UA_INIT) Or (b_Server = True) Then _GoTo Errorhandlem_BeSet = Mid(message, 6, 1)MsgBox "猜先", vbOKOnly, App.LegalTrademarksLoad f_Gfstf_Gfst.Show vbModal, mainIf Not m_Set = m_BeSet Thenc_sUse.SendData "Y our"local_side = FF_SIDE2pic_click.Visible = Falsepic_noclick.Visible = Truec_sColor.FillColor = vbBlueTransBoardElsec_sUse.SendData "Mfst"local_side = FF_SIDE1pic_noclick.Visible = Falsepic_click.Visible = Truec_sColor.FillColor = vbRedEnd IfTransState FF_US_USE_CONCase "Y our"If (Not m_State = FF_UA_INIT) Or (b_Server = False) Then _GoTo ErrorhandleTransState FF_US_USE_CONlocal_side = FF_SIDE1pic_noclick.Visible = Falsepic_click.Visible = Truec_sColor.FillColor = vbRedCase "Mfst"If (Not m_State = FF_UA_INIT) Or (b_Server = False) Then _GoTo ErrorhandleTransState FF_US_USE_CONlocal_side = FF_SIDE2pic_click.Visible = Falsepic_noclick.Visible = Truec_sColor.FillColor = vbBlueTransBoardCase "Load"If (Not m_State = FF_UA_INIT) Or (b_Server = True) Then _ GoTo Errorhandlelocal_side = Asc(Mid(message, 6, 1)) - 65TransSide local_sidepos_side = Asc(Mid(message, 7, 1)) - 65If local_side = FF_SIDE1 Thenc_sColor.FillColor = vbRedElsec_sColor.FillColor = vbBlueEnd IfIf pos_side = local_side Thenpic_noclick.Visible = Falsepic_click.Visible = TrueElsepic_click.Visible = Falsepic_noclick.Visible = TrueEnd IfDim j As Integerj = 0For i = 8 To bytesTotal - 5 Step 3temp = Asc(Mid(message, i, 1)) - 65x_off = Asc(Mid(message, i + 1, 1)) - 48y_off = Asc(Mid(message, i + 2, 1)) - 48If x_off < 0 Or x_off > 8 Or y_off < 0 Or y_off > 9 Then Exit Sub c_chess(j).Top = y_off * 600c_chess(j).Left = x_off * 600 + 195If temp = 0 Thenc_chess(j).V isible = FalseElsec_chess(j).V isible = TrueEnd Ifj = j + 1Next iTransBoardm_State = FF_UA_USECase "Post"Dim chess, chess_die, x_begin, y_begin, count As IntegerIf Not m_State = FF_UA_USE Then GoTo ErrorhandleIf pos_side = local_side Then GoTo Errorhandlechess = Asc(Mid(message, 6, 1)) - 65x_off = Asc(Mid(message, 7, 1)) - 48y_off = Asc(Mid(message, 8, 1)) - 48y_off = 9 - y_offx_off = 8 - x_offchess_die = FindChessInPos(x_off, y_off)If GoChess(chess, x_off, y_off) = False ThenIf chess = 9 Or chess = 10 Or chess = 25 Or chess = 25 Or chess = 26 ThenIf chess_die = -1 Then GoTo Errorhandlex_begin = (c_chess(chess).Left - 195) / 600y_begin = (c_chess(chess).Top) / 600count = 0If (Not x_begin = x_off) And (Not y_begin = y_off) Then GoTo ErrorhandleIf x_begin = x_off ThenFor i = y_begin + Sgn(y_off - y_begin) To y_off - Sgn(y_off - y_begin) Step Sgn(y_off - y_begin)If Not FindChessInPos(x_off, i) = -1 Then count = count + 1Next iEnd IfIf y_begin = y_off ThenFor i = x_begin + Sgn(x_off - x_begin) To x_off - Sgn(x_off - x_begin) Step Sgn(x_off - x_begin)If Not FindChessInPos(i, y_off) = -1 Then count = count + 1Next iEnd IfElseGoTo ErrorhandleEnd IfIf count = 1 Thenc_chess(chess).Top = c_chess(chess_die).Topc_chess(chess).Left = c_chess(chess_die).Leftc_chess(chess_die).V isible = FalseIf chess_die = 0 Or chess_die = 16 ThenDie chess_dieExit SubEnd IfTransSide pos_sidepic_click.Visible = Not pic_click.Visiblepic_noclick.Visible = Not pic_noclick.VisibleEnd IfElseIf chess_die = -1 Then Exit Subc_chess(chess_die).V isible = FalseIf chess_die = 0 Or chess_die = 16 ThenDie chess_dieExit SubEnd IfEnd IfCase ElseGoTo ErrorhandleEnd SelectExit SubErrorhandle:If Not message = "Invalid Command" Thenc_sUse.SendData "Invalid Command"Elsec_eState.Text = "错误的命令或操作"End IfEnd SubPrivate Sub c_sUse_Error(ByV al Number As Integer, Description As String, ByV al Scode As Long, ByV al Source As String, ByV al HelpFile As String, ByV al HelpContext As Long, CancelDisplay As Boolean)MsgBox Description, vbOKOnly, App.LegalTrademarksTransState FF_US_INITALLTransState FF_US_INITNETEnd Sub'中国象棋Option ExplicitPrivate Sub Form_Load()opt_Net.V alue = Falseopt_Local.V alue = TrueEnd SubPrivate Sub m_CmdNetOk_Click() main.bIsNet = opt_Net.V alue Unload f_GnetLoad mainmain.ShowEnd Sub'中国象棋-VB开发Option ExplicitPrivate Sub Form_Load()opt_d.V alue = TrueEnd SubPrivate Sub m_cmdGfstOk_Click() If opt_d.V alue = True Then main.m_Set = "D"Elsemain.m_Set = "S"End IfUnload f_GfstEnd Sub。

基于JAVA语言的中国象棋设计与实现设计

基于JAVA语言的中国象棋设计与实现设计

基于JAVA语言的中国象棋设计与实现设计题目:基于JA V A语言的中国象棋设计与实现毕业设计(论文)原创性声明和使用授权说明原创性声明本人郑重承诺:所呈交的毕业设计(论文),是我个人在指导教师的指导下进行的研究工作及取得的成果。

尽我所知,除文中特别加以标注和致谢的地方外,不包含其他人或组织已经发表或公布过的研究成果,也不包含我为获得及其它教育机构的学位或学历而使用过的材料。

对本研究提供过帮助和做出过贡献的个人或集体,均已在文中作了明确的说明并表示了谢意。

作者签名:日期:指导教师签名:日期:使用授权说明本人完全了解大学关于收集、保存、使用毕业设计(论文)的规定,即:按照学校要求提交毕业设计(论文)的印刷本和电子版本;学校有权保存毕业设计(论文)的印刷本和电子版,并提供目录检索与阅览服务;学校可以采用影印、缩印、数字化或其它复制手段保存论文;在不以赢利为目的前提下,学校可以公布论文的部分或全部内容。

作者签名:日期:【摘要】电脑在中国象棋上的运用还刚刚起步,尽管国内涌现出一大批中国象棋的专业网站和专业软件,但是由于缺乏必要的基础工作,电脑技术在中国象棋上的应用优势还无法体现出来,随着人工智能及计算机硬件的发展,计算机象棋程序的水平也不断地得到提高。

本文通过研究中国象棋的国内外研究现状、分析中国象棋的需求和用JA V A 语言设计中国象棋程序的可行性,同时根据国际象棋程序设计的一些成功经验,主要借鉴了位棋盘、Zobrist键值等,针对中国象棋程序设计的一系列问题,总结出一些中国象棋程序的设计方法。

根据该方法设计出了符合中国象棋行棋和吃子规则,能够判断胜负,能够实现悔棋、重新开始等多种功能,而且界面十分美观的中国象棋程序,并给出了JA V A语言的实现方法。

关键词:中国象棋,位棋盘,Zobrist键值,着发生成【Abstract】The implement of playing Chinese Chess on computer has just started. Although large numbers of professional websites and professional chess software arised in domestic, the lack of necessary basic work causes the advantage of computer technology applications in Chinese chess can’t be reflected. With the development of artificial intelligence and computer hardware, the level of computer chess program continues to be improved.This paper studies the research status of Chinese chess, analyzes the demand of Chinese chess, and learns the feasibility of Chinese chess that is designed by Java language. At the same time, the function is designed with the successful experience of chess program, such as the place board, Zobrist keys, etc. Chinese chess program is summarized some ways to design Chinese chess program for solve a range of issues. Follow this ways, it designs all the rules and funtions which adapt to the requirement of Chinese chess, including of movement, judgement, undo, re-start and so on.The application gives the implementation method in JA V A language and beautiful interface.Keywords: Chinese Chess, bit board, zobrist keys目录1绪论 (1)1.1研究背景 (1)1.2研究意义 (1)1.3预期目标 (1)2分析 (3)2.1需求分析 (3)2.2可行性分析 (3)2.3功能分析 (3)2.4硬件环境 (4)2.4.1开发环境 (4)2.4.2运行环境 (4)3界面设计框架 (5)3.1程序的框架 (5)3.2.基本数据结构——位棋盘 (5)3.2.1 什么是位棋盘 (5)3.2.2 位棋盘的作用 (6)3.2.3 位棋盘的基本运算 (6)3.2.4 Java中位棋盘的实现 (6)3.3.基本数据结构——Zobrist键值 (9)3.3.1 比较局面的方法 (9)3.3.2 Zobrist键值的工作原理 (9)3.3.3 Zobrist键值的实现方法 (10)3.3.4 Java中实现Zobrist键值 (10)4系统实现 (12)4.1着法生成 (12)4.1.1伪合法着法的生成 (12)4.1.2 合法着法的生成 (17)4.2算法实现 (20)4.2.1 行棋规则算法实现 (20)4.2.2界面功能算法实现 (23)5结论 (26)参考文献 (27)附录 (28)附录1算法主程序 (28)附录2程序截图 (53)外文文献与翻译 (54)致谢 (63)1绪论1.1研究背景计算机现在已经成为每天工作和生活必不可少的一部分,电子游戏在计算机产业的带动下也逐步深入我们每个人的娱乐活动中,棋牌游戏作为休闲类电子游戏,相对于角色扮演类游戏和即时战略类游戏等其它游戏,具有上手快、游戏时间短的特点,更利于用户进行放松休闲,为人们所喜爱,特别是棋类游戏,方便、快捷、操作简单,在休闲娱乐中占主要位置。

Java语言课程设计中国象棋打谱系统

Java语言课程设计中国象棋打谱系统

目录1.绪论 (2)1.1引言 (2)1.2主要设计内容 (3)2.开发工具简介 (3)2.1 java语言概述 (3)2.2 java语言的特点 (4)2.3 关于ECLIPSE (5)3.程序设计需求分析 (7)3.1任务概述 (7)3.2综合要求 (7)3.3 设计基本要求 (7)4.程序的总体设计 (8)4.1线程的设计 (8)4.2线程的生命周期 (9)5.程序的详细设计 (11)5.1程序流程图 (11)5.2数据字典 (12)5.3运行结果及界面 (16)6.实验总结 (18)参考文献 (18)附录(部分源代码) (19)1.绪论1.1引言象棋水平的发展是需要靠信息技术来推动的,国际象棋有两个很好的范例,一个是象棋棋谱编辑和对弈程序的公共平台——WinBoard平台,另一个是商业的国际象棋数据库和对弈软件——ChessBase,他们为国际象棋爱好者和研究者提供了极大的便利。

国际象棋软件有着成功的商业运作,已发展成一种产业。

然而,电脑在中国象棋上的运用还刚刚起步,尽管国内涌现出一大批中国象棋的专业网站和专业软件,但是由于缺乏必要的基础工作,电脑技术在中国象棋上的应用优势还无法体现出来。

在设计中国象棋软件过程中,国际象棋软件有很多值得借鉴的成功经验和优秀的思想。

例如 B. Moreland,微软(Microsoft)的程序设计师,业余从事国际象棋引擎Ferret的开发,他的一系列关于国际象棋程序设计的文章非常值得其他棋类程序设计人员借鉴。

然而,中国象棋与国际象棋存在着很大的差异,因此国际象棋的某些成熟技术,无法直接应用于中国象棋,需要对其加以改进和创新。

1.2主要设计内容本课题采用Java语言编写这个中国象棋对弈系统程序。

主要工作内容:搜集相关资料,准备参考资料,学习掌握开发方法、开发工具,需求分析,确定游戏程序实施方案,根据要求设计具体的流程图,编写程序,修改、完善程序,系统调试、测试,优化处理。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.io.*;public class Chess{public static void main(String args[]){new ChessMainFrame("中国象棋:观棋不语真君子,棋死无悔大丈夫");}}class ChessMainFrame extends JFrame implements ActionListener,MouseListener,Runnable{//玩家JLabel play[] = new JLabel[32];//棋盘JLabel image;//窗格Container con;//工具栏JToolBar jmain;//重新开始JButton anew;//悔棋JButton repent;//退出JButton exit;//当前信息JLabel text;//保存当前操作Vector Var;//规则类对象(使于调用方法)ChessRule rule;/**** 单击棋子** chessManClick = true 闪烁棋子并给线程响应** chessManClick = false 吃棋子停止闪烁并给线程响应*/boolean chessManClick;/**** 控制玩家走棋** chessPlayClick=1 黑棋走棋** chessPlayClick=2 红棋走棋默认红棋** chessPlayClick=3 双方都不能走棋*/int chessPlayClick=2;//控制棋子闪烁的线程Thread tmain;//把第一次的单击棋子给线程响应static int Man,i;ChessMainFrame(){new ChessMainFrame("中国象棋");}/**** 构造函数** 初始化图形用户界面*/ChessMainFrame(String Title){//获行客格引用con = this.getContentPane();con.setLayout(null);//实例化规则类rule = new ChessRule();Var = new Vector();//创建工具栏jmain = new JToolBar();text = new JLabel("欢迎使用象棋对弈系统");//当鼠标放上显示信息text.setToolTipText("信息提示");anew = new JButton(" 新游戏");anew.setToolTipText("重新开始新的一局");exit = new JButton(" 退出");exit.setToolTipText("退出象棋程序程序");repent = new JButton(" 悔棋");repent.setToolTipText("返回到上次走棋的位置");//把组件添加到工具栏jmain.setLayout(new GridLayout(0,4));jmain.add(anew);jmain.add(repent);jmain.add(exit);jmain.add(text);jmain.setBounds(0,0,558,30);con.add(jmain);//添加棋子标签drawChessMan();//注册按扭监听anew.addActionListener(this);repent.addActionListener(this);exit.addActionListener(this);//注册棋子移动监听for (int i=0;i<32;i++){con.add(play[i]);play[i].addMouseListener(this);}//添加棋盘标签con.add(image = new JLabel(new ImageIcon("image\\Main.GIF"))); image.setBounds(0,30,558,620);image.addMouseListener(this);//注册窗体关闭监听this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent we){System.exit(0);}});//窗体居中Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = this.getSize();if (frameSize.height > screenSize.height){frameSize.height = screenSize.height;}if (frameSize.width > screenSize.width){frameSize.width = screenSize.width;}this.setLocation((screenSize.width - frameSize.width) / 2 - 280 ,(screenSize.height - frameSize.height ) / 2 - 350);//设置this.setIconImage(new ImageIcon("image\\红将.GIF").getImage());this.setResizable(false);this.setTitle(Title);this.setSize(558,670);this.show();}/**** 添加棋子方法*/public void drawChessMan(){//流程控制int i,k;//图标Icon in;//黑色棋子//车in = new ImageIcon("image\\黑车.GIF");for (i=0,k=24;i<2;i++,k+=456){play[i] = new JLabel(in);play[i].setBounds(k,56,55,55);play[i].setName("车1");}//马in = new ImageIcon("image\\黑马.GIF");for (i=4,k=81;i<6;i++,k+=342){play[i] = new JLabel(in);play[i].setBounds(k,56,55,55);play[i].setName("马1");}//相in = new ImageIcon("image\\黑象.GIF");for (i=8,k=138;i<10;i++,k+=228){play[i] = new JLabel(in);play[i].setBounds(k,56,55,55);play[i].setName("象1");}//士in = new ImageIcon("image\\黑士.GIF"); for (i=12,k=195;i<14;i++,k+=114){ play[i] = new JLabel(in);play[i].setBounds(k,56,55,55);play[i].setName("士1");}//卒in = new ImageIcon("image\\黑卒.GIF"); for (i=16,k=24;i<21;i++,k+=114){play[i] = new JLabel(in);play[i].setBounds(k,227,55,55);play[i].setName("卒1" + i);}//炮in = new ImageIcon("image\\黑炮.GIF"); for (i=26,k=81;i<28;i++,k+=342){play[i] = new JLabel(in);play[i].setBounds(k,170,55,55);play[i].setName("炮1" + i);}//将in = new ImageIcon("image\\黑将.GIF"); play[30] = new JLabel(in);play[30].setBounds(252,56,55,55);play[30].setName("将1");//红色棋子//车in = new ImageIcon("image\\红车.GIF"); for (i=2,k=24;i<4;i++,k+=456){play[i] = new JLabel(in);play[i].setBounds(k,569,55,55);play[i].setName("车2");}//马in = new ImageIcon("image\\红马.GIF");for (i=6,k=81;i<8;i++,k+=342){play[i] = new JLabel(in);play[i].setBounds(k,569,55,55);play[i].setName("马2");}//相in = new ImageIcon("image\\红象.GIF");for (i=10,k=138;i<12;i++,k+=228){play[i] = new JLabel(in);play[i].setBounds(k,569,55,55);play[i].setName("象2");}//士in = new ImageIcon("image\\红士.GIF");for (i=14,k=195;i<16;i++,k+=114){play[i] = new JLabel(in);play[i].setBounds(k,569,55,55);play[i].setName("士2");}//兵in = new ImageIcon("image\\红卒.GIF");for (i=21,k=24;i<26;i++,k+=114){play[i] = new JLabel(in);play[i].setBounds(k,398,55,55);play[i].setName("卒2" + i);}//炮in = new ImageIcon("image\\红炮.GIF");for (i=28,k=81;i<30;i++,k+=342){play[i] = new JLabel(in);play[i].setBounds(k,455,55,55);play[i].setName("炮2" + i);}//帅in = new ImageIcon("image\\红将.GIF");play[31] = new JLabel(in);play[31].setBounds(252,569,55,55);play[31].setName("帅2");}/**** 线程方法控制棋子闪烁*/public void run(){while (true){//单击棋子第一下开始闪烁if (chessManClick){play[Man].setVisible(false);//时间控制try{tmain.sleep(200);}catch(Exception e){}play[Man].setVisible(true);}//闪烁当前提示信息以免用户看不见else {text.setVisible(false);//时间控制try{tmain.sleep(250);}catch(Exception e){}text.setVisible(true);}try{tmain.sleep(350);}catch (Exception e){}}}/**** 单击棋子方法public void mouseClicked(MouseEvent me){System.out.println("Mouse");//当前坐标int Ex=0,Ey=0;//启动线程if (tmain == null){tmain = new Thread(this);tmain.start();}//单击棋盘(移动棋子)if (me.getSource().equals(image)){//该红棋走棋的时候if (chessPlayClick == 2 && play[Man].getName().charAt(1) == '2'){ Ex = play[Man].getX();Ey = play[Man].getY();//移动卒、兵if (Man > 15 && Man < 26){rule.armsRule(Man,play[Man],me);}//移动炮else if (Man > 25 && Man < 30){rule.cannonRule(play[Man],play,me);}//移动车else if (Man >=0 && Man < 4){rule.cannonRule(play[Man],play,me);}//移动马else if (Man > 3 && Man < 8){rule.horseRule(play[Man],play,me);}//移动相、象else if (Man > 7 && Man < 12){rule.elephantRule(Man,play[Man],play,me);}//移动仕、士else if (Man > 11 && Man < 16){rule.chapRule(Man,play[Man],play,me);}//移动将、帅else if (Man == 30 || Man == 31){rule.willRule(Man,play[Man],play,me);}//是否走棋错误(是否在原地没有动)if (Ex == play[Man].getX() && Ey == play[Man].getY()){text.setText(" 红棋走棋");chessPlayClick=2;}else {text.setText(" 黑棋走棋");chessPlayClick=1;}}//if//该黑棋走棋的时候else if (chessPlayClick == 1 && play[Man].getName().charAt(1) == '1'){Ex = play[Man].getX();Ey = play[Man].getY();//移动卒、兵if (Man > 15 && Man < 26){rule.armsRule(Man,play[Man],me);}//移动炮else if (Man > 25 && Man < 30){rule.cannonRule(play[Man],play,me);}//移动车else if (Man >=0 && Man < 4){rule.cannonRule(play[Man],play,me);}//移动马else if (Man > 3 && Man < 8){rule.horseRule(play[Man],play,me);}//移动相、象else if (Man > 7 && Man < 12){rule.elephantRule(Man,play[Man],play,me);}//移动仕、士else if (Man > 11 && Man < 16){rule.chapRule(Man,play[Man],play,me);}//移动将、帅else if (Man == 30 || Man == 31){rule.willRule(Man,play[Man],play,me);}//是否走棋错误(是否在原地没有动)if (Ex == play[Man].getX() && Ey == play[Man].getY()){ text.setText(" 黑棋走棋");chessPlayClick=1;}else {text.setText(" 红棋走棋");chessPlayClick=2;}}//else if//当前没有操作(停止闪烁)chessManClick=false;}//if//单击棋子else{//第一次单击棋子(闪烁棋子)if (!chessManClick){for (int i=0;i<32;i++){//被单击的棋子if (me.getSource().equals(play[i])){//告诉线程让该棋子闪烁Man=i;//开始闪烁chessManClick=true;break;}}//for}//if//第二次单击棋子(吃棋子)else if (chessManClick){//当前没有操作(停止闪烁)chessManClick=false;for (i=0;i<32;i++){//找到被吃的棋子if (me.getSource().equals(play[i])){//该红棋吃棋的时候if (chessPlayClick == 2 && play[Man].getName().charAt(1) == '2'){Ex = play[Man].getX();Ey = play[Man].getY();//卒、兵吃规则if (Man > 15 && Man < 26){rule.armsRule(play[Man],play[i]);}//炮吃规则else if (Man > 25 && Man < 30){rule.cannonRule(0,play[Man],play[i],play,me);}//车吃规则else if (Man >=0 && Man < 4){rule.cannonRule(1,play[Man],play[i],play,me);}//马吃规则else if (Man > 3 && Man < 8){rule.horseRule(play[Man],play[i],play,me);}//相、象吃规则else if (Man > 7 && Man < 12){rule.elephantRule(play[Man],play[i],play);}//士、仕吃棋规则else if (Man > 11 && Man < 16){rule.chapRule(Man,play[Man],play[i],play);}//将、帅吃棋规则else if (Man == 30 || Man == 31){rule.willRule(Man,play[Man],play[i],play);play[Man].setVisible(true);}//是否走棋错误(是否在原地没有动)if (Ex == play[Man].getX() && Ey == play[Man].getY()){text.setText(" 红棋走棋");chessPlayClick=2;break;}else{text.setText(" 黑棋走棋");chessPlayClick=1;break;}}//if//该黑棋吃棋的时候else if (chessPlayClick == 1 && play[Man].getName().charAt(1) == '1'){Ex = play[Man].getX();Ey = play[Man].getY();//卒吃规则if (Man > 15 && Man < 26){rule.armsRule(play[Man],play[i]);}//炮吃规则else if (Man > 25 && Man < 30){rule.cannonRule(0,play[Man],play[i],play,me);}//车吃规则else if (Man >=0 && Man < 4){rule.cannonRule(1,play[Man],play[i],play,me);}//马吃规则else if (Man > 3 && Man < 8){rule.horseRule(play[Man],play[i],play,me);}//相、象吃规则else if (Man > 7 && Man < 12){rule.elephantRule(play[Man],play[i],play);}//士、仕吃棋规则else if (Man > 11 && Man < 16){rule.chapRule(Man,play[Man],play[i],play);}//将、帅吃棋规则else if (Man == 30 || Man == 31){rule.willRule(Man,play[Man],play[i],play);play[Man].setVisible(true);}//是否走棋错误(是否在原地没有动)if (Ex == play[Man].getX() && Ey == play[Man].getY()){text.setText(" 黑棋走棋");chessPlayClick=1;break;}else {text.setText(" 红棋走棋");chessPlayClick=2;break;}}//else if}//if}//for//是否胜利if (!play[31].isVisible()){JOptionPane.showConfirmDialog(this,"黑棋胜利","玩家一胜利",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE);//双方都不可以在走棋了chessPlayClick=3;text.setText(" 黑棋胜利");}//ifelse if (!play[30].isVisible()){JOptionPane.showConfirmDialog(this,"红棋胜利","玩家二胜利",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE);chessPlayClick=3;text.setText(" 红棋胜利");}//else if}//else}//else}public void mousePressed(MouseEvent me){}public void mouseReleased(MouseEvent me){}public void mouseEntered(MouseEvent me){}public void mouseExited(MouseEvent me){}/**** 定义按钮的事件响应*/public void actionPerformed(ActionEvent ae) { //重新开始按钮if (ae.getSource().equals(anew)){int i,k;//重新排列每个棋子的位置//黑色棋子//车for (i=0,k=24;i<2;i++,k+=456){play[i].setBounds(k,56,55,55);}//马for (i=4,k=81;i<6;i++,k+=342){play[i].setBounds(k,56,55,55);}//相for (i=8,k=138;i<10;i++,k+=228){play[i].setBounds(k,56,55,55);}//士for (i=12,k=195;i<14;i++,k+=114){play[i].setBounds(k,56,55,55);}//卒for (i=16,k=24;i<21;i++,k+=114){play[i].setBounds(k,227,55,55);}//炮for (i=26,k=81;i<28;i++,k+=342){play[i].setBounds(k,170,55,55);}//将play[30].setBounds(252,56,55,55);//红色棋子//车for (i=2,k=24;i<4;i++,k+=456){play[i].setBounds(k,569,55,55);}//马for (i=6,k=81;i<8;i++,k+=342){play[i].setBounds(k,569,55,55);}//相for (i=10,k=138;i<12;i++,k+=228){play[i].setBounds(k,569,55,55);}//士for (i=14,k=195;i<16;i++,k+=114){play[i].setBounds(k,569,55,55);}//兵for (i=21,k=24;i<26;i++,k+=114){play[i].setBounds(k,398,55,55);}//炮for (i=28,k=81;i<30;i++,k+=342){play[i].setBounds(k,455,55,55);}//帅play[31].setBounds(252,569,55,55);chessPlayClick = 2;text.setText(" 红棋走棋");for (i=0;i<32;i++){play[i].setVisible(true);}//清除Vector中的内容Var.clear();}//悔棋按钮else if (ae.getSource().equals(repent)){try{//获得setVisible属性值String S = (String)Var.get(Var.size()-4);//获得X坐标int x = Integer.parseInt((String)Var.get(Var.size()-3));//获得Y坐标int y = Integer.parseInt((String)Var.get(Var.size()-2));//获得索引int M = Integer.parseInt((String)Var.get(Var.size()-1));//赋给棋子play[M].setVisible(true);play[M].setBounds(x,y,55,55);if (play[M].getName().charAt(1) == '1'){text.setText(" 黑棋走棋");chessPlayClick = 1;}else{text.setText(" 红棋走棋");chessPlayClick = 2;}//删除用过的坐标Var.remove(Var.size()-4);Var.remove(Var.size()-3);Var.remove(Var.size()-2);Var.remove(Var.size()-1);//停止旗子闪烁chessManClick=false;}catch(Exception e){}}//退出else if (ae.getSource().equals(exit)){int j=JOptionPane.showConfirmDialog(this,"真的要退出吗?","退出",JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE);if (j == JOptionPane.YES_OPTION){System.exit(0);}}}/*定义中国象棋规则的类*/class ChessRule {/**卒子的移动规则*/public void armsRule(int Man,JLabel play,MouseEvent me){//黑卒向下if (Man < 21){//向下移动、得到终点的坐标模糊成合法的坐标if ((me.getY()-play.getY()) > 27 && (me.getY()-play.getY()) < 86 && (me.getX()-play.getX()) < 55 && (me.getX()-play.getX()) > 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(play.getX(),play.getY()+57,55,55);}//向右移动、得到终点的坐标模糊成合法的坐标、必须过河else if (play.getY() > 284 && (me.getX() - play.getX()) >= 57 && (me.getX() - play.getX()) <= 112){play.setBounds(play.getX()+57,play.getY(),55,55);}//向左移动、得到终点的坐标模糊成合法的坐标、必须过河else if (play.getY() > 284 && (play.getX() - me.getX()) >= 2 && (play.getX() - me.getX()) <=58){//模糊坐标play.setBounds(play.getX()-57,play.getY(),55,55);}}//红卒向上else{//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));//向上移动、得到终点的坐标模糊成合法的坐标if ((me.getX()-play.getX()) >= 0 && (me.getX()-play.getX()) <= 55 && (play.getY()-me.getY()) >27 && play.getY()-me.getY() < 86){play.setBounds(play.getX(),play.getY()-57,55,55);}//向右移动、得到终点的坐标模糊成合法的坐标、必须过河else if (play.getY() <= 341 && (me.getX() - play.getX()) >= 57 && (me.getX() - play.getX()) <= 112){play.setBounds(play.getX()+57,play.getY(),55,55);}//向左移动、得到终点的坐标模糊成合法的坐标、必须过河else if (play.getY() <= 341 && (play.getX() - me.getX()) >= 3 && (play.getX() - me.getX()) <=58){play.setBounds(play.getX()-57,play.getY(),55,55);}}}//卒移动结束/**卒吃棋规则*/public void armsRule(JLabel play1,JLabel play2){//向右走if ((play2.getX() - play1.getX()) <= 112 && (play2.getX() - play1.getX()) >= 57 && (play1.getY() - play2.getY()) < 22 && (play1.getY() - play2.getY()) > -22 && play2.isVisible() && play1.getName().charAt(1)!=play2.getName().charAt(1)){//黑棋要过河才能右吃棋if (play1.getName().charAt(1) == '1' && play1.getY() > 284 && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}//红棋要过河才左能吃棋else if (play1.getName().charAt(1) == '2' && play1.getY() < 341&& play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}}//向左走else if ((play1.getX() - play2.getX()) <= 112 && (play1.getX() - play2.getX()) >= 57 && (play1.getY() - play2.getY()) < 22 && (play1.getY() - play2.getY()) > -22 && play2.isVisible() && play1.getName().charAt(1)!=play2.getName().charAt(1)){//黑棋要过河才能左吃棋if (play1.getName().charAt(1) == '1' && play1.getY() > 284 && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}//红棋要过河才能右吃棋else if (play1.getName().charAt(1) == '2' && play1.getY() < 341 && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}}//向上走else if (play1.getX() - play2.getX() >= -22 && play1.getX() - play2.getX() <= 22 && play1.getY() - play2.getY() >= -112 && play1.getY() - play2.getY() <= 112){//黑棋不能向上吃棋if (play1.getName().charAt(1) == '1' && play1.getY() < play2.getY() && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}//红棋不能向下吃棋else if (play1.getName().charAt(1) == '2' && play1.getY() > play2.getY() && play1.getName().charAt(1) != play2.getName().charAt(1)){play2.setVisible(false);//把对方的位置给自己play1.setBounds(play2.getX(),play2.getY(),55,55);}}//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play1.isVisible()));Var.add(String.valueOf(play1.getX()));Var.add(String.valueOf(play1.getY()));Var.add(String.valueOf(Man));//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play2.isVisible()));Var.add(String.valueOf(play2.getX()));Var.add(String.valueOf(play2.getY()));Var.add(String.valueOf(i));}//卒吃结束/**炮、车移动规则*/public void cannonRule(JLabel play,JLabel playQ[],MouseEvent me){ //起点和终点之间是否有棋子int Count = 0;//上、下移动if (play.getX() - me.getX() <= 0 && play.getX() - me.getX() >= -55){ //指定所有模糊Y坐标for (int i=56;i<=571;i+=57){//移动的Y坐标是否有指定坐标相近的if (i - me.getY() >= -27 && i - me.getY() <= 27){//所有的棋子for (int j=0;j<32;j++){//找出在同一条竖线的所有棋子、并不包括自己if (playQ[j].getX() - play.getX() >= -27 && playQ[j].getX() - play.getX() <= 27 && playQ[j].getName()!=play.getName() && playQ[j].isVisible()){//从起点到终点(从左到右)for (int k=play.getY()+57;k<i;k+=57){//大于起点、小于终点的坐标就可以知道中间是否有棋子if (playQ[j].getY() < i && playQ[j].getY() >play.getY()){//中间有一个棋子就不可以从这条竖线过去Count++;break;}}//for//从起点到终点(从右到左)for (int k=i+57;k<play.getY();k+=57){//找起点和终点的棋子if (playQ[j].getY() < play.getY() && playQ[j].getY() > i){Count++;break;}}//for}//if}//for//起点和终点没有棋子就可以移动了if (Count == 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(play.getX(),i,55,55);break;}}//if}//for}//if//左、右移动else if (play.getY() - me.getY() >=-27 && play.getY() - me.getY() <= 27){//指定所有模糊X坐标for (int i=24;i<=480;i+=57){//移动的X坐标是否有指定坐标相近的if (i - me.getX() >= -55 && i-me.getX() <= 0){//所有的棋子for (int j=0;j<32;j++){//找出在同一条横线的所有棋子、并不包括自己if (playQ[j].getY() - play.getY() >= -27 && playQ[j].getY() - play.getY() <= 27 && playQ[j].getName()!=play.getName() && playQ[j].isVisible()){//从起点到终点(从上到下)for (int k=play.getX()+57;k<i;k+=57){//大于起点、小于终点的坐标就可以知道中间是否有棋子if (playQ[j].getX() < i && playQ[j].getX() > play.getX()){//中间有一个棋子就不可以从这条横线过去Count++;break;}}//for//从起点到终点(从下到上)for (int k=i+57;k<play.getX();k+=57){//找起点和终点的棋子if (playQ[j].getX() < play.getX() && playQ[j].getX() > i){Count++;break;}}//for}//if}//for//起点和终点没有棋子if (Count == 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(i,play.getY(),55,55);break;}}//if}//for}//else}//炮、车移动方法结束/**炮、车吃棋规则*/public void cannonRule(int Chess,JLabel play,JLabel playTake,JLabel playQ[],MouseEvent me){//起点和终点之间是否有棋子int Count = 0;//所有的棋子for (int j=0;j<32;j++){//找出在同一条竖线的所有棋子、并不包括自己if (playQ[j].getX() - play.getX() >= -27 && playQ[j].getX() - play.getX() <= 27 && playQ[j].getName()!=play.getName() && playQ[j].isVisible()){//自己是起点被吃的是终点(从上到下)for (int k=play.getY()+57;k<playTake.getY();k+=57){//大于起点、小于终点的坐标就可以知道中间是否有棋子if (playQ[j].getY() < playTake.getY() && playQ[j].getY() > play.getY()){//计算起点和终点的棋子个数Count++;break;}}//for//自己是起点被吃的是终点(从下到上)for (int k=playTake.getY();k<play.getY();k+=57){//找起点和终点的棋子if (playQ[j].getY() < play.getY() && playQ[j].getY() > playTake.getY()){Count++;break;}}//for}//if//找出在同一条竖线的所有棋子、并不包括自己else if (playQ[j].getY() - play.getY() >= -10 && playQ[j].getY() - play.getY() <= 10 && playQ[j].getName()!=play.getName() && playQ[j].isVisible()){//自己是起点被吃的是终点(从左到右)for (int k=play.getX()+50;k<playTake.getX();k+=57){//大于起点、小于终点的坐标就可以知道中间是否有棋子if (playQ[j].getX() < playTake.getX() && playQ[j].getX() > play.getX()){Count++;break;}}//for//自己是起点被吃的是终点(从右到左)for (int k=playTake.getX();k<play.getX();k+=57){//找起点和终点的棋子if (playQ[j].getX() < play.getX() && playQ[j].getX() > playTake.getX()){Count++;break;}}//for}//if}//for//起点和终点之间要一个棋子是炮的规则、并不能吃自己的棋子if (Count == 1 && Chess == 0 && playTake.getName().charAt(1) != play.getName().charAt(1)){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(playTake.isVisible()));Var.add(String.valueOf(playTake.getX()));Var.add(String.valueOf(playTake.getY()));Var.add(String.valueOf(i));playTake.setVisible(false);play.setBounds(playTake.getX(),playTake.getY(),55,55);}//起点和终点之间没有棋子是车的规则、并不能吃自己的棋子else if (Count ==0 && Chess == 1 &&playTake.getName().charAt(1) != play.getName().charAt(1)){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(playTake.isVisible()));Var.add(String.valueOf(playTake.getX()));Var.add(String.valueOf(playTake.getY()));Var.add(String.valueOf(i));playTake.setVisible(false);play.setBounds(playTake.getX(),playTake.getY(),55,55);}}//炮、车吃棋方法结束/**马移动规则*/public void horseRule(JLabel play,JLabel playQ[],MouseEvent me){ //保存坐标和障碍int Ex=0,Ey=0,Move=0;//上移、左边if (play.getX() - me.getX() >= 2 && play.getX() - me.getX() <= 57 && play.getY() - me.getY() >= 87 && play.getY() - me.getY() <= 141){//合法的Y坐标for (int i=56;i<=571;i+=57){//移动的Y坐标是否有指定坐标相近的if (i - me.getY() >= -27 && i - me.getY() <= 27){Ey = i;break;}}//合法的X坐标for (int i=24;i<=480;i+=57){//移动的X坐标是否有指定坐标相近的if (i - me.getX() >= -55 && i-me.getX() <= 0){Ex = i;break;}}//正前方是否有别的棋子for (int i=0;i<32;i++){if (playQ[i].isVisible() && play.getX() - playQ[i].getX() == 0 && play.getY() - playQ[i].getY() == 57 ){Move = 1;break;}}//可以移动该棋子if (Move == 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(Ex,Ey,55,55);}}//if//左移、上边else if (play.getY() - me.getY() >= 27 && play.getY() - me.getY() <= 86 && play.getX() - me.getX() >= 70 && play.getX() - me.getX() <= 130){//Yfor (int i=56;i<=571;i+=57){if (i - me.getY() >= -27 && i - me.getY() <= 27){Ey = i;}}//Xfor (int i=24;i<=480;i+=57){if (i - me.getX() >= -55 && i-me.getX() <= 0){Ex = i;}}//正左方是否有别的棋子for (int i=0;i<32;i++){if (playQ[i].isVisible() && play.getY() - playQ[i].getY() == 0 && play.getX() - playQ[i].getX() == 57 ){Move = 1;break;}}if (Move == 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(Ex,Ey,55,55);}}//else//下移、右边else if (me.getY() - play.getY() >= 87 && me.getY() - play.getY() <= 141 && me.getX() - play.getX() <= 87 && me.getX() - play.getX() >= 2 ){//Yfor (int i=56;i<=571;i+=57){if (i - me.getY() >= -27 && i - me.getY() <= 27){Ey = i;}}//Xfor (int i=24;i<=480;i+=57){if (i - me.getX() >= -55 && i-me.getX() <= 0){Ex = i;}}//正下方是否有别的棋子for (int i=0;i<32;i++){if (playQ[i].isVisible() && play.getX() - playQ[i].getX() == 0 && playQ[i].getY() - play.getY() == 57 ){Move = 1;break;}}if (Move == 0){//当前记录添加到集合(用于悔棋)Var.add(String.valueOf(play.isVisible()));Var.add(String.valueOf(play.getX()));Var.add(String.valueOf(play.getY()));Var.add(String.valueOf(Man));play.setBounds(Ex,Ey,55,55);}}//else//上移、右边else if (play.getY() - me.getY() >= 87 && play.getY() - me.getY() <= 141 && me.getX() - play.getX() <= 87 && me.getX() - play.getX() >= 30 ){//合法的Y坐标for (int i=56;i<=571;i+=57){if (i - me.getY() >= -27 && i - me.getY() <= 27){Ey = i;break;}}//合法的X坐标for (int i=24;i<=480;i+=57){if (i - me.getX() >= -55 && i-me.getX() <= 0){Ex = i;break;}}//正前方是否有别的棋子for (int i=0;i<32;i++){System.out.println(i+"playQ[i].getX()="+playQ[i].getX());//System.out.println("play.getX()="+play.getX());if (playQ[i].isVisible() && play.getX() - playQ[i].getX() == 0 && play.getY() - playQ[i].getY() == 57 ){Move = 1;//System.out.println("play.getY()="+play.getY());//System.out.println("playQ[i].getY()="+playQ[i].getY());break;}}。

相关文档
最新文档