中国象棋源代码及文档
中国象棋python代码
中国象棋python代码下面是一个简单的中国象棋的Python 代码示例:# 定义棋盘# 绘制棋盘def draw_board():for row in chessboard:for piece in row:print(piece, end=' ')print()# 判断是否在棋盘内def is_valid_move(x, y):return 0 <= x < 9 and 0 <= y < 10# 判断移动是否合法def is_valid_move(x1, y1, x2, y2):piece = chessboard[y1][x1]target = chessboard[y2][x2]if piece == ' ':return Falseif piece == '車' or piece == '車':if x1 != x2 and y1 != y2:return Falseif x1 == x2:min_y, max_y = (y1, y2) if y1 < y2 else (y2, y1)for y in range(min_y + 1, max_y):if chessboard[y][x1] != ' ':return Falseif y1 == y2:min_x, max_x = (x1, x2) if x1 < x2 else (x2, x1)for x in range(min_x + 1, max_x):if chessboard[y1][x] != ' ':return Falseif piece == '馬' or piece == '馬':dx = abs(x2 - x1)dy = abs(y2 - y1)if (dx == 1 and dy == 2) or (dx == 2 and dy == 1): return Truereturn Falseif piece == '象' or piece == '相':if y2 > 4 and (y2 - y1) % 2 != 0:return Falseif abs(x2 - x1) != 2 or abs(y2 - y1) != 2:return Falseif chessboard[(y1 + y2) // 2][(x1 + x2) // 2] != ' ': return Falseif piece == '士' or piece == '士':if x2 < 3 or x2 > 5:return Falseif y2 < 7 or y2 > 9:return Falseif abs(x2 - x1) != 1 or abs(y2 - y1) != 1: return Falseif piece == '帥' or piece == '将':if x2 < 3 or x2 > 5:return Falseif y2 < 0 or y2 > 2:return Falseif abs(x2 - x1) + abs(y2 - y1) != 1:return Falseif piece == '兵':if y1 < 5 and y2 != y1 - 1:return Falseif y1 >= 5 and (x1 != x2 or y2 != y1 - 1):return Falseif piece == '卒':if y1 > 4 and y2 != y1 + 1:return Falseif y1 <= 4 and (x1 != x2 or y2 != y1 + 1):return Falseif target == '帥' or target == '将':if piece == '卒' or piece == '兵':if y2 > 2:return Falseif piece == '兵' or piece == '卒':if y2 < 7:return Falsereturn True# 移动棋子def move_piece(x1, y1, x2, y2):if is_valid_move(x1, y1, x2, y2):piece = chessboard[y1][x1]chessboard[y2][x2] = piecechessboard[y1][x1] = ' 'else:print("Invalid move!")# 游戏循环def game_loop():while True:draw_board()player_input = input("请输入移动的起始位置和目标位置,以逗号分隔(例如:2,1,2,3):")positions = player_input.split(',')if len(positions) != 4:print("请输入正确的起始位置和目标位置!")continuex1, y1, x2, y2 = map(int, positions)if not is_valid_move(x1, y1) or not is_valid_move(x2, y2):print("请输入正确的起始位置和目标位置!")continuemove_piece(x1, y1, x2, y2)# 启动游戏game_loop()这是一个简单的中国象棋游戏代码示例,包括棋盘的绘制、棋子移动的判断和执行等功能。
中国象棋源代码C#
//拾起的棋子行号 private int _pickRow = -1; //拾起的棋子列号 private int _pickCol = -1; //鼠标移动时所在点的坐标 private Point _mouseMovePoint = new Point(0, 0); //棋盘背景位图对象 Bitmap _bmpBg = new Bitmap("棋盘桌面.jpg"); //棋子位图对象(甲乙双方共有14种棋子) Bitmap[] _bmpPiece = new Bitmap[14]; //头像位图对象 Bitmap _bmpHeadJia = new Bitmap("甲方头像.bmp"); Bitmap _bmpHeadYi = new Bitmap("乙方头像.bmp"); //当前走棋方 private string _whoPlay = "无"; //当前.exe文件所在路径 string _exePath; //当前保存或打开的文件名 private string _fileName = ""; //=============================================================== //类成员方法:绘制棋盘 public void DrawChessBoard(Graphics g) { //绘制棋盘背景 // Bitmap bmpBg = new Bitmap("棋盘桌面.jpg"); g.DrawImage(_bmpBg, new Point(0, 0)); //创建粗画笔和细画笔 Pen thinPen = new Pen(Color.Black, 2); Pen thickPen = new Pen(Color.Black, 6); //绘制外围的方框 g.DrawRectangle(thickPen, new Rectangle(_leftTop.X - 10, _leftTop.Y - 10, _columnWidth * 8 + 20, _rowHeight * 9 + 20)); //绘制10条横线 for (int row = 1; row <= 10; row++) { g.DrawLine(thinPen, new Point(_leftTop.X, _leftTop.Y + _rowHeight * (row - 1)), new Point(_leftTop.X + 8 * _columnWidth, _leftTop.Y + _rowHeight * (row - 1))); } //绘制9列 for (int col = 1; col <= 9; col++) {
C语言编写中国象棋
//// main.c// 象棋// 車马相仕帅仕相马車// 十十十十十十十十十// 十炮十十十十十炮十// 兵十兵十兵十兵十兵// 十十十十十十十十十// --楚河-汉界--// 十十十十十十十十十// 卒十卒十卒十卒十卒// 十炮十十十十十炮十// 十十十十十十十十十// 車马象士将士象马車// Created by tarena121 on 15/8/12.// Copyright (c) 2015年Tarena. All rights reserved.//#include <stdio.h>#include <stdbool.h>#include <math.h>#include <stdlib.h>#define R(piece) "\033[31m"#piece"\033[0m"//红色棋子#define B(piece) "\033[30m"#piece"\033[0m"//黑色棋子#define CROSS "\033[33m十\033[0m"//定义外部变量,棋盘坐标char* array[11][9];int xi,yi;//要移动的棋子int xj,yj;//移动的目标位置bool isStandard = 1;//是否符合规则,初始值1,符合bool gameOverSign = 1;//游戏是否结束,0结束bool restart = 0;//生成棋盘void chessboardBuilding();//打印棋盘void printChessboard();//判断是红棋还是黑棋,红旗返回1,黑棋返回-1,否则返回0 int redOrBlack(int x,int y);//红棋移动void redMove();//黑棋移动void blackMove();//每种棋子的规则void rulesOfAllKindsOfChessPieces();//判断游戏结束void isGameOver();//**************************主函数******************************int main(){//生成棋盘chessboardBuilding();//打印棋盘printChessboard();//开始下棋int turn = -1;while (gameOverSign) {isStandard = 1;turn *= (-1);//双方交替下棋switch (turn) {case1:redMove();turn = (restart) ? (turn*-1) : turn;break;case -1:blackMove();turn = (restart) ? (turn*-1) : turn;break;}isGameOver();}printf("游戏结束!\n");}//主函数结束//*************************自定义函数*****************************//生成棋盘void chessboardBuilding(){for (int i = 0; i < 11; i ++) {for (int j = 0; j < 9 ; j ++) {array[i][j] = CROSS;}printf("\n");}array[5][0] = array[5][1] = array[5][4] = array[5][7] = array[5][8] = "-";array[5][2] = B(楚);array[5][3] = B(河);array[5][5] = B(汉);array[5][6] = B(界);//布置红棋array[0][0] = array[0][8] = R(車);array[0][1] = array[0][7] = R(马);array[0][2] = array[0][6] = R(相);array[0][3] = array[0][5] = R(仕);array[0][4] = R(帅);array[2][1] = array[2][7] = R(炮);array[3][0] = array[3][2] = array[3][4] = array[3][6] = array[3][8] = R(兵);//布置黑棋array[10][0] = array[10][8] = B(車);array[10][1] = array[10][7] = B(马);array[10][2] = array[10][6] = B(相);array[10][3] = array[10][5] = B(仕);array[10][4] = B(将);array[8][1] = array[8][7] = B(炮);array[7][0] = array[7][2] = array[7][4] = array[7][6] = array[7][8] = B(卒);}//打印棋盘void printChessboard(){//显示printf(" \033[43;30m中国象棋欢迎您\033[0m\n\n");for (int i = 0; i < 11; i ++) {for (int j = 0; j < 9; j ++) {printf("%s",array[i][j]);}printf("\n");}}//判断是红棋还是黑棋,红旗返回1,黑棋返回-1,否则返回0int redOrBlack(int x,int y){if (array[x][y] == R(車) || array[x][y] == R(马) || array[x][y] == R(相) || array[x][y] == R(仕) || array[x][y] == R(帅) || array[x][y] == R(炮) || array[x][y] == R(兵)){return1;}else if (array[x][y] == B(車) || array[x][y] == B(马) || array[x][y] == B(象) || array[x][y] == B(仕) || array[x][y] == B(将) || array[x][y] == B(炮) || array[x][y] == B(卒)){return -1;}elsereturn0;}//红棋移动void redMove(){if (restart) {printf("违反游戏规则,请重新输入\n");restart = 0;}printf("[红棋]请输入你要移动的棋子:\n");scanf("%d %d",&xi,&yi);printf("[红棋]请输入你要放置的位置:\n");scanf("%d %d",&xj,&yj);rulesOfAllKindsOfChessPieces();printChessboard();}//黑棋移动void blackMove(){if (restart) {printf("违反游戏规则,请重新输入\n");restart = 0;}printf("[黑棋]请输入你要移动的棋子:\n");scanf("%d %d",&xi,&yi);printf("[黑棋]请输入你要放置的位置:\n");scanf("%d %d",&xj,&yj);rulesOfAllKindsOfChessPieces();printChessboard();}//判断游戏结束void isGameOver(){bool sign_r = 0;bool sign_b = 0;for (int i = 0; i < 11; i ++) {for (int j = 0; j < 9; j ++) {if (array[i][j] == R(帅)) {sign_r = 1;}else if (array[i][j] == B(将)){sign_b = 1;}}}if ((sign_r == 0)||(sign_b == 0)) {gameOverSign = 0;}}//每种棋子的规则void rulesOfAllKindsOfChessPieces(){//R(車)----------------------------------------if (array[xi][yi] == R(車)){if (yi == yj)//列坐标不变,同列移动{for (int i = xi+1; i < xj; i ++){if (i == 5)continue;//如果行等于5,跳过if (array[i][yi] != CROSS)isStandard = 0;//如果初始位置和目标位置之间有棋子,则不符合规则}for (int i = xi-1; i > xj; i --){if (i == 5)continue;//如果行等于5,跳过if (array[xi][yi] != CROSS)isStandard = 0;}}else if (xi == xj)//行坐标不变,同行移动{for (int i = yi+1; i < yj; i ++)if (array[xi][i] != CROSS)isStandard = 0;for (int i = yi-1; i > yj; i --)if (array[xi][i] != CROSS)isStandard = 0;}if ((xi == xj || yi == yj)&& isStandard && (redOrBlack(xj, yj) != 1))//如果棋子直行、没有犯规且落点不是红棋,可以移动{array[xi][yi] = CROSS;array[xj][yj] = R(車);}else{restart = 1;}}//B(車)----------------------------------------else if (array[xi][yi] == B(車)){if (yi == yj)//列坐标不变,同列移动{for (int i = xi+1; i < xj; i ++){if (i == 5)continue;//如果行等于5,跳过if (array[i][yi] != CROSS)isStandard = 0;//如果初始位置和目标位置之间有棋子,则不符合规则}for (int i = xi-1; i > xj; i --){if (i == 5)continue;//如果行等于5,跳过if (array[i][yi] != CROSS)isStandard = 0;}}else if (xi == xj)//行坐标不变,同行移动{for (int i = yi+1; i < yj; i ++)if (array[xi][i] != CROSS)isStandard = 0;for (int i = yi-1; i > yj; i --)if (array[xi][i] != CROSS)isStandard = 0;}if ((xi == xj || yi == yj)&& isStandard && redOrBlack(xj, yj) != -1)//如果棋子直行、没有犯规且落点不是红棋,可以移动{array[xi][yi] = CROSS;array[xj][yj] = B(車);}else{restart = 1;}}//R(马)----------------------------------------else if (array[xi][yi] == R(马)){if ((redOrBlack(xj, yj) != 1) && ((xj == xi-2 && yj == yi-1 &&redOrBlack(xi-1, yi) == 0) || (xj == xi-2 && yj == yi+1 &&redOrBlack(xi-1, yi) == 0) || (xj == xi-1 && yj == yi-2 &&redOrBlack(xi, yi-1) == 0) || (xj == xi-1 && yj == yi+2 &&redOrBlack(xi, yi+1) == 0) || (xj == xi+1 && yj == yi-2 &&redOrBlack(xi, yi-1) == 0) || (xj == xi+1 && yj == yi+2 &&redOrBlack(xi, yi+1) == 0) || (xj == xi+2 && yj == yi-1 &&redOrBlack(xi+1, yi) == 0) || (xj == xi+2 && yj == yi+1 &&redOrBlack(xi+1, yi) == 0))){array[xi][yi] = CROSS;array[xj][yj] = R(马);}else{restart = 1;}}//B(马)----------------------------------------else if (array[xi][yi] == B(马)){if ((redOrBlack(xj, yj) != -1) && ((xj == xi-2 && yj == yi-1 &&redOrBlack(xi-1, yi) == 0) || (xj == xi-2 && yj == yi+1 &&redOrBlack(xi-1, yi) == 0) || (xj == xi-1 && yj == yi-2 &&redOrBlack(xi, yi-1) == 0) || (xj == xi-1 && yj == yi+2 &&redOrBlack(xi, yi+1) == 0) || (xj == xi+1 && yj == yi-2 &&redOrBlack(xi, yi-1) == 0) || (xj == xi+1 && yj == yi+2 &&redOrBlack(xi, yi+1) == 0) || (xj == xi+2 && yj == yi-1 &&redOrBlack(xi+1, yi) == 0) || (xj == xi+2 && yj == yi+1 &&redOrBlack(xi+1, yi) == 0))){array[xi][yi] = CROSS;array[xj][yj] = B(马);}else{restart = 1;}}//R(炮)----------------------------------------else if (array[xi][yi] == R(炮)){int count = 0;//起始位置间棋子的个数if (yi == yj)//列坐标不变,同列移动{for (int i = xi+1; i < xj; i ++){if (i == 5)continue;//如果行等于5,跳过if (redOrBlack(i, yi) != 0)count++;}for (int i = xi-1; i > xj; i --){if (i == 5)continue;//如果行等于5,跳过if (redOrBlack(i, yi) != 0)count++;}}else if (xi == xj)//行坐标不变,同行移动{for (int i = yi+1; i < yj; i ++)if (redOrBlack(xi, i) != 0)count++;for (int i = yi-1; i > yj; i --)if (redOrBlack(xi, i) != 0)count++;}if ((xi == xj || yi == yj)&& (count <= 1) && redOrBlack(xj, yj) != 1)//如果棋子直行、没有犯规且落点不是红棋,可以移动{array[xi][yi] = CROSS;array[xj][yj] = R(炮);else{restart = 1;}}//B(炮)----------------------------------------else if (array[xi][yi] == B(炮)){int count = 0;//起始位置间棋子的个数if (yi == yj)//列坐标不变,同列移动{for (int i = xi+1; i < xj; i ++){if (i == 5)continue;//如果行等于5,跳过if (redOrBlack(i, yi) != 0)count++;}for (int i = xi-1; i > xj; i --){if (i == 5)continue;//如果行等于5,跳过if (redOrBlack(i, yi) != 0)count++;}}else if (xi == xj)//行坐标不变,同行移动{for (int i = yi+1; i < yj; i ++)if (redOrBlack(xi, i) != 0)count++;for (int i = yi-1; i > yj; i --)if (redOrBlack(xi, i) != 0)count++;if ((xi == xj || yi == yj)&& (count <= 1) && redOrBlack(xj, yj) != -1)//如果棋子直行、没有犯规且落点不是红棋,可以移动{array[xi][yi] = CROSS;array[xj][yj] = B(炮);}else{restart = 1;}}//R(兵)----------------------------------------else if (array[xi][yi] == R(兵)){if (xi > xj)isStandard = 0;//如果倒退,则不符合规范if (xi == 3)if ((xj != xi+1) || (yi != yj))isStandard = 0;//第3行时只能前进一步if (xi == 4)if ((xj != xi+2) || (yi != yj))isStandard = 0;//第4行时只能前进两步if (xi > 4) {if ((xj == xi+1 && yi ==yj)|| (xj == xi && yi ==yj+1)||(xj == xi && yi ==yj-1)){}elseisStandard = 0;}if ((xi == xj || yi == yj)&& isStandard && redOrBlack(xj, yj) != 1)//{array[xi][yi] = CROSS;array[xj][yj] = R (兵);}else{restart = 1;}}//B(卒)----------------------------------------else if (array[xi][yi] == B(卒)){if (xi < xj)isStandard = 0;//如果倒退,则不符合规范if (xi == 7)if ((xj != xi-1) || (yi != yj))isStandard = 0;//第3行时只能前进一步if (xi == 6)if ((xj != xi-2) || (yi != yj))isStandard = 0;//第4行时只能前进两步if (xi < 4) {if ((xj == xi-1 && yi ==yj)|| (xj == xi && yi ==yj+1)||(xj == xi && yi ==yj-1)){}elseisStandard = 0;}if (isStandard && redOrBlack(xj, yj) != -1)//{array[xi][yi] = CROSS;array[xj][yj] = R (卒);}else{restart = 1;}}//R(相)----------------------------------------else if (array[xi][yi] == R(相)){if ((xj <= 4)&&(redOrBlack(xj, yj) != 1) && ((xj == xi-2 && yj == yi-2 &&redOrBlack(xi-1, yi-1) == 0) || (xj == xi-2 && yj == yi+2 &&redOrBlack(xi-1, yi+1) == 0) || (xj == xi+2 && yj == yi-2 &&redOrBlack(xi+1, yi-1) == 0) || (xj == xi+2 && yj == yi+2 &&redOrBlack(xi+1, yi+1) == 0))){array[xi][yi] = CROSS;array[xj][yj] = R(相);}else{restart = 1;}}//B(象)----------------------------------------else if (array[xi][yi] == B(象)){if ((xj >= 6)&&(redOrBlack(xj, yj) != -1) && ((xj == xi-2 && yj == yi-2 &&redOrBlack(xi-1, yi-1) == 0) || (xj == xi-2 && yj == yi+2 &&redOrBlack(xi-1, yi+1) == 0) || (xj == xi+2 && yj == yi-2&&redOrBlack(xi+1, yi-1) == 0) || (xj == xi+2 && yj == yi+2 &&redOrBlack(xi+1, yi+1) == 0))) {array[xi][yi] = CROSS;array[xj][yj] = B(象);}else{restart = 1;}}//R(仕)----------------------------------------else if (array[xi][yi] == R(仕)){if ((xj <= 2)&&(redOrBlack(xj, yj) != 1) && ((xj == xi-1 && yj == yi-1 ) || (xj == xi-1 && yj == yi+1 ) || (xj == xi+1 && yj == yi-1 ) || (xj == xi+1 && yj == yi+1 ))){array[xi][yi] = CROSS;array[xj][yj] = R(仕);}else{restart = 1;}}//B(士)----------------------------------------else if (array[xi][yi] == B(士)){if ((xj >= 8)&&(redOrBlack(xj, yj) != 1) && ((xj == xi-1 && yj == yi-1 ) || (xj == xi-1 && yj == yi+1 ) || (xj == xi+1 && yj == yi-1 ) || (xj == xi+1 && yj == yi+1 ))){array[xi][yi] = CROSS;array[xj][yj] = B(士);}else{restart = 1;}}//R(帅)----------------------------------------else if (array[xi][yi] == R(帅)){if ((xj <= 2 && yj <= 5 && yj >=3)&&(redOrBlack(xj, yj) != 1) && (((xj == xi)&&(yj == yi + 1 || yj == yi - 1))||((yj == yi)&&(xj == xi + 1 || xj == xi - 1)))){array[xi][yi] = CROSS;array[xj][yj] = R(帅);}else{restart = 1;}}//B(将)----------------------------------------else if (array[xi][yi] == B(将)){if ((xj >= 8 && yj <= 5 && yj >=3)&&(redOrBlack(xj, yj) != -1) && (((xj == xi)&&(yj == yi + 1 || yj == yi - 1))||((yj == yi)&&(xj == xi + 1 || xj == xi - 1)))){array[xi][yi] = CROSS;array[xj][yj] = B(将);}else{restart = 1;}}else {restart = 1;}}。
中国象棋源代码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){。
VC++的中国象棋源码
// 五子棋Dlg.cpp : implementation file// Download by #include "stdafx.h"#include "五子棋.h"#include "五子棋Dlg.h"#include "SettingDlg.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App Aboutclass CAboutDlg : public CDialog{public:CAboutDlg();// Dialog Data//{{AFX_DATA(CAboutDlg)enum { IDD = IDD_ABOUTBOX };//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CAboutDlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL// Implementationprotected://{{AFX_MSG(CAboutDlg)//}}AFX_MSGDECLARE_MESSAGE_MAP()};CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){//{{AFX_DATA_INIT(CAboutDlg)//}}AFX_DATA_INIT}void CAboutDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CAboutDlg)//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)//{{AFX_MSG_MAP(CAboutDlg)// No message handlers//}}AFX_MSG_MAPEND_MESSAGE_MAP()///////////////////////////////////////////////////////////////////////////// // CMyDlg dialogCMyDlg::CMyDlg(CWnd* pParent /*=NULL*/): CDialog(CMyDlg::IDD, pParent){//{{AFX_DATA_INIT(CMyDlg)// NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT// Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);m_num1=1;CBitmap qp;qp.LoadBitmap(IDB_BITMAP1);tqp.CreateCompatibleDC(NULL);tqp.SelectObject(&qp);qp.DeleteObject();}void CMyDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CMyDlg)// NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CMyDlg, CDialog)//{{AFX_MSG_MAP(CMyDlg)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDC_BUTTON4, OnButton4)ON_BN_CLICKED(IDC_BUTTON3, OnButton3)ON_BN_CLICKED(IDC_BUTTON1, OnButton1)ON_WM_LBUTTONDOWN()ON_WM_CANCELMODE()ON_BN_CLICKED(IDC_BUTTON2, OnButton2)//}}AFX_MSG_MAPEND_MESSAGE_MAP()///////////////////////////////////////////////////////////////////////////// // CMyDlg message handlersBOOL CMyDlg::OnInitDialog(){CDialog::OnInitDialog();// Add "About..." menu item to system menu.// IDM_ABOUTBOX must be in the system command range.ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){pSysMenu->AppendMenu(MF_SEPARATOR);pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);}}// Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialogSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small icon// TODO: Add extra initialization herechess.SetDc(&tqp,this->GetDC());return TRUE; // return TRUE unless you set the focus to a controlvoid CMyDlg::OnSysCommand(UINT nID, LPARAM lParam){if ((nID & 0xFFF0) == IDM_ABOUTBOX){CAboutDlg dlgAbout;dlgAbout.DoModal();}else{CDialog::OnSysCommand(nID, lParam);}}// If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework.void CMyDlg::OnPaint(){if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;// Draw the icondc.DrawIcon(x, y, m_hIcon);}else{CDialog::OnPaint();chess.ReDraw();}}// The system calls this to obtain the cursor to display while the user drags // the minimized window.HCURSOR CMyDlg::OnQueryDragIcon(){return (HCURSOR) m_hIcon;}void CMyDlg::OnButton4(){// TODO: Add your control notification handler code hereCAboutDlg aboutdlg;aboutdlg.DoModal();}void CMyDlg::OnButton3(){// TODO: Add your control notification handler code hereCSettingDlg dlg;dlg.m_type=CMyDlg::m_num1;if(IDOK==dlg.DoModal()){CMyDlg::m_num1=dlg.m_type;chess.NewGame(m_num1);}}void CMyDlg::OnButton1(){// TODO: Add your control notification handler code herechess.NewGame(m_num1);}void CMyDlg::OnLButtonDown(UINT nFlags, CPoint point){// TODO: Add your message handler code here and/or call defaultint x1,y1;x1=(int)(point.x-7)/29;y1=(int)(point.y-7)/29;chess.DownZi(x1,y1,m_num1,m_hWnd);CDialog::OnLButtonDown(nFlags, point);}void CMyDlg::OnButton2(){// TODO: Add your control notification handler code herechess.BackGo();}// stdafx.cpp : source file that includes just the standard includes// 五子棋.pch will be the pre-compiled header// stdafx.obj will contain the pre-compiled type information#include "stdafx.h"// stdafx.h : include file for standard system include files,// or project specific include files that are used frequently, but// are changed infrequently//#if !defined(AFX_STDAFX_H__F7DE87B0_9475_4FDA_AEF4_C53C73C48D83__INCLUDED_)#define AFX_STDAFX_H__F7DE87B0_9475_4FDA_AEF4_C53C73C48D83__INCLUDED_#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers#include <afxwin.h> // MFC core and standard components#include <afxext.h> // MFC extensions#include <afxdisp.h> // MFC Automation classes#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #ifndef _AFX_NO_AFXCMN_SUPPORT#include <afxcmn.h> // MFC support for Windows Common Controls#endif // _AFX_NO_AFXCMN_SUPPORT//{{AFX_INSERT_LOCATION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif// !defined(AFX_STDAFX_H__F7DE87B0_9475_4FDA_AEF4_C53C73C48D83__INCLUDED_) Microsoft Developer Studio Workspace File, Format Version 6.00# 警告: 不能编辑或删除该工作区文件!###############################################################################Project: "五子棋"=".\五子棋.dsp" - Package Owner=<4>Package=<5>{{{}}}Package=<4>{{{}}}############################################################################### Global:Package=<5>{{{}}}Package=<3>{{{}}}###############################################################################// 五子棋.h : main header file for the 五子棋 application//#if !defined(AFX__H__3BD1ACC8_B9C0_42BC_B055_F0D95FD559B8__INCLUDED_)#define AFX__H__3BD1ACC8_B9C0_42BC_B055_F0D95FD559B8__INCLUDED_#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000#ifndef __AFXWIN_H__#error include 'stdafx.h' before including this file for PCH#endif#include "resource.h" // main symbols/////////////////////////////////////////////////////////////////////////////// CMyApp:// See 五子棋.cpp for the implementation of this class//class CMyApp : public CWinApp{public:CMyApp();// Overrides// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CMyApp)public:virtual BOOL InitInstance();//}}AFX_VIRTUAL// Implementation//{{AFX_MSG(CMyApp)// NOTE - the ClassWizard will add and remove member functions here.// DO NOT EDIT what you see in these blocks of generated code !//}}AFX_MSGDECLARE_MESSAGE_MAP()};///////////////////////////////////////////////////////////////////////////////{{AFX_INSERT_LOCATION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif // !defined(AFX__H__3BD1ACC8_B9C0_42BC_B055_F0D95FD559B8__INCLUDED_) struct pos{int x,y;int flag;};//{{NO_DEPENDENCIES}}// Microsoft Developer Studio generated include file.// Used by 五子棋.rc//#define IDM_ABOUTBOX 0x0010#define IDD_ABOUTBOX 100#define IDS_ABOUTBOX 101#define IDD_MY_DIALOG 102#define IDR_MAINFRAME 128#define IDD_DIALOG1 129#define IDB_BITMAP1 130#define IDC_BUTTON1 1000#define IDC_BUTTON2 1001#define IDC_RADIO1 1001#define IDC_BUTTON3 1002#define IDC_RADIO2 1002#define IDC_BUTTON4 1003#define IDC_RADIO3 1003#define IDC_RADIO4 1004// Next default values for new objects//#ifdef APSTUDIO_INVOKED#ifndef APSTUDIO_READONLY_SYMBOLS#define _APS_NEXT_RESOURCE_VALUE 131#define _APS_NEXT_COMMAND_VALUE 32771#define _APS_NEXT_CONTROL_VALUE 1002#define _APS_NEXT_SYMED_VALUE 101#endif#endif// 五子棋Dlg.h : header file//#if !defined(AFX_DLG_H__92DA4FFC_303C_4677_8281_72F1BC71336E__INCLUDED_)#define AFX_DLG_H__92DA4FFC_303C_4677_8281_72F1BC71336E__INCLUDED_#include "Chess.h" // Added by ClassView#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000///////////////////////////////////////////////////////////////////////////// // CMyDlg dialogclass CMyDlg : public CDialog{// Constructionpublic:int m_num1;CMyDlg(CWnd* pParent = NULL); // standard constructorCDC tqp;// Dialog Data//{{AFX_DATA(CMyDlg)enum { IDD = IDD_MY_DIALOG };// NOTE: the ClassWizard will add data members here//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CMyDlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support//}}AFX_VIRTUAL// Implementationprotected:HICON m_hIcon;// Generated message map functions//{{AFX_MSG(CMyDlg)virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void OnButton4();afx_msg void OnButton3();afx_msg void OnButton1();afx_msg void OnLButtonDown(UINT nFlags, CPoint point);afx_msg void OnButton2();//}}AFX_MSGDECLARE_MESSAGE_MAP()private:CChess chess;};//{{AFX_INSERT_LOCATION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif // !defined(AFX_DLG_H__92DA4FFC_303C_4677_8281_72F1BC71336E__INCLUDED_) #if !defined(AFX_SETTINGDLG_H__F07D46A4_1FBC_498B_A59F_FD1A5EAC64B6__INCLUDED_) #define AFX_SETTINGDLG_H__F07D46A4_1FBC_498B_A59F_FD1A5EAC64B6__INCLUDED_#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000// SettingDlg.h : header file/////////////////////////////////////////////////////////////////////////////// // CSettingDlg dialogclass CSettingDlg : public CDialog{// Constructionpublic:CSettingDlg(CWnd* pParent = NULL); // standard constructor// Dialog Data//{{AFX_DATA(CSettingDlg)enum { IDD = IDD_DIALOG1 };int m_type;//}}AFX_DATA// Overrides// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CSettingDlg)protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support//}}AFX_VIRTUAL// Implementationprotected:// Generated message map functions//{{AFX_MSG(CSettingDlg)// NOTE: the ClassWizard will add member functions here//}}AFX_MSGDECLARE_MESSAGE_MAP()};//{{AFX_INSERT_LOCATION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif// !defined(AFX_SETTINGDLG_H__F07D46A4_1FBC_498B_A59F_FD1A5EAC64B6__INCLUDED_) // Chess.h: interface for the CChess class.//////////////////////////////////////////////////////////////////////#if !defined(AFX_CHESS_H__590E0189_29A3_4903_A772_1E8B2DCFA3F1__INCLUDED_)#define AFX_CHESS_H__590E0189_29A3_4903_A772_1E8B2DCFA3F1__INCLUDED_#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000#include "info.h"class CChess //实现五子棋功能的类{public:void BackGo(); //悔棋void SetDc(CDC*,CDC*); //设置绘图dcvoid NewGame(int); //新游戏void ReDraw(); //重画函数bool DownZi(int nx,int ny,int type,HWND hwnd); //外不调用此函数下子CChess();virtual ~CChess();private:void AiGo(int &,int &); //本人独创的五子棋AI,智力不是很高,但基本实现下棋功能void DrawQz(int nx,int ny,int type=0);//画棋子void DrawQp(); //画棋盘int PanYing(int nx,int ny); //判断输赢int m_turn; //下棋次序int m_flag; //输赢标志,1白,2黑CDC *dc,*qp;char m_board[15][15]; //棋盘数组pos posinfo[225]; //下子信息数组,用于悔棋函数int posflag; //下子信息数组下标};#endif // !defined(AFX_CHESS_H__590E0189_29A3_4903_A772_1E8B2DCFA3F1__INCLUDED_) // Chess.cpp: implementation of the CChess class.// Download by //////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "五子棋.h"#include "Chess.h"#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#define new DEBUG_NEW#endif//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////CChess::CChess(){memset(m_board,0,sizeof(m_board));m_turn=1;m_flag=0;posflag=0;}CChess::~CChess(){}int CChess::PanYing(int nx, int ny){int count=0;for(int i=-4;i<5;i++){if(m_board[ny][nx+i]==m_turn) {count++;if(count==5) return m_turn;}else count=0;}count=0;for(i=-4;i<5;i++){if(m_board[ny+i][nx]==m_turn) {count++;if(count==5) return m_turn;}else count=0;}count=0;for(i=-4;i<5;i++){if(m_board[ny+i][nx+i]==m_turn) {count++;if(count==5) return m_turn;}else count=0;}count=0;for(i=-4;i<5;i++){if(m_board[ny+i][nx-i]==m_turn) {count++;if(count==5) return m_turn;}else count=0;}count=0;return 0;}void CChess::DrawQp(){dc->BitBlt(0,0,446,446,qp,0,0,SRCCOPY);}void CChess::DrawQz(int nx,int ny,int type){if(type==0){if(m_turn==1){dc->Ellipse(nx*29+7,ny*29+7,nx*29+34,ny*29+34);posinfo[posflag].x=nx;posinfo[posflag].y=ny;posinfo[posflag].flag=m_turn;posflag++;}else{CBrush *brush;CBrush brush1(RGB(0,0,0));brush=dc->SelectObject(&brush1);dc->Ellipse(nx*29+7,ny*29+7,nx*29+34,ny*29+34);posinfo[posflag].x=nx;posinfo[posflag].y=ny;posinfo[posflag].flag=m_turn;posflag++;dc->SelectObject(brush);}}else if(type==1){dc->Ellipse(nx*29+7,ny*29+7,nx*29+34,ny*29+34);posinfo[posflag].x=nx;posinfo[posflag].y=ny;posinfo[posflag].flag=m_turn;posflag++;}else{CBrush *brush;CBrush brush1(RGB(0,0,0));brush=dc->SelectObject(&brush1);dc->Ellipse(nx*29+7,ny*29+7,nx*29+34,ny*29+34);posinfo[posflag].x=nx;posinfo[posflag].y=ny;posinfo[posflag].flag=m_turn;posflag++;dc->SelectObject(brush);}}bool CChess::DownZi(int nx, int ny,int type,HWND hwnd){int x,y;if(nx<0||nx>14||ny<0||ny>14){MessageBox(hwnd,"不正确的下子位置!", NULL,MB_OK);return false;}if(CChess::m_flag!=0)//已分出胜负{if(m_flag==1){MessageBox(hwnd,"白棋获胜!", NULL,MB_OK);return true;}else{MessageBox(hwnd,"黑棋获胜!", NULL,MB_OK);return true;} }if(m_board[ny][nx]==0){if(type==2)//人人对战{m_board[ny][nx]=m_turn;DrawQz(nx,ny);m_flag=PanYing(nx,ny);m_turn=(m_turn==1?2:1);if(m_flag==1){MessageBox(hwnd,"白棋获胜!", NULL,MB_OK);return true;}if(m_flag==2){MessageBox(hwnd,"黑棋获胜!", NULL,MB_OK);return true;}return true;}else //人机对战{m_board[ny][nx]=m_turn;DrawQz(nx,ny);m_flag=PanYing(nx,ny);m_turn=(m_turn==1?2:1);if(m_flag==1){MessageBox(hwnd,"白棋获胜!", NULL,MB_OK);return true;}if(m_flag==2){MessageBox(hwnd,"黑棋获胜!", NULL,MB_OK);return true;}CChess::AiGo(x,y);m_board[y][x]=m_turn;DrawQz(x,y);m_flag=PanYing(x,y);m_turn=(m_turn==1?2:1);if(m_flag==1){MessageBox(hwnd,"白棋获胜!", NULL,MB_OK);return true;}if(m_flag==2){MessageBox(hwnd,"黑棋获胜!", NULL,MB_OK);return true;}return true;}}return false;}void CChess::ReDraw(){DrawQp();for(int i=0;i<15;i++)for(int j=0;j<15;j++){if(m_board[i][j]==1){DrawQz(j,i,1);}if(m_board[i][j]==2){DrawQz(j,i,2);}}}void CChess::NewGame(int type){memset(m_board,0,sizeof(m_board));m_flag=0;m_turn=1;posflag=0;if(type==0){m_board[7][7]=1;m_turn=2;posinfo[posflag].x=7;posinfo[posflag].y=7;posinfo[posflag].flag=2;posflag++;}ReDraw();}void CChess::SetDc(CDC* tqp, CDC *qz){qp=tqp;dc=qz;}void CChess::AiGo(int& t, int &h){int qiju[2][15][15][8][2]={0}; /* 棋型数组*/int k,i,j,q,b=0,a=1,d,y1=0,y2=0,x1=0,x2=0;int a1[15][15]={0},a2[15][15]={0};/****************为双方填写棋型表************/for(k=0;k<2;k++)for(i=0;i<15;i++)for(j=0;j<15;j++){if(m_board[i][j]==0){for(q=0;q<8;q++){if(k==0) d=1;else d=2;if(q==0&&j>=0){for(;j-a>=0;){if(m_board[i][j-a]==d){b++;a++;continue;}else break;}qiju[k][i][j][q][0]=b;b=0;if(m_board[i][j-a]==0&&j-a>=0){qiju[k][i][j][q][1]=1;a=1;}else {qiju[k][i][j][q][1]=0;a=1;}}if(q==1&&i>=0&&j>=0){for(;i-a>=0&&j-a>=0;){if(m_board[i-a][j-a]==d){b++;a++;continue;}else break;}qiju[k][i][j][q][0]=b;b=0;if(m_board[i-a][j-a]==0&&j-a>=0&&i-a>=0){qiju[k][i][j][q][1]=1;a=1;}else {qiju[k][i][j][q][1]=0;a=1;}}if(q==2&&i>=0){for(;i-a>=0;){if(m_board[i-a][j]==d){b++;a++;continue;}else break;}qiju[k][i][j][q][0]=b;b=0;if(m_board[i-a][j]==0&&i-a>=0){qiju[k][i][j][q][1]=1;a=1;}else {qiju[k][i][j][q][1]=0;a=1;}}if(q==3&&i>=0&&j<15){for(;i-a>=0&&j+a<15;){if(m_board[i-a][j+a]==d){b++;a++;continue;}else break;}qiju[k][i][j][q][0]=b;b=0;if(m_board[i-a][j+a]==0&&i-a>=0&&j+a<15){qiju[k][i][j][q][1]=1;a=1;}else {qiju[k][i][j][q][1]=0;a=1;}}if(q==4&&j<15){for(;j+a<15;){if(m_board[i][j+a]==d){b++;a++;continue;}else break;}qiju[k][i][j][q][0]=b;b=0;if(m_board[i][j+a]==0&&j+a<15){qiju[k][i][j][q][1]=1;a=1;}else {qiju[k][i][j][q][1]=0;a=1;}}if(q==5&&i<15&&j<15){for(;i+a<15&&j+a<15;){if(m_board[i+a][j+a]==d){b++;a++;continue;}else break;}qiju[k][i][j][q][0]=b;b=0;if(m_board[i+a][j+a]==0&&i+a<15&&j+a<15){qiju[k][i][j][q][1]=1;a=1;}else {qiju[k][i][j][q][1]=0;a=1;}}if(q==6&&i<15){for(;i+a<15;){if(m_board[i+a][j]==d){b++;a++;continue;}else break;}qiju[k][i][j][q][0]=b;b=0;if(m_board[i+a][j]==0&&i+a<15){qiju[k][i][j][q][1]=1;a=1;}else {qiju[k][i][j][q][1]=0;a=1;}}if(q==7&&j>=0&&i<15){for(;i+a<15&&j-a>=0;){if(m_board[i+a][j-a]==d){b++;a++;continue;}else break;}qiju[k][i][j][q][0]=b;b=0;if(m_board[i+a][j-a]==0&&i+a<15&&j-a>=0){qiju[k][i][j][q][1]=1;a=1;}else {qiju[k][i][j][q][1]=0;a=1;}}}}}/******************根据评分规则对每一个空格评分***************/for(k=0;k<2;k++)for(i=0;i<15;i++)for(j=0;j<15;j++){if(k==0) /*为白棋评分*/{for(q=0;q<4;q++){if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==4&&qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==1)b+=7000;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==3&&qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==1)b+=301;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==2&&qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==1)b+=43;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==1&&qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==1)b+=11;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==4&&((qiju[k][i][j][q+4][1]==0)||(qiju[k][i][j][q][1]==0)))b+=7000;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==3&&((qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==0)||(qiju[k][i][j][q][1]==0&&qiju[k][i][j][q+4][1]==1)))b+=63;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==2&&((qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==0)||(qiju[k][i][j][q][1]==0&&qiju[k][i][j][q+4][1]==1)))b+=6;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==1&&((qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==0)||(qiju[k][i][j][q][1]==0&&qiju[k][i][j][q+4][1]==1)))b+=1;}if(b==126||b==189||b==252) b=1500;if(b==106) b=1000;a1[i][j]=b;b=0;}if(k==1) /*为黑棋评分*/{for(q=0;q<4;q++){if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==4&&qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==1)b+=30000;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==3&&qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==1)b+=1500;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==2&&qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==1)b+=51;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==1&&qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==1)b+=16;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==4&&((qiju[k][i][j][q+4][1]==0)||(qiju[k][i][j][q][1]==0)))b+=30000;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==3&&((qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==0)||(qiju[k][i][j][q][1]==0&&qiju[k][i][j][q+4][1]==1)))b+=71;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==2&&((qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==0)||(qiju[k][i][j][q][1]==0&&qiju[k][i][j][q+4][1]==1)))b+=7;if((qiju[k][i][j][q][0]+qiju[k][i][j][q+4][0])==1&&((qiju[k][i][j][q][1]==1&&qiju[k][i][j][q+4][1]==0)||(qiju[k][i][j][q][1]==0&&qiju[k][i][j][q+4][1]==1)))b+=2;}if(b==142||b==213||b==284) b=1500;if(b==122) b=1300;a2[i][j]=b;b=0;}}/****************算出分数最高的空位,填写坐标*********************/for(i=0;i<15;i++)for(j=0;j<15;j++){if(a1[y1][x1]<a1[i][j]) {y1=i;x1=j;}}for(i=0;i<15;i++)for(j=0;j<15;j++){if(a2[y2][x2]<a2[i][j]) {y2=i;x2=j;}}if(a2[y2][x2]>=a1[y1][x1]) {t=x2;h=y2;}else{t=x1;h=y1;}}void CChess::BackGo(){m_board[posinfo[posflag-1].y][posinfo[posflag-1].x]=0;ReDraw();}// SettingDlg.cpp : implementation file// Download by #include "stdafx.h"#include "五子棋.h"#include "SettingDlg.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif///////////////////////////////////////////////////////////////////////////// // CSettingDlg dialogCSettingDlg::CSettingDlg(CWnd* pParent /*=NULL*/): CDialog(CSettingDlg::IDD, pParent){//{{AFX_DATA_INIT(CSettingDlg)m_type = -1;//}}AFX_DATA_INIT}void CSettingDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CSettingDlg)DDX_Radio(pDX, IDC_RADIO1, m_type);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CSettingDlg, CDialog)//{{AFX_MSG_MAP(CSettingDlg)// NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAPEND_MESSAGE_MAP()///////////////////////////////////////////////////////////////////////////// // CSettingDlg message handlers// 五子棋.cpp : Defines the class behaviors for the application.// Download by #include "stdafx.h"#include "五子棋.h"#include "五子棋Dlg.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif///////////////////////////////////////////////////////////////////////////// // CMyAppBEGIN_MESSAGE_MAP(CMyApp, CWinApp)//{{AFX_MSG_MAP(CMyApp)// NOTE - the ClassWizard will add and remove mapping macros here.// DO NOT EDIT what you see in these blocks of generated code!//}}AFX_MSGON_COMMAND(ID_HELP, CWinApp::OnHelp)END_MESSAGE_MAP()///////////////////////////////////////////////////////////////////////////// // CMyApp constructionCMyApp::CMyApp(){// TODO: add construction code here,// Place all significant initialization in InitInstance}///////////////////////////////////////////////////////////////////////////// // The one and only CMyApp objectCMyApp theApp;///////////////////////////////////////////////////////////////////////////// // CMyApp initializationBOOL CMyApp::InitInstance(){AfxEnableControlContainer();// Standard initialization// If you are not using these features and wish to reduce the size// of your final executable, you should remove from the following// the specific initialization routines you do not need.#ifdef _AFXDLLEnable3dControls(); // Call this when using MFC in a shared DLL #elseEnable3dControlsStatic(); // Call this when linking to MFC statically #endifCMyDlg dlg;m_pMainWnd = &dlg;int nResponse = dlg.DoModal();if (nResponse == IDOK){// TODO: Place code here to handle when the dialog is// dismissed with OK}else if (nResponse == IDCANCEL){// TODO: Place code here to handle when the dialog is// dismissed with Cancel}// Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump.return FALSE;}。
中国象棋(代码)
中国象棋(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();}。
联网式-中国象棋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。
中国象棋游戏代码
中国象棋游戏代码#include<stdio.h>#include<stdlib.h>#include<string.h>char x, y, z;int i, i1, j, j1, k, k1, ii, jj;int f(char X){if (X == '0')printf(" ");else{if (X >= 'a' || X <= 'g'){switch (X - 'a'){case 6:printf("兵");break;case 5:printf("包");break;case 4:printf("帅");break;case 3:printf("士");break;case 2:printf("相");break;case 1:printf("马");break;case 0:printf("车");}}if (X <= 'A' || X <= 'G'){switch (X - 'A'){case 6:printf("卒");break;case 5:printf("炮");break;case 4:printf("将");break;case 3:printf("仕");break;case 2:printf("象");break;case 1:printf("馬");break;case 0:printf("車");}}}}char f2(char **str2, int q){int m, n, o, p;char x1, x2, y2, y1, z1;if (q == 1)printf("\n轮到红子动!\n");elseprintf("\n轮到黑子动!\n");for (;;){if (q == 1)printf("\n攻(红)方:车(a) 马(b)\n");elseprintf("\n黑(守)方:将(E)\n");lm1:printf("请选择棋子代号:");scanf("%c", &x);scanf("%c", &x);if (q == 1 && x != 'a' && x != 'b'){printf("请按要求输入!\n");goto lm1;}if (q == 0 && x != 'E'){printf("请按要求输入!\n");goto lm1;}printf("(欲换棋子输入'0 0')请选择该子所在位置(行与列):");scanf("%d%d", &i, &j);if (i == 0 && j == 0)goto lm1;for (;;){if (i < 1 || i > 3 || j < 1 || j > 3){printf("请认真输入,位置应在棋盘内!\n再次输入:");scanf("%d%d", &i, &j);}elsebreak;}i--;j--;if (*(*(str2 + j) + i) == x)break;elseprintf("该位置没有该棋子!请认真输入!\n");}printf("请输入要下的位置(移动后位置):");label1:scanf("%d%d", &i1, &j1);for (;;){if (i1 < 1 || i1 > 3 || j1 < 1 || j1 > 3){printf("请认真输入,位置应在棋盘内!\n再次输入:");scanf("%d%d", &i1, &j1);}elsebreak;}i1--;j1--;y = *(*(str2 + j1) + i1);if (q == 1 && (y == 'a' || y == 'b')){printf("移动后位置有己方棋子\n重新输入下的位置:");goto label1;}else{if (i1 == i && j1 == j){printf("原地未动\n重新输入下的位置:");goto label1;}else{if (x == 'a'){if (i1 != i && j1 != j){printf("'车'应直走!\n重新输入下的位置:");goto label1;}else{if (i1 == i){if (j1 > j)for (k = j + 1; k < j1; k++){if (*(*(str2 + k) + i) != '0'){printf("中间有子挡\n重新输入下的位置:");goto label1;}}else{for (k = j1 + 1; k < j; k++){if (*(*(str2 + k) + i) != '0'){printf("中间有子挡\n重新输入下的位置:");goto label1;}}}}else{if (i1 > i)for (k = i + 1; k < i1; k++){if (*(*(str2 + j) + k) != '0'){printf("中间有子挡\n重新输入下的位置:");goto label1;}}else{for (k = i1 + 1; k < i; k++){if (*(*(str2 + j) + k) != '0'){printf("中间有子挡\n重新输入下的位置:");goto label1;}}}}}if (i1 != ii && j1 != jj){if (ii == 0){if ((jj == 0 || jj == 2)&& (*(*(str2 + 1) + 2) != 'b'|| ((*(*str2 + 1) + 2) == 'b' && *(*(str2 + 1) + 1) != '0'))) {printf("未将军!\n");goto lm1;}if (jj == 1&& (*(*(str2 + 0) + 2) != 'b'|| (*(*(str2 + 0) + 2) == 'b' && *(*(str2) + 1) != '0'))&& (*(*(str2 + 2) + 2) != 'b'|| (*(*(str2 + 2) + 2) == 'b' && *(*(str2 + 2) + 1) != '0'))) {printf("未将军!\n");goto lm1;}}if (ii == 1 && jj == 0&& (*(*(str2 + 2)) != 'b'|| (*(*(str2 + 2)) == 'b' && *(*(str2 + 1)) != '0'))&& (*(*(str2 + 2) + 2) != 'b'|| (*(*(str2 + 2) + 2) == 'b' && *(*(str2 + 1) + 2) != '0'))) {printf("未将军!\n");goto lm1;}if (ii == 1 && jj == 2&& (**str2 != 'b' || (**str2 == 'b' && *(*(str2 + 1)) != '0'))&& (*(*(str2) + 2) != 'b'|| (*(*(str2) + 2) == 'b' && *(*(str2 + 1) + 2) != '0'))) {printf("未将军!\n");goto lm1;}if (ii == 2){if ((jj == 0 || jj == 2)&& (*(*(str2 + 1)) != 'b'|| ((*(*str2 + 1)) == 'b' && *(*(str2 + 1) + 1) != '0'))) {printf("未将军!\n");goto lm1;}if (jj == 1&& (*(*(str2 + 0)) != 'b'|| (*(*(str2 + 0)) == 'b' && *(*(str2) + 1) != '0'))&& (*(*(str2 + 2)) != 'b'|| (*(*(str2 + 2)) == 'b' && *(*(str2 + 2) + 1) != '0'))) {printf("未将军!\n");goto lm1;}}}}if (x == 'b'){if (i1 == i + 1 || i1 == i - 1){if (j1 == j + 2){if (*(*(str2 + j + 1) + i) != '0'){printf("'马'撇腿!\n重新输入下的位置:");goto label1;}else{if (((i1 != ii + 1 || i1 != ii - 1)&& (j1 != jj + 2 || j1 != jj - 2)) && ((j1 != jj + 1|| j1 != jj - 1)&& (i1 != ii + 2|| i1 !=ii - 2))&& y != 'E'){printf("未将军\n");goto lm1;}goto la1;}}else{if (j1 == j - 2){if (*(*(str2 + j - 1) + i) != '0'){printf("'马'撇腿!\n重新输入下的位置:");goto label1;}else{if (((i1 != ii + 1 || i1 != ii - 1)&& (j1 != jj + 2 || j1 != jj - 2))&& ((j1 != jj + 1 || j1 != jj - 1)&& (i1 != ii + 2 || i1 != ii - 2)) && y != 'E'){printf("未将军\n");goto lm1;}goto la1;}}else{printf("'马'应走'日'\n重新输入下的位置:");goto label1;}}}else{if (i1 == i + 2 || i1 == i - 2){if (j1 == j + 1 || j1 == j - 1){if (*(*(str2 + j) + (i1 + i) / 2) != '0'){printf("'马'撇腿!\n重新输入下的位置:");goto label1;}else{if (((i1 != ii + 1 || i1 != ii - 1)&& (j1 != jj + 2 || j1 != jj - 2))&& ((j1 != jj + 1 || j1 != jj - 1)&& (i1 != ii + 2 || i1 != ii - 2)) && y != 'E'){printf("未将军\n");goto lm1;}goto la1;}}else{printf("'马'应走'日'\n重新输入下的位置:");goto label1;}}else{printf("'马'应走'日'\n重新输入下的位置:");goto label1;}}}if (x == 'E'){ii = i1;jj = j1;if ((i1 == i + 1 || i1 == i - 1) && j1 == j)goto la1;else{if (i1 == i && (j1 == j + 1 || j1 == j - 1))goto la1;else{printf("'帅'一次只(直)走一格\n重新输入下的位置:");goto label1;}}}}la1:*(*(str2 + j1) + i1) = x;*(*(str2 + j) + i) = '0';printf("\n");for (m = 0; m < 3; m++){for (n = 0; n < 3; n++){o = *(*(str2 + n) + m);f(o);}printf("\n\n");}}}char f1(char **str, int q){int m, n, o, p, o3;char x1, x2, y2, y1, z1;if (q == 1){x1 = 'a';x2 = 'A';y1 = 'g';y2 = 'G';o3 = 7;}else{x1 = 'A';x2 = 'a';y1 = 'G';y2 = 'g';o3 = 2;}if (q == 1)printf("\n轮到红子动!\n");elseprintf("\n轮到黑子动!\n");for (;;){if (q == 1)printf("\n红方:车(a) 马(b) 相(c) 士(d) 帅(e) 包(f) 兵(g)\n");elseprintf("\n黑方:車(A) 馬(B) 象(C) 仕(D) 将(E) 炮(F) 卒(G)\n"); lm:printf("请选择棋子代号:");scanf("%c", &x);scanf("%c", &x);if (x >= x2 && x <= y2){printf("请不要动对方棋子\n");goto lm;}else if (x > y1 || x < x1){printf("输入不合要求!\n");goto lm;}printf("(欲换棋子输入'0 0')请选择该子所在位置(行与列):");scanf("%d%d", &i, &j);if (i == 0 && j == 0)goto lm;for (;;){if (i < 1 || i > 10 || j < 1 || j > 9){printf("请认真输入,位置应在棋盘内!\n再次输入:");scanf("%d%d", &i, &j);}elsebreak;}i--;j--;if (*(*(str + j) + i) == x)break;elseprintf("该位置没有该棋子!请认真输入!\n");}printf("请输入要下的位置(移动后位置):");label:scanf("%d%d", &i1, &j1);for (;;){if (i1 < 1 || i1 > 10 || j1 < 1 || j1 > 9){printf("请认真输入,位置应在棋盘内!\n再次输入:");scanf("%d%d", &i1, &j1);}elsebreak;}i1--;j1--;y = *(*(str + j1) + i1);if (y >= x1 && y <= y1){printf("移动后位置有己方棋子\n重新输入下的位置:");goto label;}else{if (i1 == i && j1 == j){printf("原地未动\n重新输入下的位置:");goto label;}else{/*车的情况*/if (x == 'a' || x == 'A'){if (i1 != i && j1 != j){if (q == 1)printf("'车'应直走!\n");elseprintf("'車'应直走!\n重新输入下的位置:");goto label;}else{if (i1 == i){if (j1 > j)for (k = j + 1; k < j1; k++){if (*(*(str + k) + i) != '0'){printf("中间有子挡\n重新输入下的位置:");goto label;}}else{for (k = j1 + 1; k < j; k++){if (*(*(str + k) + i) != '0'){printf("中间有子挡\n重新输入下的位置:");goto label;}}}}else{if (i1 > i)for (k = i + 1; k < i1; k++){if (*(*(str + j) + k) != '0')printf("中间有子挡\n重新输入下的位置:");goto label;}}else{for (k = i1 + 1; k < i; k++){if (*(*(str + j) + k) != '0'){printf("中间有子挡\n重新输入下的位置:");goto label;}}}}}}/*车的情况*/ /*马的情况*/ if (x == 'b' || x == 'B'){if (i1 == i + 1 || i1 == i - 1){if (j1 == j + 2){if (*(*(str + j + 1) + i) != '0'){if (q == 1)printf("'马'撇腿!\n");elseprintf("'馬'撇腿!\n重新输入下的位置:");goto label;}elsegoto la;}else{if (j1 == j - 2){if (*(*(str + j - 1) + i) != '0'){if (q == 1)printf("'马'撇腿!\n");printf("'馬'撇腿!\n重新输入下的位置:");goto label;}elsegoto la;}else{if (q == 1)printf("'马'应走'日'\n");elseprintf("'馬'应走'日'\n重新输入下的位置:");goto label;}}}else{if (i1 == i + 2 || i1 == i - 2){if (j1 == j + 1 || j1 == j - 1){if (*(*(str + j) + (i1 + i) / 2) != '0'){if (q == 1)printf("'马'撇腿!\n");elseprintf("'馬'撇腿!\n重新输入下的位置:");goto label;}elsegoto la;}else{if (q == 1)printf("'马'应走'日'\n");elseprintf("'馬'应走'日'\n重新输入下的位置:");goto label;}}else{if (q == 1)printf("'马'应走'日'\n");elseprintf("'馬'应走'日'\n重新输入下的位置:");goto label;}}}/*马的情况*/ /*相的情况*/ if (x == 'c' || x == 'C'){if ((i1 == i + 2 || i1 == i - 2) && (j1 == j + 2 || j1 == j - 2)){if (*(*(str + (j + j1) / 2) + (i + i1) / 2) != '0'){if (q == 1)printf("'相'压田!\n");elseprintf("'象'压田!\n重新输入下的位置:");goto label;}elsegoto la;}else{if (q == 1)printf("'相'应飞'田'\n");elseprintf("'象'应飞'田'\n重新输入下的位置:");goto label;}}/*相的情况*/ /*士的情况*/ if (x == 'd' || x == 'D'){if (q == 1 && (j1 < 3 || j1 > 5 || i1 < o3)){printf("'士'不可出九宫格\n重新输入下的位置:");goto label;}else{if (q == 0 && (j1 < 3 || j1 > 5 || i1 > o3)){printf("'仕'不可出九宫格\n重新输入下的位置:");goto label;}else{if ((i1 == i + 1 || i1 == i - 1) && (j1 == j + 1 || j1 == j - 1))goto la;else{if (q == 1)printf("'士'应斜着走\n");elseprintf("'仕'应斜着走\n重新输入下的位置:");goto label;}}}}/*士的情况*/ /*帅的情况*/if (x == 'e' || x == 'E'){for (k = i1 - 1; k >= 0; k--){if (*(*(str + j1) + k) != '\0'){if (q == 1)z1 = 'E';elsez1 = 'e';if (*(*(str + j1) + k) == z1){printf("'将''帅' 照面\n重新输入下的位置:");goto label;}break;}}if (q == 1 && (j1 < 3 || j1 > 5 || i1 < o3)){printf("'帅'不可出九宫格\n重新输入下的位置:");goto label;}else{if (q == 0 && (j1 < 3 || j1 > 5 || i1 > o3)){printf("'将'不可出九宫格\n重新输入下的位置:");goto label;}else{if ((i1 == i + 1 || i1 == i - 1) && j1 == j)goto la;else{if (i1 == i && (j1 == j + 1 || j1 == j - 1))goto la;else{if (q == 1)printf("'帅'一次只(直)走一格\n");elseprintf("'将'一次只(直)走一格\n重新输入下的位置:");goto label;}}}}}/*帅的情况*/ /*包的情况*/ if (x == 'f' || x == 'F'){if (i1 != i && j1 != j){if (q == 1)printf("'包'应直走!\n");elseprintf("'炮'应直走!\n重新输入下的位置:");goto label;}else{if (i1 == i){if (j1 > j){for (p = 0, k = j + 1; k < j1; k++)if (*(*(str + k) + i) != '0')p++;if ((p == 0 && *(*(str + j1) + i1) != '0')|| (p == 1 && *(*(str + j1) + i1) == '0')){printf("有子挡\n重新输入下的位置:");goto label;}else{if (p > 1){printf("隔子太多\n重新输入下的位置:");goto label;}elsegoto la;}}else{for (p = 0, k = j1 + 1; k < j; k++)if (*(*(str + k) + i) != '0')p++;if ((p == 0 && *(*(str + j1) + i1) != '0')|| (p == 1 && *(*(str + j1) + i1) == '0')){printf("有子挡\n重新输入下的位置:");goto label;}else{if (p > 1){printf("隔子太多\n重新输入下的位置:");goto label;}elsegoto la;}}}else{if (i1 > i){for (p = 0, k = i + 1; k < i1; k++)if (*(*(str + k) + i) != '0')p++;if ((p == 0 && *(*(str + j1) + i1) != '0')|| (p == 1 && *(*(str + j1) + i1) == '0')){printf("有子挡\n重新输入下的位置:");goto label;}else{if (p > 1){printf("隔子太多\n重新输入下的位置:");goto label;}elsegoto la;}}else{for (p = 0, k = i1 + 1; k < i; k++)if (*(*(str + k) + i) != '0')p++;if ((p == 0 && *(*(str + j1) + i1) != '0')|| (p == 1 && *(*(str + j1) + i1) == '0')){printf("有子挡\n重新输入下的位置:");goto label;}else{if (p > 1){printf("隔子太多\n重新输入下的位置:");goto label;}elsegoto la;}}}}}/*包的情况*/ /*兵的情况*/if (x == 'g'){if (i1 > i){printf("'兵'不能后退\n重新输入下的位置:");goto label;}if (i1 == i && i1 > 5){printf("'兵'没过河不能横着走\n重新输入下的位置:");goto label;}else{if (i1 == i && (j1 == j + 1 || j1 == j - 1))goto la;else{if (j1 == j && i1 == i - 1)goto la;else{printf("'兵'一次只走一格\n重新输入下的位置:");goto label;}}}}/*兵的情况*/ /*卒的情况*/ if (x == 'G'){if (i1 < i){printf("'卒'不能后退\n重新输入下的位置:");goto label;}if (i1 == i && i1 < 5){printf("'卒'没过河不能横着走\n重新输入下的位置:");goto label;}else{if (i1 == i && (j1 == j + 1 || j1 == j - 1))goto la;else{if (j1 == j && i1 == i + 1)goto la;else{printf("'卒'一次只走一格\n重新输入下的位置:");goto label;}}}}/*卒的情况*/ la:*(*(str + j1) + i1) = x;*(*(str + j) + i) = '0';printf("\n");for (m = 0; m < 10; m++){for (n = 0; n < 9; n++){o = *(*(str + n) + m);f(o);}printf("\n\n");}}}}int main(){int i0, j0, k0, m, n, m1, n1, p1, p3, ww;char **str, **str2;char x0, str1[10];str = (char **)malloc(1600);for (i0 = 0; i0 < 11; i0++)*(str + i0) = (char *)malloc(40);str2 = (char **)malloc(144);for (i0 = 0; i0 < 4; i0++)*(str2 + i0) = (char *)malloc(12);ww1:printf("\n欢迎游戏!\n 中国象棋\n\n");printf("请选择游戏模式:\n1.双人大战!\n2.九宫象棋!\n请输入编号:");scanf("%d", &ww);if (ww != 1 && ww != 2){printf("请按要求输入!\n");goto ww1;}if (ww == 2){printf("\n游戏规则:\n攻(红)方先动棋子不可出九宫格,在步步将军的情况下最终吃将获胜!\n""守(黑)方一直逃,直到对方无法将死便获胜!\n""攻(红)方只有車,馬二子,走法同象棋\n\n");lma1:printf("\n");for (i0 = 0; i0 < 3; i0++){for (j0 = 0; j0 < 3; j0++)*(*(str2 + j0) + i0) = '0';}**str2 = 'a';**(str2 + 2) = 'b';*(*(str2 + 1) + 1) = 'E';*(*(str2) + 2) = 'b';*(*(str2 + 2) + 2) = 'a';for (i0 = 0; i0 < 3; i0++){for (j0 = 0; j0 < 3; j0++){x0 = *(*(str2 + j0) + i0);f(x0);}printf("\n\n");}ii = 1, jj = 1;}else{printf("\n游戏简介:本游戏与现实中象棋规则相同!为方便游戏运行,棋子将用字母替代\n\n""红方:车(a) 马(b) 相(c) 士(d) 帅(e) 包(f) 兵(g)\n""黑方:車(A) 馬(B) 象(C) 仕(D) 将(E) 炮(F) 卒(G)\n\n");lma:printf("\n");for (i0 = 0; i0 < 10; i0++)for (j0 = 0; j0 < 9; j0++)*(*(str + j0) + i0) = '0';**str = 'A';**(str + 1) = 'B';**(str + 2) = 'C';**(str + 3) = 'D';**(str + 4) = 'E';*(*(str + 1) + 2) = 'F';*(*(str) + 3) = 'G';*(*(str + 2) + 3) = 'G';*(*(str + 4) + 3) = 'G';*(*(str) + 6) = 'g';*(*(str + 2) + 6) = 'g';*(*(str + 4) + 6) = 'g';*(*(str + 1) + 7) = 'f';*(*(str) + 9) = 'a';*(*(str + 1) + 9) = 'b';*(*(str + 2) + 9) = 'c';*(*(str + 3) + 9) = 'd';*(*(str + 4) + 9) = 'e';for (i0 = 0; i0 < 10; i0++){for (j0 = 5; j0 < 9; j0++)*(*(str + j0) + i0) = *(*(str + 8 - j0) + i0);}for (i0 = 0; i0 < 10; i0++){for (j0 = 0; j0 < 9; j0++){x0 = *(*(str + j0) + i0);f(x0);}printf("\n\n");}}printf("Ready Go?(输入“start”开始):");scanf("%s", str1);for (;;){if (str1[0] == 's' && str1[1] == 't' && str1[2] == 'a' && str1[3] == 'r' && str1[4] == 't'&& str1[5] == '\0')break;elseprintf("请正确输入!{Not ready?)\n再次输入:");scanf("%s", str1);}printf("\n红子先动!\n\n是否开启悔棋功能\n""征求双方意见,同意输入1,反对输入0(将关闭悔棋功能)\n");l11:printf("红方意见:");scanf("%d", &m1);if (m1 != 0 && m1 != 1){printf("请按要求输入!\n");goto l11;}l12:printf("黑方意见:");scanf("%d", &n1);if (n1 != 0 && n1 != 1){printf("请按要求输入!\n");goto l12;}p3 = m1 * n1;for (m = 1;; m++){l3:m = m % 2;if (ww == 1)f1(str, m);elsef2(str2, m);if (p3 != 0){printf("是否悔棋\n征求双方意见,同意输入1,反对输入0,关闭悔棋功能输入2\n");l1:printf("红方意见:");scanf("%d", &m1);if (m1 != 0 && m1 != 1 && m1 != 2){printf("请按要求输入!\n");goto l1;}l2:printf("黑方意见:");scanf("%d", &n1);if (n1 != 0 && n1 != 1 && n1 != 2){printf("请按要求输入!\n");goto l2;}p1 = m1 * n1;if (p1 == 1 && m1 != 2 && n1 != 2){if (ww == 1){*(*(str + j) + i) = x;*(*(str + j1) + i1) = y;}else{*(*(str2 + j) + i) = x;*(*(str2 + j1) + i1) = y;}printf("\n");if (ww == 1){for (i0 = 0; i0 < 10; i0++){for (j0 = 0; j0 < 9; j0++){x0 = *(*(str + j0) + i0);f(x0);}printf("\n\n");}}else{for (i0 = 0; i0 < 3; i0++){for (j0 = 0; j0 < 3; j0++){x0 = *(*(str2 + j0) + i0);f(x0);}printf("\n\n");}}goto l3;}if (m1 == 2 || n1 == 2)p3 = 0;}if (ww == 1){if (y == 'E'){printf("红方胜\n");break;}if (y == 'e'){printf("黑方胜\n");break;}}else{if (y == 'E'){printf("攻(红)方胜\n");break;}}}ljl:printf("是否再来一局?是(Yes),否(No),返回主菜单(Return):");scanf("%s", str1);if (str1[0] == 'Y' && str1[1] == 'e' && str1[2] == 's' && str1[3] == '\0') {if (ww == 1)goto lma;if (ww == 2)goto lma1;}else{if (str1[0] == 'N' && str1[1] == 'o' && str1[2] == '\0')printf("Game Over!\n");else{if (str1[0] == 'R' && str1[1] == 'e' && str1[2] == 't' && str1[3] == 'u' && str1[4] == 'r' && str1[5] == 'n' && str1[6] == '\0')goto ww1;else{printf("请按要求输入!\n");goto ljl;}}}for (i0 = 0; i0 < 10; i0++)free(*(str + i0));free(str);for (i0 = 0; i0 < 3; i0++)free(*(str2 + i0));free(str2);system("PAUSE");return 0;}。
C语言知识学习程序源代码-中国象棋
#include<graphics.h> #include<conio.h>#include<string.h>#include<bios.h>#include<stdlib.h>#include"c:\tc\LIB\1.c"#define W 119#define S 115#define A 97#define D 100#define space 32#define UP 72#define DOWN 80#define LEFT 75#define RIGHT 77#define ENTER 13void qipan();void jiemian(int);void guangbiao1(int,int); void guangbiao2(int,int);void xuanzhong(int,int);void gaizi(int,int);char array(int,int);void xiazi(int,int,int,int);/*int panding(char,int,int,int,int);*/main(){int gdriver,gmode,i=0,c=0,x=190,y=190,m,n; char p;FILE *fp;gdriver=DETECT;gmode=0;if((fp=fopen("file.txt","at")) == NULL) {printf("Cannot open file!");system("pause");exit(0);}printf("%d,%d",gdriver,gmode); registerbgidriver(EGAVGA_driver);initgraph(&gdriver,&gmode,"c:\\tc"); cleardevice();while(c!=27){c=getch();clrscr();jiemian(i);if(c==80){fputs("down ",fp);i++;if(i==4){i=0;}}if(i==1){if(c==13){fputs("enter ",fp);qipan();c=getch();while(c!=27){c=getch();if(c==115){fputs("S ",fp);y=y+40; guangbiao1(x,y); guangbiao2(x,y-40);}if(c==119){fputs("W ",fp);y=y-40;guangbiao1(x,y);guangbiao2(x,y+40); }if(c==97){ fputs("A\n",fp);x=x-40;guangbiao1(x,y);guangbiao2(x+40,y); }if(c==100){ fputs("D\n",fp);x=x+40;guangbiao1(x,y);guangbiao2(x-40,y); }if(c==13){fputs("enter\n",fp);xuanzhong(x,y);m=x;n=y;}if(c==32){fputs("space\n",fp);xiazi(m,n,x,y);fputs("gaizi\n",fp);gaizi(m,n);}if(x>350||y>390||x<30||y<30){x=190;y=30;}}}}}getch();closegraph();fclose(fp);restorecrtmode();return 0;}void qipan(){int i,j;setbkcolor(GREEN);cleardevice();setlinestyle(0,0,3);setcolor(1);rectangle(10,10,370,410); rectangle(30,30,350,390);for(i=1;i<8;i++){setlinestyle(0,0,3);line(i*40+30,30,i*40+30,190); line(i*40+30,230,i*40+30,390); }for(j=1;j<9;j++){setlinestyle(0,0,3);line(30,j*40+30,350,j*40+30); }setlinestyle(3,0,3);line(150,30,230,110);line(230,30,150,110);line(150,310,230,390);line(230,310,150,390); setusercharsize(4,1,2,1);settextstyle(1,0,4);outtextxy(70,195,"chinese chess"); red_shuai(190,30);red_shi(150,30);red_shi(230,30);red_xiang(110,30);red_xiang(270,30);red_ma(70,30);red_ma(310,30);red_ju(30,30);red_ju(350,30);red_pao(70,110);red_pao(310,110);red_bing(30,150);red_bing(110,150);red_bing(190,150);red_bing(270,150);red_bing(350,150);black_jiang(190,390);black_shi(150,390);black_shi(230,390);black_xiang(110,390);black_xiang(270,390);black_ma(70,390);black_ma(310,390);black_ju(30,390);black_ju(350,390);black_pao(70,310);black_pao(310,310);black_zu(30,270);black_zu(110,270);black_zu(190,270);black_zu(270,270);black_zu(350,270);setcolor(BLUE);rectangle(400,30,600,320);setcolor(4);settextstyle(1,0,2);outtextxy(420,50,"A->shuai B->shi"); outtextxy(420,80,"C->xiang D->ma"); outtextxy(420,110,"E->ju F->pao"); outtextxy(420,140,"G->bing"); setcolor(8);outtextxy(420,200,"H->jiang I->shi");outtextxy(420,230,"J->xiang K->ma"); outtextxy(420,260,"L->ju M->pao"); outtextxy(420,290,"N->zu");}void jiemian(int i){setbkcolor(GREEN);cleardevice();settextstyle(1,0,8);setcolor(BLUE);outtextxy(50,70,"chinese chess"); settextstyle(0,0,3);setcolor(RED);outtextxy(260,215,"start");outtextxy(260,255,"again"); outtextxy(260,295,"undo"); outtextxy(260,335,"exit");rectangle(250,210+i*40,390,240+i*40); }void guangbiao1(int x,int y){setcolor(WHITE); setlinestyle(0,0,3);line(x-17,y-7,x-17,y-17); line(x-7,y-17,x-17,y-17); line(x+7,y-17,x+17,y-17); line(x+17,y-7,x+17,y-17); line(x-7,y+17,x-17,y+17); line(x-17,y+7,x-17,y+17); line(x+17,y+7,x+17,y+17); line(x+7,y+17,x+17,y+17); }void guangbiao2(int x,int y) {setcolor(GREEN); setlinestyle(0,0,3);line(x-17,y-7,x-17,y-17); line(x-7,y-17,x-17,y-17); line(x+7,y-17,x+17,y-17); line(x+17,y-7,x+17,y-17); line(x-7,y+17,x-17,y+17); line(x-17,y+7,x-17,y+17); line(x+17,y+7,x+17,y+17);line(x+7,y+17,x+17,y+17);}void xuanzhong(int x,int y){setcolor(CYAN);setlinestyle(0,0,3);circle(x,y,15);}void gaizi(int x1,int y1){setlinestyle(0,0,3);setcolor(GREEN);circle(x1,y1,15);setfillstyle(0,3);floodfill(x1,y1,GREEN);setcolor(1);setlinestyle(0,0,3);if((30<x1<350)&&((y1==30)||(y1==230))) {line(x1-18,y1,x1+18,y1);line(x1,y1,x1,y1+18);}if((30<x1<350)&&(y1==390||y1==190)) {line(x1-18,y1,x1+18,y1);line(x1,y1-18,x1,y1);}if((30<y1<390)&&x1==30){line(x1,y1,x1+18,y1);line(x1,y1-18,x1,y1+18);}if((30<y1<390)&&(x1==350)){line(x1-18,y1,x1,y1);line(x1,y1-18,x1,y1+18);}if((x1==30)&&(y1==30)){line(x1,y1,x1+18,y1);line(x1,y1,x1,y1+18);}if((x1==350)&&(y1==30)) {line(x1-18,y1,x1,y1);line(x1,y1,x1,y1+18);}if((x1==30)&&(y1==390)) {line(x1,y1,x1+18,y1);line(x1,y1,x1,y1-18);}if((x1==350)&&(y1==390)) {line(x1,y1,x1-18,y1);line(x1,y1,x1,y1-18);}else{line(x1-18,y1,x1+18,y1); line(x1,y1-18,x1,y1+18); }}char array(int i,int j)char a[13][13];int c,b;c=i;b=j;for(c=1;c<10;c++){for(b=1;b<11;b++){a[c][b]='Z';}}a[1][5]='A';a[1][4]='B';a[1][6]='B';a[1][3]='C';a[1][7]='C';a[1][2]='D';a[1][8]='D';a[1][1 ]='E';a[1][9]='E';a[3][2]='F';a[3][8]='F';a[4][1]=a[4][3]=a[4][5]=a[4][7]=a[4][9]='G';a[10][5]='H';a[10][4]='I';a[10][6]='I';a[10][3]='J';a[10][7]='J';a[10][2]='K';a[10][8]='K'; a[10][1]='L';a[10][9]='L';a[2][3]='M';a[8][3]='M';a[7][1]=a[7][3]=a[7][5]=a[7][7]=a[7][9]='N';return a[i][j];void xiazi(int x6,int y6,int x7,int y7) {switch(array(y6/40+1,x6/40+1)) {case 'A':red_shuai(x7,y7);break;case 'B':red_shi(x6,y7);break;case 'C':red_xiang(x7,y7);break;case 'D':red_ma(x7,y7);break;case 'E':red_ju(x7,y7);break;case 'F':red_pao(x7,y7);break;case 'G':red_bing(x7,y7);break;case 'H':black_jiang(x7,y7);break;case 'I':black_shi(x7,y7);break;case 'J':black_xiang(x7,y7);break;case 'K':black_ma(x7,y7);break;case 'L':black_ju(x7,y7);break;case 'M':black_pao(x7,y7);break;case 'N':black_zu(x7,y7);break;case 'Z':gaizi(x6,x6);break;}}/*int panding(char q,int x,int y,int a,int b) {switch(q){case 'A':if(y>110||x>230||x<150||(a-x)>40||(x-a)>40||(y-b)>40||(b-y)>40)return 0;elsereturn 1;break;case'B':if(((x-a)==40&&(y-b)==40)&&y<=110&&230<x<150||((a-x)==40&&(b-y)==4 0)&&y<=110&&230>x>150)return 1;elsereturn 0;break;case'C':if((((x-a)==80&&(y-b)==80)&&y<=190)&&(array((y+b)/2/40+1,(x+a)/2/40+1,) =='Z')))||(((a-x)==80&&(b-y)==80)&&y<=190)&&(array((y+b)/2/40+1,(x+a)/2/40 +1)=='Z'))))return 1;elsereturn 0;break;case'D':if((((x-a)==80&&(y-b)==40&&(array(y/40+1,(x-40)/40+1)=='Z'))||(((a-x)==80& &(b-y)==40)&&(array(y/40+1,(x+40)/40+1)=='Z'))||(((x-a)==40&&(y-b)==80)(arra y((y-40)/40+1,x/40+1)=='Z'))||(((a-x)==40&&(b-y)==80)&&(array((y+40)/40+1,x/4 0+1)=='z'))))return 1;elsereturn 0;break;case 'E':return 1;break;case 'F':return 1;break;case 'G':if(y<190){if(y>b||x!=a){return 0;}elsereturn 1;}else{if((b-y)>40||(a-x)>40||(x-a)>40||y>b){return 0;}elsereturn 1;}break;case 'H':if(y<310||x>230||x<150||(a-x)>40||(x-a)>40||(y-b)>40||(b-y)>40) return 0;elsereturn 1;break;case'I':if(((x-a)==40&&(y-b)==40)&&y>=310&&230<x<150||((a-x)==40&&(b-y)==40 )&&y>310&&230>x>150)return 1;elsebreak;case'J':if(((((x-a)==80&&(y-b)==80)&&y>=230)&&array(((y+b)/2/40+1,(x+a)/2/40+1) =='Z')))||(((a-x)==80&&(b-y)==80)&&y>=230)&&(array((y+b)/2/40+1,(x+a)/2/40 +1)=='Z'))))return 1;elsereturn 0;break;case'K':if((((x-a)==80&&(y-b)==40&&(array(y/40+1,(x-40)/40+1)=='Z'))||(((a-x)==80& &(b-y)==40)&&(array(y/40+1,(x+40)/40+1)=='Z'))||(((x-a)==40&&(y-b)==80)(arra y((y-40)/40+1,x/40+1)=='Z'))||(((a-x)==40&&(b-y)==80)&&(array((y+40)/40+1,x/4 0+1)=='Z'))return 1;elsereturn 0;break;case 'L':return 1;break;break;case 'N':if(y>230){if(y<b||x!=a){return 0;}elsereturn 1;}else{if(y-b>40||(a-x)>40||(x-a)>40||y<b){return 0;}elsereturn 1;}default:return 0;}}*/。
中国象棋C语言源代码
*--------------------chess.c----------------------*/ #include "dos.h"#include "stdio.h"/*----------------------------------------------------*/ #define RED 7#define BLACK 14#define true 1#define false 0#define SELECT 0#define MOVE 1#define RED_UP 0x1100#define RED_DOWN 0x1f00#define RED_LEFT 0x1e00#define RED_RIGHT 0x2000#define RED_DO 0x3900#define RED_UNDO 0x1000#define BLACK_UP 0x4800#define BLACK_DOWN 0x5000#define BLACK_LEFT 0x4b00#define BLACK_RIGHT 0x4d00#define BLACK_DO 0x1c00#define BLACK_UNDO 0x2b00#define ESCAPE 0x0100#define RED_JU 1#define RED_MA 2#define RED_XIANG 3#define RED_SHI 4#define RED_JIANG 5#define RED_PAO 6#define RED_BIN 7#define BLACK_JU 8#define BLACK_MA 9#define BLACK_XIANG 10#define BLACK_SHI 11#define BLACK_JIANG 12#define BLACK_PAO 13#define BLACK_BIN 14/*----------------------------------------------------*/ int firsttime=1;int savemode;char page_new=0,page_old=0;int finish=false,turn=BLACK,winner=0;int key;int redstate=SELECT,blackstate=SELECT;int board[10][9];/*----------------------------------------------------*/char *chessfile[15]={"","bmp\\rju.wfb", "bmp\\rma.wfb", "bmp\\rxiang.wfb","bmp\\rshi.wfb","bmp\\rjiang.wfb","bmp\\rpao.wfb","bmp\\rbin.wfb","bmp\\bju.wfb", "bmp\\bma.wfb", "bmp\\bxiang.wfb","bmp\\bshi.wfb","bmp\\bjiang.wfb","bmp\\bpao.wfb","bmp\\bbin.wfb"};char *boardfile[10][9]={{"bmp\\11.wfb","bmp\\1t.wfb","bmp\\1t.wfb","bmp\\14.wfb","bmp\\15.wfb","bmp\\16.wfb"," bmp\\1t.wfb","bmp\\1t.wfb","bmp\\19.wfb"},{"bmp\\21.wfb","bmp\\2c.wfb","bmp\\2c.wfb","bmp\\24.wfb","bmp\\25.wfb","bmp\\26.wfb"," bmp\\2c.wfb","bmp\\2c.wfb","bmp\\29.wfb"},{"bmp\\21.wfb","bmp\\3a.wfb","bmp\\3t.wfb","bmp\\34.wfb","bmp\\3t.wfb","bmp\\36.wfb"," bmp\\3t.wfb","bmp\\3a.wfb","bmp\\29.wfb"},{"bmp\\41.wfb","bmp\\4t.wfb","bmp\\4a.wfb","bmp\\4t.wfb","bmp\\4a.wfb","bmp\\4t.wfb","b mp\\4a.wfb","bmp\\4t.wfb","bmp\\49.wfb"},{"bmp\\51.wfb","bmp\\52.wfb","bmp\\5t.wfb","bmp\\54.wfb","bmp\\5t.wfb","bmp\\56.wfb"," bmp\\5t.wfb","bmp\\58.wfb","bmp\\59.wfb"},{"bmp\\61.wfb","bmp\\62.wfb","bmp\\6t.wfb","bmp\\64.wfb","bmp\\6t.wfb","bmp\\66.wfb"," bmp\\6t.wfb","bmp\\68.wfb","bmp\\69.wfb"},{"bmp\\71.wfb","bmp\\7t.wfb","bmp\\7a.wfb","bmp\\7t.wfb","bmp\\7a.wfb","bmp\\7t.wfb","b mp\\7a.wfb","bmp\\7t.wfb","bmp\\79.wfb"},{"bmp\\81.wfb","bmp\\8a.wfb","bmp\\8t.wfb","bmp\\84.wfb","bmp\\85.wfb","bmp\\86.wfb"," bmp\\8t.wfb","bmp\\8a.wfb","bmp\\89.wfb"},{"bmp\\91.wfb","bmp\\9t.wfb","bmp\\9t.wfb","bmp\\9t.wfb","bmp\\95.wfb","bmp\\9t.wfb","b mp\\9t.wfb","bmp\\9t.wfb","bmp\\99.wfb"},{"bmp\\101.wfb","bmp\\102.wfb","bmp\\102.wfb","bmp\\104.wfb","bmp\\105.wfb","bmp\\10 6.wfb","bmp\\108.wfb","bmp\\108.wfb","bmp\\109.wfb"}};char cursor[14][14]={0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,255,255,255,255,255,255,255,0,0,1,1,1,1,0,255,255,255,255,255,255,0,0,1,1,1,1,1,0,255,255,255,255,255,255,0,0,1,1,1,1,1,0,255,255,255,255,255,255,255,0,0,1,1,1,1,0,255,255,255,255,255,255,255,255,0,0,1,1,1,0,255,255,255,255,255,255,255,255,255,0,0,1,1,0,255,255,0,255,255,255,255,255,255,255,0,0,1,0,255,0,1,1,0,255,255,255,255,255,255,255,0,0,0,1,1,1,1,0,255,255,255,255,255,0,1,0,1,1,1,1,1,1,0,255,255,255,0,1,1,1,1,1,1,1,1,1,1,0,255,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1};struct pos{int x;int y;}position[10][9],redcurpos,redtemppos,redoldpos,blackcurpos,blacktemppos,blackoldpos; /*----------------------------------------------------*/selectpage(register char page) /*换页函数*/{union REGS r;r.x.ax=0x4f05;r.x.bx=0;r.x.dx=page; /*选择页面*/int86(0x10,&r,&r);}unsigned char set_SVGA_mode(int vmode) /*设置SVGA屏幕模式*/{union REGS r;r.x.ax=0x4f02;r.x.bx=vmode;int86(0x10,&r,&r);return(r.h.ah);}unsigned int get_SVGA_mode() /*获取当前SVGA屏幕模式*/{union REGS r;r.x.ax=0x4f03;int86(0x10,&r,&r);return(r.x.bx);}drawbmp(int start_x,int start_y,char filename[]){char buffer[640];int i,j,k,n,r,g,b,width,length;long position;FILE *fp;if((fp=fopen(filename,"rb"))==NULL){printf("Error! Can't open file!");getch();return;}fseek(fp,28,SEEK_SET);fread(&i,2,1,fp);if(i!=8) /*检查是否为256色位图*/{puts("Error!Can't find bitmap!");fclose(fp);getch();exit(0);}fseek(fp,18,SEEK_SET);fread(&width,4,1,fp);fread(&length,4,1,fp);if(firsttime){fseek(fp,54,SEEK_SET);for(i=0;i<256;i++) /*按照该图片的DAC色表设置色彩寄存器*/{b=fgetc(fp);g=fgetc(fp);r=fgetc(fp); /*获取R、G、B分量*/outportb(0x3c8,i);outportb(0x3c9,r>>2); /*右移是要转化为VGA的6位寄存器形式*/ outportb(0x3c9,g>>2);outportb(0x3c9,b>>2);fgetc(fp);}}elsefseek(fp,300,SEEK_SET);k=(width%4)?(4-width%4):0; /*宽度修正值*/for(j=length-1+start_x;j>=start_x;j--){fread(buffer,width,1,fp);for(i=start_y,n=0;i<width+start_y;i++,n++){position=j*640l+i; /*计算要显示点的显存位置*/page_new=position/65536; /*计算显示页*/if(page_new!=page_old) /*当显示页不同时更换页面,提高一定的输出速度*/{selectpage(page_new);page_old=page_new;}pokeb(0xa000,position%65536,buffer[n]); /*写到显存位置*/}fseek(fp,k,SEEK_CUR); /*每行绘制完后修正宽度*/}fclose(fp);}init(){savemode=get_SVGA_mode(); /*先保存原来的屏幕模式*/set_SVGA_mode(0x101); /*硬件无关性初始化屏幕为640*480 256色模式*/ }end(){set_SVGA_mode(savemode); /*恢复屏幕*/}/*----------------------------------------------------*/initpos(){int i,j;for(i=0;i<10;i++)for (j=0;j<9;j++){position[i][j].x=35+i*39;position[i][j].y=43+j*40;}}initchessmap(){board[0][0]=BLACK_JU;board[0][1]=BLACK_MA;board[0][2]=BLACK_XIANG;board[0][3]=BLACK_SHI;board[0][4]=BLACK_JIANG;board[0][5]=BLACK_SHI;board[0][6]=BLACK_XIANG;board[0][7]=BLACK_MA;board[0][8]=BLACK_JU;board[2][1]=BLACK_PAO;board[2][7]=BLACK_PAO;board[3][0]=BLACK_BIN;board[3][2]=BLACK_BIN;board[3][4]=BLACK_BIN;board[3][6]=BLACK_BIN;board[3][8]=BLACK_BIN;board[9][0]=RED_JU;board[9][1]=RED_MA;board[9][2]=RED_XIANG;board[9][3]=RED_SHI;board[9][4]=RED_JIANG;board[9][5]=RED_SHI;board[9][6]=RED_XIANG;board[9][7]=RED_MA;board[9][8]=RED_JU;board[7][1]=RED_PAO;board[7][7]=RED_PAO;board[6][0]=RED_BIN;board[6][2]=RED_BIN;board[6][4]=RED_BIN;board[6][6]=RED_BIN;board[6][8]=RED_BIN;}initdrawchess(){int i,j;;for(i=0;i<10;i++)for(j=0;j<9;j++){if(board[i][j])drawbmp(position[i][j].x,position[i][j].y,chessfile[board[i][j]]); }}drawcursor(struct pos p){int i,j,n,m,x,y;long thisposition;x=position[p.x][p.y].x+20;y=position[p.x][p.y].y+25;for(j=13-1+x,m=13;j>=x;j--,m--){for(i=y,n=0;i<13+y;i++,n++){thisposition=j*640l+i; /*计算要显示点的显存位置*/page_new=thisposition/65536; /*计算显示页*/if(page_new!=page_old) /*当显示页不同时更换页面,提高一定的输出速度*/ {selectpage(page_new);page_old=page_new;}if(cursor[m][n]!=1)if(cursor[m][n]==0)pokeb(0xa000,thisposition%65536,0);elseif(turn==RED)pokeb(0xa000,thisposition%65536,153);elsepokeb(0xa000,thisposition%65536,255);}}}drawselecursor(struct pos p){int i,j,n,m,x,y;long thisposition;x=position[p.x][p.y].x+20;y=position[p.x][p.y].y+25;for(j=13-1+x,m=13;j>=x;j--,m--){for(i=y,n=0;i<13+y;i++,n++){thisposition=j*640l+i; /*计算要显示点的显存位置*/page_new=thisposition/65536; /*计算显示页*/if(page_new!=page_old) /*当显示页不同时更换页面,提高一定的输出速度*/ {selectpage(page_new);page_old=page_new;}if(cursor[m][n]!=1)pokeb(0xa000,thisposition%65536,0);}}}/*----------------------------------------------------*/int getkey(){int press;while(bioskey(1) == 0);press=bioskey(0);press=press&0xff00;return(press);}/*--------------------红方操作--------------------*/int redcanselect(){int x,y;x=redcurpos.x;y=redcurpos.y;if(board[x][y]>=RED_JU&&board[x][y]<=RED_BIN)return 1;elsereturn 0;}int redcanmove(){int i,j,min,max,oldx,oldy,x,y;oldx=redoldpos.x;oldy=redoldpos.y;x=redcurpos.x;y=redcurpos.y;/*case1 目标位置是否是自己人*/if(board[x][y]>=RED_JU&&board[x][y]<=RED_BIN)return 0;/* 军、马、炮、相、士、将、卒的走法正确性的判断*/ switch(board[oldx][oldy]){case RED_BIN: /*完成*/if(oldx>=5){ if(y!=oldy||(oldx-x)!=1) return 0;}else{ if(x==(oldx-1)&&y==oldy) return 1;elseif(x==oldx&&y==(oldy+1)) return 1;elseif(x==oldx&&y==(oldy-1)) return 1;elsereturn 0;}break;case RED_JIANG: /*完成*/if(x!=oldx&&y!=oldy) return 0;if(x!=oldx)if((x-oldx)>1||(oldx-x)>1) return 0;else if(x<7) return 0;else if(y!=oldy)if((y-oldy)>1||(oldy-y)>1) return 0;else if(y<3||y>5) return 0;break;case RED_JU: /*完成*/if(x!=oldx&&y!=oldy) return 0;else if(x!=oldx){ min=(x>oldx)?oldx:x;max=(x>oldx)?x:oldx;for(i=min+1;i<max;i++)if(board[i][y]!=0) return 0;}else if(y!=oldy){ min=(y>oldy)?oldy:y;max=(y>oldy)?y:oldy;for(i=min+1;i<max;i++)if(board[x][i]!=0) return 0;}break;case RED_MA: /*完成*/if((x-oldx)==2&&((y-oldy)==1||(oldy-y)==1)) {if(board[oldx+1][oldy]!=0) return 0;}elseif((oldx-x)==2&&((y-oldy)==1||(oldy-y)==1)) {if(board[oldx-1][oldy]!=0) return 0;}elseif((y-oldy)==2&&((x-oldx)==1||(oldx-x)==1)) {if(board[oldx][oldy+1]!=0) return 0;}elseif((oldy-y)==2&&((x-oldx)==1||(oldx-x)==1)) {if(board[oldx][oldy-1]!=0) return 0;}elsereturn 0;break;case RED_PAO: /*完成*/if(x!=oldx&&y!=oldy) return 0;if(board[x][y]==0){if(x!=oldx){ min=(x>oldx)?oldx:x;max=(x>oldx)?x:oldx;for(i=min+1;i<max;i++)if(board[i][y]!=0) return 0; }else if(y!=oldy){ min=(y>oldy)?oldy:y; max=(y>oldy)?y:oldy;for(i=min+1;i<max;i++)if(board[x][i]!=0) return 0; }}else{if(x!=oldx){ min=(x>oldx)?oldx:x; max=(x>oldx)?x:oldx;for(i=min+1,j=0;i<max;i++) if(board[i][y]!=0) j++;if(j!=1) return 0;}else if(y!=oldy){ min=(y>oldy)?oldy:y; max=(y>oldy)?y:oldy;for(i=min+1,j=0;i<max;i++) if(board[x][i]!=0) j++;if(j!=1) return 0;}}break;case RED_SHI: /*完成*/if(oldx==9||oldx==7){if(x!=8||y!=4) return 0;} else if(oldx==8){if(x==9&&y==3) return 1; elseif(x==9&&y==5) return 1; elseif(x==7&&y==3) return 1; elseif(x==7&&y==5) return 1; else return 0;}else return 0;break;case RED_XIANG: /*完成*/ if(x<5) return 0;if(x!=oldx&&y!=oldy){if((x-oldx)==2&&(y-oldy)==2){i=oldx+1;j=oldy+1;}else if((x-oldx)==2&&(oldy-y)==2) {i=oldx+1;j=oldy-1;}else if((oldx-x)==2&&(y-oldy)==2) {i=oldx-1;j=oldy+1;}else if((oldx-x)==2&&(oldy-y)==2) {i=oldx-1;j=oldy-1;}else return 0;if(board[i][j]!=0) return 0;}else return 0;break;}return 1;}。
C语言程序源代码---中国象棋
#include<graphics.h>#include<conio.h>#include<string.h>#include<bios.h>#include<stdlib.h>#include"c:\tc\LIB\1.c"#define W 119#define S 115#define A 97#define D 100#define space 32#define UP 72#define DOWN 80#define LEFT 75#define RIGHT 77#define ENTER 13void qipan();void jiemian(int);void guangbiao1(int,int);void guangbiao2(int,int);void xuanzhong(int,int);void gaizi(int,int);char array(int,int);void xiazi(int,int,int,int);/*int panding(char,int,int,int,int);*/main(){int gdriver,gmode,i=0,c=0,x=190,y=190,m,n; char p;FILE *fp;gdriver=DETECT;gmode=0;if((fp=fopen("file.txt","at")) == NULL) {printf("Cannot open file!");system("pause");exit(0);}printf("%d,%d",gdriver,gmode); registerbgidriver(EGAVGA_driver);initgraph(&gdriver,&gmode,"c:\\tc"); cleardevice();while(c!=27){c=getch();clrscr();jiemian(i);if(c==80){fputs("down ",fp);i++;if(i==4){i=0;}}if(i==1){if(c==13){fputs("enter ",fp);qipan();c=getch();while(c!=27){c=getch();if(c==115){fputs("S ",fp);y=y+40;guangbiao1(x,y);guangbiao2(x,y-40);}if(c==119){fputs("W ",fp);y=y-40;guangbiao1(x,y);guangbiao2(x,y+40);}if(c==97){ fputs("A\n",fp);x=x-40;guangbiao1(x,y);guangbiao2(x+40,y);}if(c==100){ fputs("D\n",fp);x=x+40;guangbiao1(x,y);guangbiao2(x-40,y);}if(c==13){fputs("enter\n",fp);xuanzhong(x,y);m=x;n=y;}if(c==32){fputs("space\n",fp);xiazi(m,n,x,y);fputs("gaizi\n",fp);gaizi(m,n);}if(x>350||y>390||x<30||y<30){x=190;y=30;}}}}}getch();closegraph();fclose(fp);restorecrtmode();return 0;}void qipan(){int i,j;setbkcolor(GREEN);cleardevice();setlinestyle(0,0,3);setcolor(1);rectangle(10,10,370,410);rectangle(30,30,350,390);for(i=1;i<8;i++){setlinestyle(0,0,3);line(i*40+30,30,i*40+30,190);line(i*40+30,230,i*40+30,390);}for(j=1;j<9;j++){setlinestyle(0,0,3);line(30,j*40+30,350,j*40+30);}setlinestyle(3,0,3);line(150,30,230,110);line(230,30,150,110);line(150,310,230,390);line(230,310,150,390); setusercharsize(4,1,2,1); settextstyle(1,0,4);outtextxy(70,195,"chinese chess"); red_shuai(190,30);red_shi(150,30);red_shi(230,30);red_xiang(110,30);red_xiang(270,30);red_ma(70,30);red_ma(310,30);red_ju(30,30);red_ju(350,30);red_pao(70,110);red_pao(310,110);red_bing(30,150);red_bing(110,150);red_bing(190,150);red_bing(270,150);red_bing(350,150);black_jiang(190,390);black_shi(150,390);black_shi(230,390);black_xiang(110,390);black_xiang(270,390);black_ma(70,390);black_ma(310,390);black_ju(30,390);black_ju(350,390);black_pao(70,310);black_pao(310,310);black_zu(30,270);black_zu(110,270);black_zu(190,270);black_zu(270,270);black_zu(350,270);setcolor(BLUE);rectangle(400,30,600,320);setcolor(4);settextstyle(1,0,2);outtextxy(420,50,"A->shuai B->shi"); outtextxy(420,80,"C->xiang D->ma"); outtextxy(420,110,"E->ju F->pao"); outtextxy(420,140,"G->bing"); setcolor(8);outtextxy(420,200,"H->jiang I->shi"); outtextxy(420,230,"J->xiang K->ma"); outtextxy(420,260,"L->ju M->pao"); outtextxy(420,290,"N->zu");}void jiemian(int i){setbkcolor(GREEN); cleardevice();settextstyle(1,0,8);setcolor(BLUE);outtextxy(50,70,"chinese chess"); settextstyle(0,0,3);setcolor(RED);outtextxy(260,215,"start"); outtextxy(260,255,"again"); outtextxy(260,295,"undo"); outtextxy(260,335,"exit"); rectangle(250,210+i*40,390,240+i*40); }void guangbiao1(int x,int y){setcolor(WHITE);setlinestyle(0,0,3);line(x-17,y-7,x-17,y-17);line(x-7,y-17,x-17,y-17);line(x+7,y-17,x+17,y-17);line(x+17,y-7,x+17,y-17);line(x-7,y+17,x-17,y+17);line(x-17,y+7,x-17,y+17);line(x+17,y+7,x+17,y+17);line(x+7,y+17,x+17,y+17);}void guangbiao2(int x,int y){setcolor(GREEN);setlinestyle(0,0,3);line(x-17,y-7,x-17,y-17);line(x-7,y-17,x-17,y-17);line(x+7,y-17,x+17,y-17);line(x+17,y-7,x+17,y-17);line(x-7,y+17,x-17,y+17);line(x-17,y+7,x-17,y+17);line(x+17,y+7,x+17,y+17);line(x+7,y+17,x+17,y+17);}void xuanzhong(int x,int y){setcolor(CYAN);setlinestyle(0,0,3);circle(x,y,15);}void gaizi(int x1,int y1){setlinestyle(0,0,3);setcolor(GREEN);circle(x1,y1,15);setfillstyle(0,3);floodfill(x1,y1,GREEN);setcolor(1);setlinestyle(0,0,3);if((30<x1<350)&&((y1==30)||(y1==230))) {line(x1-18,y1,x1+18,y1);line(x1,y1,x1,y1+18);if((30<x1<350)&&(y1==390||y1==190)) {line(x1-18,y1,x1+18,y1);line(x1,y1-18,x1,y1);}if((30<y1<390)&&x1==30){line(x1,y1,x1+18,y1);line(x1,y1-18,x1,y1+18);}if((30<y1<390)&&(x1==350)){line(x1-18,y1,x1,y1);line(x1,y1-18,x1,y1+18);}if((x1==30)&&(y1==30)){line(x1,y1,x1+18,y1);line(x1,y1,x1,y1+18);}if((x1==350)&&(y1==30)){line(x1-18,y1,x1,y1);line(x1,y1,x1,y1+18);}if((x1==30)&&(y1==390)){line(x1,y1,x1+18,y1);line(x1,y1,x1,y1-18);}if((x1==350)&&(y1==390)){line(x1,y1,x1-18,y1);line(x1,y1,x1,y1-18);}else{line(x1-18,y1,x1+18,y1);line(x1,y1-18,x1,y1+18);}}char array(int i,int j)char a[13][13];int c,b;c=i;b=j;for(c=1;c<10;c++){for(b=1;b<11;b++){a[c][b]='Z';}}a[1][5]='A';a[1][4]='B';a[1][6]='B';a[1][3]='C';a[1][7]='C';a[1][2]='D';a[1][8]='D';a[1][1]='E';a[1][9]='E';a[3][2]='F';a[3][8]='F';a[4][1]=a[4][3]=a[4][5]=a[4][7]=a[4][9]='G';a[10][5]='H';a[10][4]='I';a[10][6]='I';a[10][3]='J';a[10][7]='J';a[10][2]='K';a[10][8]='K';a[10][1]='L';a[10][ 9]='L';a[2][3]='M';a[8][3]='M';a[7][1]=a[7][3]=a[7][5]=a[7][7]=a[7][9]='N';return a[i][j];}void xiazi(int x6,int y6,int x7,int y7){switch(array(y6/40+1,x6/40+1)){case 'A':red_shuai(x7,y7);break;case 'B':red_shi(x6,y7);break;case 'C':red_xiang(x7,y7);break;case 'D':red_ma(x7,y7);break;case 'E':red_ju(x7,y7);break;case 'F':red_pao(x7,y7);break;case 'G':red_bing(x7,y7);break;case 'H':black_jiang(x7,y7);break;case 'I':black_shi(x7,y7);break;case 'J':black_xiang(x7,y7);break;case 'K':black_ma(x7,y7);break;case 'L':black_ju(x7,y7);break;case 'M':black_pao(x7,y7);break;case 'N':black_zu(x7,y7);break;case 'Z':gaizi(x6,x6);break;}}/*int panding(char q,int x,int y,int a,int b){switch(q){case 'A':if(y>110||x>230||x<150||(a-x)>40||(x-a)>40||(y-b)>40||(b-y)>40)return 0;elsereturn 1;break;case'B':if(((x-a)==40&&(y-b)==40)&&y<=110&&230<x<150||((a-x)==40&&(b-y)==40)&&y<=110& &230>x>150)return 1;elsereturn 0;break;case'C':if((((x-a)==80&&(y-b)==80)&&y<=190)&&(array((y+b)/2/40+1,(x+a)/2/40+1,)=='Z')))||(((a-x)==80&&(b-y)==80)&&y<=190)&&(array((y+b)/2/40+1,(x+a)/2/40+1)=='Z'))))return 1;elsereturn 0;break;case'D':if((((x-a)==80&&(y-b)==40&&(array(y/40+1,(x-40)/40+1)=='Z'))||(((a-x)==80&&(b-y)==40)&&(array(y/40+1,(x+40)/40+1)=='Z'))||(((x-a)==40&&(y-b)==80)(array((y-40)/40+1,x/40+1)==' Z'))||(((a-x)==40&&(b-y)==80)&&(array((y+40)/40+1,x/40+1)=='z'))))return 1;elsereturn 0;break;case 'E':return 1;break;case 'F':return 1;break;case 'G':if(y<190){if(y>b||x!=a){return 0;}elsereturn 1;}else{if((b-y)>40||(a-x)>40||(x-a)>40||y>b){return 0;}elsereturn 1;}break;case 'H':if(y<310||x>230||x<150||(a-x)>40||(x-a)>40||(y-b)>40||(b-y)>40)return 0;elsereturn 1;break;case'I':if(((x-a)==40&&(y-b)==40)&&y>=310&&230<x<150||((a-x)==40&&(b-y)==40)&&y>310&& 230>x>150)return 1;elsereturn 0;break;case'J':if(((((x-a)==80&&(y-b)==80)&&y>=230)&&array(((y+b)/2/40+1,(x+a)/2/40+1)=='Z')))||(((a-x )==80&&(b-y)==80)&&y>=230)&&(array((y+b)/2/40+1,(x+a)/2/40+1)=='Z'))))return 1;elsereturn 0;break;case'K':if((((x-a)==80&&(y-b)==40&&(array(y/40+1,(x-40)/40+1)=='Z'))||(((a-x)==80&&(b-y)==40) &&(array(y/40+1,(x+40)/40+1)=='Z'))||(((x-a)==40&&(y-b)==80)(array((y-40)/40+1,x/40+1)==' Z'))||(((a-x)==40&&(b-y)==80)&&(array((y+40)/40+1,x/40+1)=='Z'))return 1;elsereturn 0;break;case 'L':return 1;break;case 'M':return 1;break;case 'N':if(y>230){if(y<b||x!=a){return 0;}elsereturn 1;}else{if(y-b>40||(a-x)>40||(x-a)>40||y<b){return 0;}elsereturn 1;}default:return 0;}}*/精品。
中国象棋游戏源代码
using System;using System.Collections.Generic; using ponentModel; using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace象棋{enum player{blank,red,blue,};enum chesstype{blank,jiang,che,ma,pao,xiang,zu,shi};struct chess{public player side;public chesstype type;};//下载于struct block{public PictureBox container;public chess item;};public partial class Form1 : Form{public Form1(){InitializeComponent();pictureboxlist = new List<PictureBox>(81); Matrix=new block[10][];int i,j;for (i = 0; i < 10;i++ ){Matrix[i] = new block[9];}for(i=0;i<10;i++){for(j=0;j<9;j++){Control[] col =this.Controls.Find("pictureBox" + (i*9+j+1), false); Matrix[i][j].container=col[0] as PictureBox;Matrix[i][j].container.Location = new Point(60 * j, 60 * i);}}redcoll = new collecter();bluecool = new collecter();for (i = 91; i < 107;i++ ){Control[] col =this.Controls.Find("pictureBox" + i, false);bluecool.add(col[0] as PictureBox);}for (i = 107; i < 123;i++ ){Control[] col =this.Controls.Find("pictureBox" + i, false);redcoll.add(col[0] as PictureBox);}resetground();}List<PictureBox> pictureboxlist;block[][] Matrix;collecter redcoll;collecter bluecool;int chozenX;int chozenY;player currentside;bool beenchozen;bool clickswitch;private void click1(object sender, EventArgs e) {if(!clickswitch){resetground();return;}string name = (sender as PictureBox).Name;string number = name.Substring(10);int index = Convert.ToInt32(number);int i,j;bool flag = false;i=(index-1)/9;j=(index-1)%9;//下载于if (beenchozen){Matrix[chozenX][chozenY].container.BorderStyle = BorderStyle.None;Matrix[chozenX][chozenY].container.BackColor =Color.Transparent;beenchozen = false;if(Matrix[chozenX][chozenY].item.side==Matrix[i][j].it em.side){return;}if(Matrix[chozenX][chozenY].item.side != player.blank) {if(Matrix[i][j].item.type== chesstype.jiang){flag=true;}if(!movechess(i, j)){return;}if(flag){if (currentside == player.red) {MessageBox.Show("红方胜利!点击任意处重新开局");}else{MessageBox.Show("蓝方胜利!点击任意处重新开局");}clickswitch = false;}}if (currentside == player.red){currentside = player.blue;label1.Text = "蓝方";label1.ForeColor = Color.Blue;}else{currentside = player.red;label1.Text = "红方";label1.ForeColor = Color.Red;}}else if(Matrix[i][j].item.side== currentside){Matrix[i][j].container.BorderStyle = BorderStyle.FixedSingle;Matrix[i][j].container.BackColor = Color.Brown;chozenX = i;chozenY = j;beenchozen = true;}}private void resetground(){int i, j;for (i = 0; i < 10;i++ ){for(j=0;j<9;j++){Matrix[i][j].container.Image = null;Matrix[i][j].item.side = player.blank;Matrix[i][j].item.type = chesstype.blank;}}beenchozen = false;clickswitch = true;currentside = player.red;label1.Text = "红方";label1.ForeColor = Color.Red;redcoll.clear();bluecool.clear();Matrix[0][0].container.Image = global::象棋.Properties.Resources.蓝车;Matrix[0][1].container.Image = global::象棋.Properties.Resources.蓝马;Matrix[0][2].container.Image = global::象棋.Properties.Resources.蓝象;Matrix[0][3].container.Image = global::象棋.Properties.Resources.蓝士;Matrix[0][4].container.Image = global::象棋.Properties.Resources.蓝将;Matrix[0][5].container.Image = global::象棋.Properties.Resources.蓝士;Matrix[0][6].container.Image = global::象棋.Properties.Resources.蓝象;Matrix[0][7].container.Image = global::象棋.Properties.Resources.蓝马;Matrix[0][8].container.Image = global::象棋.Properties.Resources.蓝车;Matrix[2][1].container.Image = global::象棋.Properties.Resources.蓝炮;Matrix[2][7].container.Image = global::象棋.Properties.Resources.蓝炮;Matrix[3][0].container.Image = global::象棋.Properties.Resources.蓝卒;Matrix[3][2].container.Image = global::象棋.Properties.Resources.蓝卒;Matrix[3][4].container.Image = global::象棋.Properties.Resources.蓝卒;Matrix[3][6].container.Image = global::象棋.Properties.Resources.蓝卒;Matrix[3][8].container.Image = global::象棋.Properties.Resources.蓝卒;Matrix[6][0].container.Image = global::象棋.Properties.Resources.红卒;Matrix[6][2].container.Image = global::象棋.Properties.Resources.红卒;Matrix[6][4].container.Image = global::象棋.Properties.Resources.红卒;Matrix[6][6].container.Image = global::象棋.Properties.Resources.红卒;Matrix[6][8].container.Image = global::象棋.Properties.Resources.红卒;Matrix[7][1].container.Image = global::象棋.Properties.Resources.红炮;Matrix[7][7].container.Image = global::象棋.Properties.Resources.红炮;Matrix[9][0].container.Image = global::象棋.Properties.Resources.红车;Matrix[9][1].container.Image = global::象棋.Properties.Resources.红马;Matrix[9][2].container.Image = global::象棋.Properties.Resources.红象;Matrix[9][3].container.Image = global::象棋.Properties.Resources.红士;Matrix[9][4].container.Image = global::象棋.Properties.Resources.红将;Matrix[9][5].container.Image = global::象棋.Properties.Resources.红士;Matrix[9][6].container.Image = global::象棋.Properties.Resources.红象;Matrix[9][7].container.Image = global::象棋.Properties.Resources.红马;Matrix[9][8].container.Image = global::象棋.Properties.Resources.红车;//下载于Matrix[0][0].item.side = player.blue;Matrix[0][1].item.side = player.blue;Matrix[0][2].item.side = player.blue;Matrix[0][3].item.side = player.blue;Matrix[0][4].item.side = player.blue;Matrix[0][5].item.side = player.blue;Matrix[0][6].item.side = player.blue;Matrix[0][7].item.side = player.blue;Matrix[0][8].item.side = player.blue;Matrix[2][1].item.side = player.blue;Matrix[2][7].item.side = player.blue;Matrix[3][0].item.side = player.blue;Matrix[3][2].item.side = player.blue;Matrix[3][4].item.side = player.blue;Matrix[3][6].item.side = player.blue;Matrix[3][8].item.side = player.blue;Matrix[6][0].item.side = player.red;Matrix[6][2].item.side = player.red;Matrix[6][4].item.side = player.red;Matrix[6][6].item.side = player.red;Matrix[6][8].item.side = player.red;Matrix[7][1].item.side = player.red;Matrix[7][7].item.side = player.red;Matrix[9][0].item.side = player.red;Matrix[9][1].item.side = player.red;Matrix[9][2].item.side = player.red;Matrix[9][3].item.side = player.red;Matrix[9][4].item.side = player.red;Matrix[9][5].item.side = player.red;Matrix[9][6].item.side = player.red;Matrix[9][7].item.side = player.red;Matrix[9][8].item.side = player.red;Matrix[0][0].item.type = chesstype.che; Matrix[0][1].item.type = chesstype.ma;Matrix[0][2].item.type = chesstype.xiang; Matrix[0][3].item.type = chesstype.shi; Matrix[0][4].item.type = chesstype.jiang; Matrix[0][5].item.type = chesstype.shi; Matrix[0][6].item.type = chesstype.xiang; Matrix[0][7].item.type = chesstype.ma;Matrix[0][8].item.type = chesstype.che; Matrix[2][1].item.type = chesstype.pao; Matrix[2][7].item.type = chesstype.pao; Matrix[3][0].item.type = chesstype.zu;Matrix[3][2].item.type = chesstype.zu;Matrix[3][4].item.type = chesstype.zu;Matrix[3][6].item.type = chesstype.zu;Matrix[3][8].item.type = chesstype.zu;Matrix[6][0].item.type = chesstype.zu;Matrix[6][2].item.type = chesstype.zu;Matrix[6][4].item.type = chesstype.zu;Matrix[6][6].item.type = chesstype.zu;Matrix[6][8].item.type = chesstype.zu;Matrix[7][1].item.type = chesstype.pao;Matrix[7][7].item.type = chesstype.pao;Matrix[9][0].item.type = chesstype.che;Matrix[9][1].item.type = chesstype.ma;Matrix[9][2].item.type = chesstype.xiang; Matrix[9][3].item.type = chesstype.shi;Matrix[9][4].item.type = chesstype.jiang; Matrix[9][5].item.type = chesstype.shi;Matrix[9][6].item.type = chesstype.xiang; Matrix[9][7].item.type = chesstype.ma;Matrix[9][8].item.type = chesstype.che;}private bool movechess(int X,int Y){int i, j, k, n=0;switch(Matrix[chozenX][chozenY].item.type) {case chesstype.che:if(chozenX==X){i = chozenY < Y ? chozenY : Y; j = chozenY > Y ? chozenY : Y;for(k=i+1;k<j;k++){if(Matrix[X][k].item.side!= player.blank){return false;}}}if (chozenY == Y){i = chozenX < X ? chozenX : X; j = chozenX > X ? chozenX : X;for (k = i + 1; k < j; k++){if(Matrix[k][Y].item.side != player.blank){return false;}}}setmove(X, Y);return true;case chesstype.jiang:if(Matrix[X][Y].item.type== chesstype.jiang&&chozenY==Y){i = chozenX < X ? chozenX : X; j = chozenX > X ? chozenX : X;for (k = i + 1; k < j; k++){if(Matrix[k][Y].item.side != player.blank){return false;}}setmove(X, Y);return true;}if(Matrix[chozenX][chozenY].item.side== player.blue){if(Y<3||Y>5||X>2){return false;}}else{if(Y<3||Y>5||X<7){return false;}}if((chozenX-X)*(chozenX-X)+(chozenY-Y)*(chozenY-Y)!=1) {return false;}setmove(X, Y);return true;case chesstype.ma:if (Math.Abs(chozenX - X) == 1 && Math.Abs(chozenY - Y) == 2){if (Matrix[chozenX][chozenY +(Y - chozenY) / Math.Abs(Y - chozenY)].item.side!= player.blank){return false;}}else if (Math.Abs(chozenX - X) == 2 && Math.Abs(chozenY - Y) == 1){if (Matrix[chozenX + (X - chozenX) / Math.Abs(X - chozenX)][chozenY].item.side != player.blank){return false;}}else{return false;}setmove(X, Y);return true;case chesstype.pao: n = 0;if(chozenX==X){i = chozenY < Y ? chozenY : Y; j = chozenY > Y ? chozenY : Y; n = 0;for(k=i+1;k<j;k++){if(Matrix[X][k].item.side!= player.blank){n++;}}if(n>1){return false;}}else if (chozenY == Y){i = chozenX < X ? chozenX : X; j = chozenX > X ? chozenX : X; n = 0;for (k = i + 1; k < j; k++){if(Matrix[k][Y].item.side != player.blank){n++;}}if (n > 1){return false;}}else{return false;}if(n==0&&Matrix[X][Y].item.side!= player.blank){return false;}if(n==1&&Matrix[X][Y].item.side== player.blank){return false;}setmove(X, Y);return true;case chesstype.shi:if(Matrix[chozenX][chozenY].item.side== player.blue){if(Y<3||Y>5||X>2){return false;}}else{if(Y<3||Y>5||X<7){return false;}}if(Math.Abs(X-chozenX)!=1||Math.Abs(chozenY-Y)!=1){return false;}setmove(X, Y);return true;case chesstype.xiang:if(Matrix[chozenX][chozenY].item.side == player.blue){if (X>4){return false;}}else{if (X<5){return false;}}if ((X - chozenX) * (X - chozenX) + (chozenY - Y) * (chozenY - Y) != 8){return false;}if(Matrix[(X+chozenX)/2][(Y+chozenY)/2].item.side!=player.blank){return false;}setmove(X, Y);return true;case chesstype.zu:if(X!=chozenX&&Y!=chozenY){return false;}if(Matrix[chozenX][chozenY].item.side == player.blue) {if (chozenX<5&&X-chozenX!=1) {return false;}if(chozenX>4){if(X==chozenX&&Math.Abs(Y-chozenY)!=1){return false;}if(Y==chozenY&&X-chozenX!=1){return false;}}}else{if (chozenX>4&&chozenX-X!=1) {return false;}if (chozenX <5){if (X == chozenX && Math.Abs(Y - chozenY) != 1){return false;}if (Y == chozenY && chozenX-X != 1){return false;}}}setmove(X,Y);return true;}return false;}private void setmove(int X,int Y){if (Matrix[X][Y].item.side== player.red) {redcoll.push(Matrix[X][Y].container.Image);}else if (Matrix[X][Y].item.side == player.blue){bluecool.push(Matrix[X][Y].container.Image);}Matrix[X][Y].container.Image =Matrix[chozenX][chozenY].container.Image;Matrix[X][Y].item =Matrix[chozenX][chozenY].item;Matrix[chozenX][chozenY].container.Image = null;Matrix[chozenX][chozenY].item.side = player.blank;Matrix[chozenX][chozenY].item.type= chesstype.blank;}}class collecter{public PictureBox[] container;public int number;public int chessnum;public collecter(){number = 0;container = new PictureBox[16];chessnum = 0;}public void add(PictureBox box).{container[number++] = box;}public void push(Image ima){container[chessnum++].BackgroundImage = ima;}public void clear(){for (int i = 0; i < chessnum; i++){container[i].BackgroundImage = null; }chessnum = 0;}};}.。
中国象棋C代码
中国象棋#include<stdio.h>#include<conio.h>#include<string.h>#include<stdlib.h>#include<windows.h>int x, y, i, j, k, p, q, num = 1, round; //象棋游戏的全局变量int px1 = 0, py1 = 0, px2 = 0, py2 = 0;int ck_x, ck_y, ck_t; //基本参数char ch, tn = 'O', tn1 = 'N', tp, tp1;char ck_1[9][3] ={"車","馬","相","仕","帥","砲","兵","+-"}; //取棋子时只判断前8合法char ck_2[9][3] ={"车","马","象","士","将","炮","卒","+-"};//下棋子时判断多一个空位合法char check[3];void ckm1(char* tp,char* tp1,char* tn,char* tn1,int *num,int *if_ov,char map[100][100]) {//象棋函数判断将方下棋是否合法check[0] = *tp; check[1] = *tp1; check[2] = '\0';char a,b;for ( i = 0; i < 8; i++){ if ( strcmp(ck_2[i],check) == 0){ *tp = *tn; *tp1 = *tn1; *tn = 'O'; *tn1 = 'N';if( i < 7){ printf(" 将方的%s被吃",ck_2[i]); Sleep(500); }*num = *num + 1;for( k = 4; k <= 8; k = k + 2)//判断将是否死亡{for(j = 15; j <= 23; j= j+ 4){ if (map[k][j] == ck_2[4][0] && map[k][j+1] == ck_2[4][1]){ px2 = k; py2 = j; break; }}if( j <= 23) break;}if( k == 10){printf(" 将被将死帥方获得胜利\n"); printf("按任意键返回菜单");getch( ); *if_ov = 1; return;}for( k = 18; k <= 22; k = k + 2) //判断帥是否死亡{for(j = 15; j <= 23; j= j+ 4){if(map[k][j] == ck_1[4][0] && map[k][j+1] == ck_1[4][1]){px1 = k; py1 = j; break; }}if( j <= 23) break;}if ( k == 24){printf(" 帥被将死将方获得胜利\n"); printf("按任意键返回菜单");getch( ); *if_ov = 1; return;}if ( py1 == py2){for( k = px2 + 2; k <= px1 - 2; k = k +2) {if(map[k][py1] != '+') break;}if( k == px1){if(round == 1) printf(" 帥方对将将方胜利");else if( round == 2) printf(" 将方对将帥方胜利");printf("按任意键返回菜单"); getch( ); *if_ov = 1; return;}}break;}} // for ( i = 0; i < 8; i++)循环结束if( i == 8) {printf("不合法的走法\n"); Sleep(500); }}void ckm2(char* tp,char* tp1,char* tn,char* tn1,int *num,int *if_ov,char map[100][100]) {//象棋函数判断帥方下棋是否合法check[0] = *tp; check[1] = *tp1; check[2] = '\0';char a,b;for ( i = 0; i < 8; i++){if ( strcmp(ck_1[i],check) == 0){ *tp = *tn; *tp1 = *tn1; *tn = 'O'; *tn1 = 'N';if( i < 7) {printf(" 帥方的%s被吃",ck_1[i]); Sleep(500); }*num = *num + 1;for( k = 4; k <= 8; k = k + 2) //判断将是否死亡{for(j = 15; j <= 23; j= j+ 4){if(map[k][j] == ck_2[4][0] && map[k][j+1] == ck_2[4][1]){px2 = k; py2 = j; break; }}if( j <= 23) break;}if( k == 10){printf(" 将被将死帥方获得胜利\n");printf("按任意键返回菜单"); getch( );*if_ov = 1; return;}for( k = 18; k <= 22; k = k + 2) //判断帥是否死亡{for(j = 15; j <= 23; j= j+ 4){if(map[k][j] == ck_1[4][0] && map[k][j+1] == ck_1[4][1]){px1 = k; py1 = j; break; }}if( j <= 23) break;}if( k == 24){printf(" 帥被将死将方获得胜利\n");printf("按任意键返回菜单"); getch( );*if_ov = 1; return;}if( py1 == py2){for( k = px2 + 2; k <= px1 - 2; k = k +2) {if(map[k][py1] != '+') break; }if( k == px1){if(round == 1) printf(" 帥方对将将方胜利");else if( round == 2) printf(" 将方对将帥方胜利");printf("按任意键返回菜单"); getch( ); *if_ov = 1; return;}}break;}} // for ( i = 0; i < 8; i++)循环结束if( i == 8) {printf("不合法的走法\n"); Sleep(500); }}void xiangqi( )//象棋主程序{char map[100][100]= { "[[===================================]]","[| ①帥【象棋】②将|]","[[===================================]]","[[-----------------------------------]]","[[ 车—-马—-象—-士—-将—-士—-象—-马—-车]]","[[ | | | | \\ | / | | | | ]]","[[ +-—-+-—-+-—-+-—-+-—-+-—-+-—-+-—-+-]]","[[ | | | | / | \\ | | | | ]]","[[ +-—-炮—-+-—-+-—-+-—-+-—-+-—-炮—-+-]]","[[ | | | | | | | | | ]]","[[ 卒—-+-—-卒—-+-—-卒—-+-—-卒—-+-—-卒]]","[[ | | | | | | | | | ]]","[[ +-—-+-—-+-—-+-—-+-—-+-—-+-—-+-—-+-]]","[[===================================]]","[[ +-—-+-—-+-—-+-—-+-—-+-—-+-—-+-—-+-]]","[[ | | | | | | | | | ]]","[[ 兵—-+-—-兵—-+-—-兵—-+-—-兵—-+-—-兵]]","[[ | | | | | | | | | ]]","[[ +-—-砲—-+-—-+-—-+-—-+-—-+-—-砲—-+-]]","[[ | | | | \\ | / | | | | ]]","[[ +-—-+-—-+-—-+-—-+-—-+-—-+-—-+-—-+-]]","[[ | | | | / | \\ | | | | ]]","[[ 車—-馬—-相—-仕—-帥—-仕—-相—-馬—-車]]","[[-----------------------------------]]","[[===================================]]"};int if_ov = 0;system("mode con cols=42 lines=32"); //迷你界面system("color 70");printf("[[==================================]]\n");printf("[[ -------------------------------- ]]\n");printf("[[ | | ]]\n");printf("[[ | 【<<游戏规则>>】| ]]\n");printf("[[ | | ]]\n");printf("[[ |------------------------------| ]]\n");printf("[[ | 控制wasd双方轮流控制指针下棋| ]]\n");printf("[[ |------------------------------| ]]\n");printf("[[ | 键盘输入大小写‘M ’| ]]\n");printf("[[ | 都视为确认下棋| ]]\n");printf("[[ |------------------------------| ]]\n");printf("[[ | 为了方便区分棋子| ]]\n");printf("[[ | 先手方全设为繁体复杂字体| ]]\n");printf("[[ |------------------------------| ]]\n");printf("[[ |------------------------------| ]]\n");printf("[[ | 我已阅读规则,按任意键继续| ]]\n");printf("[[ |------------------------------| ]]\n");printf("[[==================================]]\n");getch( );system("mode con cols=42 lines=32"); //迷你界面system("color 70");for ( i = 0; i < 27; i++){ puts(map[i]); Sleep(100); }x = 6, y = 19; tp = map[x][y]; tp1 = map[x][y+1];while(num){ if (num % 2 == 1 &&num / 2 % 2 == 0){ printf(" 现在是'帥'的回合\n");round = 1; } else if( num %2 == 1){ printf(" 现在轮到'将'的回合了\n");round = 2; }ch = getch( );if ( ch == 's') //下移{ if ( map[x+1][y]!= '-'){map[x][y] =tp; map[x][y+1] = tp1;x = x + 2; tp = map[x][y]; tp1 = map[x][y+1];map[x][y] = tn; map[x][y+1] = tn1;}}else if ( ch == 'a') //左移{ if (map[x][y-1]!=' '){map[x][y] =tp; map[x][y+1] = tp1;y = y - 4; tp = map[x][y]; tp1 = map[x][y+1];map[x][y] = tn; map[x][y+1] = tn1;}}else if ( ch == 'w') //上移{ if ( map[x-1][y]!= '-'){map[x][y] =tp; map[x][y+1] = tp1;x = x - 2; tp = map[x][y]; tp1 = map[x][y+1];map[x][y] = tn; map[x][y+1] = tn1;}}else if ( ch == 'd') //右移{ if (map[x][y+2]!=']'){map[x][y] =tp; map[x][y+1] = tp1;y = y + 4; tp = map[x][y]; tp1 = map[x][y+1];map[x][y] = tn; map[x][y+1] = tn1;}}else if( ch == 'm' || ch =='M')//M确认要移动的棋子,或确认要移到的目的地{ if (num % 2 == 1 && tp != '+' && tp1 != '-') //取子{check[0] = tp; check[1] = tp1; check[2] = '\0';if ( round == 1){ for ( i = 0; i < 7; i++) //将方{ if ( strcmp(ck_1[i],check) == 0){tn = tp; tn1 = tp1; tp = '+'; tp1 = '-';ck_x = x; ck_y = y; ck_t = 10 + i;num++; break;}}if( i == 7){ printf("这不是你的棋子\n"); Sleep(500); }}else if( round == 2){for ( i = 0; i < 7; i++) //帅方{ if( strcmp(ck_2[i],check) == 0){tn = tp; tn1 = tp1; tp = '+'; tp1 = '-';ck_x = x; ck_y = y; ck_t = 20 + i;num++; break;}}if( i == 7){ printf("这不是你的棋子\n"); Sleep(500); }}}else if( num % 2 == 0) //放子{ char ck_1[8][3] ={"车","马","象","士","将","炮","卒","+-"};char ck_2[8][3] ={"俥","馬","相","仕","帥","軳","兵","+-"};//中界楚河上下坐标12 15 往下2 往右4if ( ck_t < 20){if( ck_t == 10) //车的走法规范(将方){ if((x == ck_x && y == ck_y)){tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n"); printf("还是你的回合"); Sleep(500);}else if( y == ck_y ){ if( x > ck_x){ for(j = ck_x + 2; j < x;j = j + 2){ if(map[j][y] == '+'); else{printf("不合法的下法\n"); Sleep(500); break; }}if( j >= x) ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);}if( x < ck_x){ for(j = ck_x - 2; j > x;j = j - 2){ if(map[j][y] == '+'); else{printf("不合法的下法\n"); Sleep(500); break; }}if( j <= x) ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);}}else if( x == ck_x ){if( y > ck_y){for(j = ck_y + 4; j < y;j = j + 4){if(map[x][j] == '+'); else {printf("不合法的下法\n"); Sleep(500); break; }}if( j >= y) ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);}if( y < ck_y){for(j = ck_y - 4; j > y;j = j - 4){ if(map[x][j] == '+'); else { printf("不合法的下法\n"); Sleep(500); break; }}if( j <= y) ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);}}else { printf("不合法的下法\n"); Sleep(500); }}if( ck_t == 11) //马的走法规范{if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n"); printf("还是你的回合"); Sleep(500);}else if( (abs( x - ck_x) == 2&& abs( y - ck_y) == 8)&& map[ck_x][(y+ck_y)/2] =='+') {ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map); }else if( (abs( x - ck_x) == 4&& abs( y - ck_y) == 4)&& map[(x + ck_x)/2][ck_y] == '+' ) {ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map); }else { printf("不合法的下法\n");Sleep(500); }}if( ck_t == 12) //相的走法规范{ if((x == ck_x && y == ck_y)){tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n"); printf("还是你的回合"); Sleep(500);}else if( x >= 15 &&(abs(y - ck_y) == 8 && abs(x - ck_x) == 4)){if((x == 22 && (y == 11 || y == 27))||(x == 18 &&( y == 3 || y == 19 || y == 35)) ||(x == 14 && (y == 11|| y ==27))){ if( map[(x+ck_x)/2][(y+ck_y)/2] == '+')ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else {printf("棋子卡住,不可执行"); Sleep(500); }}else {printf("不合法的下法\n");Sleep(500); }}else {printf("不合法的下法\n"); Sleep(500); }}if( ck_t == 13) //士的走法规范{ if((x == ck_x && y == ck_y)){tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n"); printf("还是你的回合"); Sleep(500);}else if( abs(x - ck_x)== 2 && abs( y - ck_y) == 4 &&((x==22 && (y == 15 || y == 23)) || ( x == 20 && y == 19) || ( x == 18 && ( y == 15 || y == 23)))){ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map); }else { printf("不合法的下法\n"); Sleep(500); }}if( ck_t == 14) //将的走法规范{ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n"); printf("还是你的回合"); Sleep(500);}else if( ((abs(x - ck_x)== 2 && abs( y - ck_y) == 0 )|| (abs(x - ck_x)== 0 && abs( y - ck_y) == 4)) && x >= 18 && x <= 22 && y >= 15 && y <= 23 ){ ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map); }else { printf("不合法的下法\n"); Sleep(500); }}if( ck_t == 15) //炮的走法规范{ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n"); printf("还是你的回合"); Sleep(500);}else if( y == ck_y ){ int check_pao = 0;if( x > ck_x){ for(j = ck_x + 2; j<= x ;j = j+ 2){ if(map[j][y] == '+' ); else check_pao++;}if(check_pao == 1&& tp == '+') // 直线行走但不可吃棋子ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else if( check_pao == 2 && tp != '+') //跳跃吃棋ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n"); Sleep(500); }}else { for(j = ck_x - 2; j>= x;j = j - 2){ if(map[j][y] == '+' ); else { check_pao++;} }if(check_pao == 1&& tp == '+') //直线行走但不可吃棋子ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else if( check_pao == 2 && tp != '+') //跳跃吃棋ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n"); Sleep(500); }}}else if( x == ck_x ){ int check_pao = 0;if( y > ck_y){ for(j = ck_y + 4; j<= y ;j = j+4){ if(map[x][j] == '+' ); else check_pao++;}if(check_pao == 1&& tp == '+') //直线行走但不可吃棋子ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else if( check_pao == 2 && tp != '+') //跳跃吃棋ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n"); Sleep(500); }}else {for(j = ck_y - 4; j>= y;j = j - 4){if(map[x][j] == '+' ); else check_pao++;}if(check_pao == 1&& tp == '+') //直线行走但不可吃棋子ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else if( check_pao == 2 && tp != '+') //跳跃吃棋ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n"); Sleep(500); }}}else { printf("不合法的下法\n");Sleep(500); }}if( ck_t == 16) //卒的走法规范{ if ( x >= 14){ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n"); printf("还是你的回合"); Sleep(500);}else if( x == ck_x - 2 && y == ck_y)ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n"); Sleep(500); }}else{ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n"); printf("还是你的回合"); Sleep(500);}else if((x - ck_x == 0 && abs(y-ck_y) ==4) ||( x - ck_x == -2 && abs(y-ck_y) == 0)) ckm1(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n"); Sleep(500); }}}}else { if( ck_t == 20) //车的走法规范(帅方){ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n"); printf("还是你的回合"); Sleep(500);}else if( y == ck_y ){ if( x > ck_x){ for(j = ck_x + 2; j < x;j = j + 2){ if(map[j][y] == '+'); else {printf("不合法的下法\n"); Sleep(500); break; } }if( j >= x) ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);}if( x < ck_x){ for(j = ck_x - 2; j > x;j = j - 2){ if(map[j][y] == '+'); else { printf("不合法的下法\n"); Sleep(500); break; } }if( j <= x) ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);}}else if( x == ck_x ){ if( y > ck_y){ for(j = ck_y + 4; j < y;j = j + 4){ if(map[x][j] == '+'); else { printf("不合法的下法\n"); Sleep(500); break; } }if( j >= y) ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);}if( y < ck_y){ for(j = ck_y - 4; j > y;j = j - 4){ if(map[x][j] == '+'); else { printf("不合法的下法\n");Sleep(500); break; } }if( j <= y) ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);}}else { printf("不合法的下法\n"); Sleep(500); }}if( ck_t == 21) //马的走法规范{ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n");printf("还是你的回合"); Sleep(500);}else if( (abs( x - ck_x) == 2&& abs( y - ck_y) == 8)&&map[ck_x][(y+ck_y)/2] =='+'){ ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map); }else if( (abs( x - ck_x) == 4&& abs( y - ck_y) == 4)&&map[(x + ck_x)/2][ck_y] == '+' ){ ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map); }else { printf("不合法的下法\n");Sleep(500); }}if( ck_t == 22) //相的走法规范{ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n");printf("还是你的回合"); Sleep(500);}else if( x <= 12 && (abs(y - ck_y) == 8 && abs(x - ck_x) == 4)){ if((x == 4 && (y == 11 || y == 27))||(x == 8 && ( y == 3 || y == 19 || y == 35)) ||(x == 12 && (y == 11|| y ==27))){ if( map[(x+ck_x)/2][(y+ck_y)/2] == '+')ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("棋子卡住,不可执行");Sleep(500); }}else {printf("不合法的下法\n");Sleep(500); }}else { printf("不合法的下法\n");Sleep(500); }}if( ck_t == 23) //士的走法规范{ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n");printf("还是你的回合"); Sleep(500);}else if( abs(x - ck_x)== 2 && abs( y - ck_y) == 4 &&((x==4 &&(y == 15 || y == 23)) || ( x == 6 && y == 19) || ( x == 8 && ( y == 15 || y == 23)))) { ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map); }else { printf("不合法的下法\n");Sleep(500); }}if( ck_t == 24) //将的走法规范{ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n");printf("还是你的回合"); Sleep(500);}else if( ((abs(x - ck_x)== 2 && abs( y - ck_y) == 0 )|| (abs(x - ck_x)== 0 && abs( y - ck_y) == 4)) && x >= 4 && x <= 8 && y >= 15 && y <= 23 ){ ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map); }else {printf("不合法的下法\n");Sleep(500); }}if( ck_t == 25) //炮的走法规范{ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n");printf("还是你的回合"); Sleep(500);}else if( y == ck_y ){ int check_pao = 0;if( x > ck_x){ for(j = ck_x + 2; j<= x ;j = j+ 2){ if(map[j][y] == '+' ); else check_pao++;}if(check_pao == 1&& tp == '+') //直线行走但不可吃棋子ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else if( check_pao == 2 && tp != '+') //跳跃吃棋ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n");Sleep(500); }}else { for(j = ck_x - 2; j>= x;j = j - 2){ if(map[j][y] == '+' ); else { check_pao++;} }if(check_pao == 1&& tp== '+') //直线行走但不可吃棋子ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else if( check_pao == 2 && tp != '+') //跳跃吃棋ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n");Sleep(500); }}}else if( x == ck_x ){ int check_pao = 0;if( y > ck_y){ for(j = ck_y + 4; j<= y ;j = j+4){ if(map[x][j] == '+' ); else check_pao++;}if(check_pao == 1&& tp == '+') //直线行走但不可吃棋子ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else if( check_pao == 2 && tp != '+') //跳跃吃棋ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n");Sleep(500); }}else{ for(j = ck_y - 4 ; j>= y;j = j - 4){ if(map[x][j] == '+' ); else check_pao++;}if(check_pao ==1&& tp == '+') //直线行走但不可吃棋子ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else if( check_pao == 2&& tp != '+') //跳跃吃棋ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n");Sleep(500); }}}else { printf("不合法的下法\n");Sleep(500); }}if( ck_t == 26) //卒的走法规范{ if( x <= 12){ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n"); printf("还是你的回合"); Sleep(500);}else if( x == ck_x + 2 && y == ck_y)ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n");Sleep(500); }}else{ if((x == ck_x && y == ck_y)){ tp = tn; tp1 = tn1; tn = 'O'; tn1 = 'N'; num--;printf("三思而后行\n");printf("还是你的回合"); Sleep(500);}else if((x - ck_x == 0 && abs(y-ck_y) ==4) ||( x - ck_x == 2&& abs(y-ck_y) == 0))ckm2(&tp,&tp1,&tn,&tn1,&num,&if_ov,map);else { printf("不合法的下法\n");Sleep(500); }}}}}}system("cls");if( if_ov) return;for(i = 0; i < 27; i++)puts(map[i]);}Sleep(5000);}int main( ){while(1){xiangqi( );printf("\n 重来,请按键.\n");getch( );}return 0;}。
象棋游戏代码
#include<stdio.h>#include<math.h>int x[11][12];void main(){int i,j;int x1,y1,x2,y2,rg,gg;int rgo(int,int,int,int);int ggo(int,int,int,int);/*初始化棋子(开局)*/for(i=1;i<=5;i++){ x[i][1]=x[10-i][1]=i+10;x[i][10]=x[10-i][10]=i+20;if(i%2==1){ x[i][4]=x[10-i][4]=17;x[i][7]=x[10-i][7]=27;}}x[2][3]=x[8][3]=16;x[2][8]=x[8][8]=26;for(i=0;i<=9;i++)x[i][0]=i;for(i=1;i<=10;i++)x[0][i]=i;printf("S27\n=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=\n"); for(j=10;j>=0;j--){ for(i=0;i<=9;i++){if(i==0){printf("%2d |",x[i][j]);continue;}if(j==0){printf(" 0%d ",x[i][j]);continue;}switch(x[i][j]){case 0 : printf(" ");break;case 11 : printf(" 车");break;case 12 : printf(" 马");break;case 13 : printf(" 相");break;case 14 : printf(" 士");break;case 15 : printf(" 帅");break;case 16 : printf(" 炮");break;case 17 : printf(" 兵");break;case 21 : printf(" JU ");break;case 22 : printf(" MA ");break;case 23 : printf(" XN ");break;case 24 : printf(" SH ");break;case 25 : printf(" JN ");break;case 26 : printf(" PO ");break;case 27 : printf(" ZU ");break;}}if(j==1)printf("|\n---+-------------------------------------\n");else if(j==0)printf("\n");elseprintf("|\n | |\n");}/*走子*/for(;;){/*红子走子*/for(rg=0;rg==0;){for(x1=0,y1=0,x2=0,y2=0;x[x1][y1]==0||x[x1][y1]>=20||x2<1||y2<1||x2>9||y2>10||x[x2][y2] <20&&x[x2][y2]>10||x[x2][y2]==x[x1][y1];){printf("请输入红子坐标(x1,y1,x2,y2):");scanf("%d,%d,%d,%d",&x1,&y1,&x2,&y2);}if(x[x1][y1]>20){continue;}rg=rgo(x1,y1,x2,y2);if(rg==0)continue;else{if(x[x2][y2]==25){x[x2][y2]=x[x1][y1],x[x1][y1]=0;printf("lu qi shu le\n");}elsex[x2][y2]=x[x1][y1],x[x1][y1]=0;}}printf("S27 制作\n=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=\n"); for(j=10;j>=0;j--){for(i=0;i<=9;i++){if(i==0){printf("%2d |",x[i][j]);continue;}if(j==0){printf(" 0%d ",x[i][j]);continue;}switch(x[i][j]){case 0 : printf(" ");break;case 11 : printf(" 车");break;case 12 : printf(" 马");break;case 13 : printf(" 相");break;case 14 : printf(" 士");break;case 15 : printf(" 帅");break;case 16 : printf(" 炮");break;case 17 : printf(" 兵");break;case 21 : printf(" JU ");break;case 22 : printf(" MA ");break;case 23 : printf(" XN ");break;case 24 : printf(" SH ");break;case 25 : printf(" JN ");break;case 26 : printf(" PO ");break;case 27 : printf(" ZU ");break;}}if(j==1)printf("|\n---+-------------------------------------\n");else if(j==0)printf("\n");printf("|\n | |\n");}/*绿子走子*/for(gg=0;gg==0;){for(x1=0,y1=0,x2=0,y2=0;x[x1][y1]<10||x2<1||y2<1||x2>9||y2>10||x[x2][y2]>20||x[x2][y2]= =x[x1][y1];){printf("请输入绿子坐标(x1,y1,x2,y2):");scanf("%d,%d,%d,%d",&x1,&y1,&x2,&y2);}if(x[x1][y1]<20){continue;}gg=ggo(x1,y1,x2,y2);if(gg==0)continue;else{if(x[x2][y2]==25){x[x2][y2]=x[x1][y1],x[x1][y1]=0;printf("hong qi shu le\n");}elsex[x2][y2]=x[x1][y1],x[x1][y1]=0;}}printf("S27 制作\n=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=\n");for(j=10;j>=0;j--){for(i=0;i<=9;i++){if(i==0){printf("%2d |",x[i][j]);continue;}if(j==0){printf(" 0%d ",x[i][j]);continue;switch(x[i][j]){case 0 : printf(" ");break;case 11 : printf(" 车");break;case 12 : printf(" 马");break;case 13 : printf(" 相");break;case 14 : printf(" 士");break;case 15 : printf(" 帅");break;case 16 : printf(" 炮");break;case 17 : printf(" 兵");break;case 21 : printf(" JU ");break;case 22 : printf(" MA ");break;case 23 : printf(" XN ");break;case 24 : printf(" SH ");break;case 25 : printf(" JN ");break;case 26 : printf(" PO ");break;case 27 : printf(" ZU ");break;}}if(j==1)printf("|\n---+-------------------------------------\n");else if(j==0)printf("\n");elseprintf("|\n | |\n"); }}}/*判定红棋是否有错*/int rgo(int xa,int ya,int xb,int yb){ if(x[xa][ya]==11) /*车*/{int t;if(xb-xa==0){if(yb<ya)t=yb,yb=ya,ya=t;for(t=1+ya;t<yb;t++)if(x[xa][t]!=0&&x[xa][t]<20)return 0;}else if(yb-ya==0){ if(xb<xa)t=xb,xb=xa,xa=t;for(t=1+xa;t<xb;t++)if(x[t][ya]!=0&&x[xa][t]<20)return 0;}else return 0;return 1;}if(x[xa][ya]==12) /*马*/ { if(fabs(yb-ya)==2&&fabs(xb-xa)==1) {if(yb-ya>0&&x[xa][ya+1]!=0)return 0;if(yb-ya<0&&x[xa][ya-1]!=0)return 0;if(x[xb][yb]!=0&&x[xb][yb]<20)return 0;}else if(fabs(xb-xa)==2&&fabs(yb-ya)==1) {if(xb-xa>0&&x[xa+1][ya]!=0)return 0;if(xb-xa<0&&x[xa-1][ya]!=0)return 0;if(x[xb][yb]!=0&&x[xb][yb]<20)return 0;}else return 0;return 1;}if(x[xa][ya]==13) /*相*/ {if(yb>5)return 0;if(fabs(yb-ya)==2&&fabs(xb-xa)==2) {if(yb-ya>0){if(xb-xa>0&&x[xa+1][ya+1]!=0)return 0;else if(xb-xa<0&&x[xa-1][ya+1]!=0)return 0;}else{if(xb-xa>0&&x[xa+1][ya-1]!=0)return 0;else if(xb-xa<0&&x[xa-1][ya-1]!=0)return 0;}if(x[xb][yb]!=0&&x[xb][yb]<20)return 0;}else return 0;return 1;}if(x[xa][ya]==14) /*士*/{if(xb<4||xb>6||yb>3)return 0;if(x[xb][yb]!=0&&x[xb][yb]<20)return 0;if(fabs(yb-ya)==fabs(xb-xa)==1)return 1;else return 0;}if(x[xa][ya]==15) /*帅*/{if(xb<4||xb>6||yb>3)return 0;if((fabs(yb-ya)==1&&xb-xa==0)||(fabs(xb-xa)==1&&yb-ya==0)) return 1;else return 0;}if(x[xa][ya]==16) /*炮*/{int t,k;if(yb-ya==0){if(xb<xa)t=xb,xb=xa,xa=t;for(t=0,k=1;xb>xa+k;k++)if(x[xa+k][ya]!=0)t++;if(t>1)return 0;else if(t==0){if(x[xb][yb]==0||x[xa][ya]==0)return 1;else return 0;}else if(t==1){if(x[xb][yb]>20)return 1;else return 0;}}else if(xb-xa==0){if(yb<ya)t=yb,yb=ya,ya=t;for(t=0,k=1;yb>ya+k;k++)if(x[xa][ya+k]!=0)t++;if(t>1)return 0;else if(t==0){if(x[xb][yb]==0||x[xa][ya]==0)return 1;else return 0;}else if(t==1){if(x[xb][yb]>20)return 1;else return 0;}}else return 0;}if(x[xa][ya]==17) /*兵*/{if(yb==ya&&fabs(xb-xa)==1||yb-ya==1&&xb==xa) {if((ya==4||ya==5)&&xb!=xa)return 0;if(x[xb][yb]!=0&&x[xb][yb]<20)return 0;}else return 0;}}/*判定绿棋是否有错*/int ggo(int xa,int ya,int xb,int yb){if(x[xa][ya]==21) /*车*/ {int t;if(xb-xa==0){if(yb<ya)t=yb,yb=ya,ya=t;for(t=1+ya;t<yb;t++)if(x[xa][t]!=0&&x[xa][t]>20)return 0;}else if(yb-ya==0){if(xb<xa)t=xb,xb=xa,xa=t;for(t=1+xa;t<xb;t++)if(x[t][ya]!=0&&x[t][ya]>20)return 0;}else return 0;return 1;}if(x[xa][ya]==22) /*马*/ {if(fabs(yb-ya)==2&&fabs(xb-xa)==1) {if(yb-ya>0&&x[xa][ya+1]!=0)return 0;if(yb-ya<0&&x[xa][ya-1]!=0)return 0;if(x[xb][yb]!=0&&x[xb][yb]>20)return 0;}else if(fabs(xb-xa)==2&&fabs(yb-ya)==1) {if(xb-xa>0&&x[xa+1][ya]!=0)return 0;if(xb-xa<0&&x[xa-1][ya]!=0)if(x[xb][yb]!=0&&x[xb][yb]>20)return 0;}else return 0;return 1;}if(x[xa][ya]==23) /*相*/ {if(yb<6)return 0;if(fabs(yb-ya)==2&&fabs(xb-xa)==2) {if(yb-ya>0){if(xb-xa>0&&x[xa+1][ya+1]!=0)return 0;else if(xb-xa<0&&x[xa-1][ya+1]!=0)return 0;}else{if(xb-xa>0&&x[xa+1][ya-1]!=0)return 0;else if(xb-xa<0&&x[xa-1][ya-1]!=0)return 0;}if(x[xb][yb]!=0&&x[xb][yb]>20)return 0;}else return 0;return 1;}if(x[xa][ya]==24) /*士*/ {if(xb<4||xb>6||yb<8)return 0;if(x[xb][yb]!=0&&x[xb][yb]>20)return 0;if(fabs(yb-ya)==fabs(xb-xa)==1) return 1;else return 0;}if(x[xa][ya]==25) /*帅*/ {return 0;if((fabs(yb-ya)==1&&xb-xa==0)||(fabs(xb-xa)==1&&yb-ya==0)) return 1;else return 0;}if(x[xa][ya]==26) /*炮*/{ int t,k;if(yb-ya==0){ if(xb<xa)t=xb,xb=xa,xa=t;for(t=0,k=1;xb>xa+k;k++)if(x[xa+k][ya]!=0)t++;if(t>1)return 0;else if(t==0){ if(x[xb][yb]==0||x[xa][ya]==0)return 1;else return 0;}else if(t==1){ if(x[xb][yb]<20)return 1;else return 0;}}else if(xb-xa==0){if(yb<ya)t=yb,yb=ya,ya=t;for(t=0,k=1;yb>ya+k;k++)if(x[xa][ya+k]!=0)t++;if(t>1)return 0;else if(t==0){if(x[xb][yb]==0||x[xa][ya]==0)return 1;else return 0;}else if(t==1){return 1;else return 0;}}else return 0;}if(x[xa][ya]==27) /*兵*/{if(yb==ya&&fabs(xb-xa)==1||ya-yb==1&&xb==xa) {if((ya==6||ya==7)&&xb!=xa)return 0;if(x[xb][yb]!=0&&x[xb][yb]>20)return 0;}else return 0;return 1;}}。
Python开发中国象棋实战(附源码)
Python开发中国象棋实战(附源码)Pygame 做的中国象棋,⼀直以来喜欢下象棋,写了 python 就拿来做⼀个试试,⽔平有限,电脑⾛法⽔平低,需要在下次版本中更新电脑⾛法,希望源码能帮助⼤家更好的学习 python。
总共分为四个⽂件,chinachess.py 为主⽂件,constants.py 数据常量,pieces.py 棋⼦类,⾛法,computer.py 电脑⾛法计算。
PS:另外很多⼈在学习Python的过程中,往往因为遇问题解决不了或者没好的教程从⽽导致⾃⼰放弃,为此我整理啦从基础的python脚本到web开发、爬⾍、django、数据挖掘等【PDF等】需要的可以进Python全栈开发交流.裙:⼀久武其⽽⽽流⼀思(数字的谐⾳)转换下可以找到了,⾥⾯有最新Python教程项⽬可拿,不懂的问题有⽼司机解决哦,⼀起相互监督共同进步chinachess.py 为主⽂件import pygameimport timeimport constantsimport piecesimport computerclass MainGame():window = NoneStart_X = constants.Start_XStart_Y = constants.Start_YLine_Span = constants.Line_SpanMax_X = Start_X + 8 * Line_SpanMax_Y = Start_Y + 9 * Line_Spanplayer1Color = constants.player1Colorplayer2Color = constants.player2ColorPutdownflag = player1ColorpiecesSelected = Nonebutton_go = NonepiecesList = []def start_game(self):MainGame.window = pygame.display.set_mode([constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT])pygame.display.set_caption("天青-中国象棋")MainGame.button_go = Button(MainGame.window, "重新开始", constants.SCREEN_WIDTH - 100, 300) # 创建开始按钮self.piecesInit()while True:time.sleep(0.1)# 获取事件MainGame.window.fill(constants.BG_COLOR)self.drawChessboard()#MainGame.button_go.draw_button()self.piecesDisplay()self.VictoryOrDefeat()puterplay()self.getEvent()pygame.display.update()pygame.display.flip()def drawChessboard(self):mid_end_y = MainGame.Start_Y + 4 * MainGame.Line_Spanmin_start_y = MainGame.Start_Y + 5 * MainGame.Line_Spanfor i in range(0, 9):x = MainGame.Start_X + i * MainGame.Line_Spanif i==0 or i ==8:y = MainGame.Start_Y + i * MainGame.Line_Spanpygame.draw.line(MainGame.window, constants.BLACK, [x, MainGame.Start_Y], [x, MainGame.Max_Y], 1)else:pygame.draw.line(MainGame.window, constants.BLACK, [x, MainGame.Start_Y], [x, mid_end_y], 1)pygame.draw.line(MainGame.window, constants.BLACK, [x, min_start_y], [x, MainGame.Max_Y], 1)for i in range(0, 10):x = MainGame.Start_X + i * MainGame.Line_Spany = MainGame.Start_Y + i * MainGame.Line_Spanpygame.draw.line(MainGame.window, constants.BLACK, [MainGame.Start_X, y], [MainGame.Max_X, y], 1)speed_dial_start_x = MainGame.Start_X + 3 * MainGame.Line_Spanspeed_dial_end_x = MainGame.Start_X + 5 * MainGame.Line_Spanspeed_dial_y1 = MainGame.Start_Y + 0 * MainGame.Line_Spanspeed_dial_y2 = MainGame.Start_Y + 2 * MainGame.Line_Spanspeed_dial_y3 = MainGame.Start_Y + 7 * MainGame.Line_Spanspeed_dial_y4 = MainGame.Start_Y + 9 * MainGame.Line_Spanpygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y1], [speed_dial_end_x, speed_dial_y2], 1)pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y2],[speed_dial_end_x, speed_dial_y1], 1)pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y3],[speed_dial_end_x, speed_dial_y4], 1)pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y4],[speed_dial_end_x, speed_dial_y3], 1)def piecesInit(self):MainGame.piecesList.append(pieces.Rooks(MainGame.player2Color, 0,0))MainGame.piecesList.append(pieces.Rooks(MainGame.player2Color, 8, 0))MainGame.piecesList.append(pieces.Elephants(MainGame.player2Color, 2, 0))MainGame.piecesList.append(pieces.Elephants(MainGame.player2Color, 6, 0))MainGame.piecesList.append(pieces.King(MainGame.player2Color, 4, 0))MainGame.piecesList.append(pieces.Knighs(MainGame.player2Color, 1, 0))MainGame.piecesList.append(pieces.Knighs(MainGame.player2Color, 7, 0))MainGame.piecesList.append(pieces.Cannons(MainGame.player2Color, 1, 2))MainGame.piecesList.append(pieces.Cannons(MainGame.player2Color, 7, 2))MainGame.piecesList.append(pieces.Mandarins(MainGame.player2Color, 3, 0))MainGame.piecesList.append(pieces.Mandarins(MainGame.player2Color, 5, 0))MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 0, 3))MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 2, 3))MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 4, 3))MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 6, 3))MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 8, 3))MainGame.piecesList.append(pieces.Rooks(MainGame.player1Color, 0, 9))MainGame.piecesList.append(pieces.Rooks(MainGame.player1Color, 8, 9))MainGame.piecesList.append(pieces.Elephants(MainGame.player1Color, 2, 9))MainGame.piecesList.append(pieces.Elephants(MainGame.player1Color, 6, 9))MainGame.piecesList.append(pieces.King(MainGame.player1Color, 4, 9))MainGame.piecesList.append(pieces.Knighs(MainGame.player1Color, 1, 9))MainGame.piecesList.append(pieces.Knighs(MainGame.player1Color, 7, 9))MainGame.piecesList.append(pieces.Cannons(MainGame.player1Color, 1, 7))MainGame.piecesList.append(pieces.Cannons(MainGame.player1Color, 7, 7))MainGame.piecesList.append(pieces.Mandarins(MainGame.player1Color, 3, 9))MainGame.piecesList.append(pieces.Mandarins(MainGame.player1Color, 5, 9))MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 0, 6))MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 2, 6))MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 4, 6))MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 6, 6))MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 8, 6))def piecesDisplay(self):for item in MainGame.piecesList:item.displaypieces(MainGame.window)#MainGame.window.blit(item.image, item.rect)def getEvent(self):# 获取所有的事件eventList = pygame.event.get()for event in eventList:if event.type == pygame.QUIT:self.endGame()elif event.type == pygame.MOUSEBUTTONDOWN:pos = pygame.mouse.get_pos()mouse_x = pos[0]mouse_y = pos[1]if (mouse_x > MainGame.Start_X - MainGame.Line_Span / 2 and mouse_x < MainGame.Max_X + MainGame.Line_Span / 2) and ( mouse_y > MainGame.Start_Y - MainGame.Line_Span / 2 and mouse_y < MainGame.Max_Y + MainGame.Line_Span / 2):# print( str(mouse_x) + "" + str(mouse_y))# print(str(MainGame.Putdownflag))if MainGame.Putdownflag != MainGame.player1Color:returnclick_x = round((mouse_x - MainGame.Start_X) / MainGame.Line_Span)click_y = round((mouse_y - MainGame.Start_Y) / MainGame.Line_Span)click_mod_x = (mouse_x - MainGame.Start_X) % MainGame.Line_Spanclick_mod_y = (mouse_y - MainGame.Start_Y) % MainGame.Line_Spanif abs(click_mod_x - MainGame.Line_Span / 2) >= 5 and abs(click_mod_y - MainGame.Line_Span / 2) >= 5:# print("有效点:x="+str(click_x)+" y="+str(click_y))# 有效点击点self.PutdownPieces(MainGame.player1Color, click_x, click_y)else:print("out")if MainGame.button_go.is_click():#self.restart()print("button_go click")else:print("button_go click out")def PutdownPieces(self, t, x, y):selectfilter=list(filter(lambda cm: cm.x == x and cm.y == y and cm.player == MainGame.player1Color,MainGame.piecesList)) if len(selectfilter):MainGame.piecesSelected = selectfilter[0]returnif MainGame.piecesSelected :#print("1111")arr = pieces.listPiecestoArr(MainGame.piecesList)if MainGame.piecesSelected.canmove(arr, x, y):self.PiecesMove(MainGame.piecesSelected, x, y)MainGame.Putdownflag = MainGame.player2Colorelse:fi = filter(lambda p: p.x == x and p.y == y, MainGame.piecesList)listfi = list(fi)if len(listfi) != 0:MainGame.piecesSelected = listfi[0]def PiecesMove(self,pieces, x , y):for item in MainGame.piecesList:if item.x ==x and item.y == y:MainGame.piecesList.remove(item)pieces.x = xpieces.y = yprint("move to " +str(x) +" "+str(y))return Truedef Computerplay(self):if MainGame.Putdownflag == MainGame.player2Color:print("轮到电脑了")computermove = computer.getPlayInfo(MainGame.piecesList)#if computer==None:#returnpiecemove = Nonefor item in MainGame.piecesList:if item.x == computermove[0] and item.y == computermove[1]:piecemove= itemself.PiecesMove(piecemove, computermove[2], computermove[3])MainGame.Putdownflag = MainGame.player1Color#判断游戏胜利def VictoryOrDefeat(self):txt =""result = [MainGame.player1Color,MainGame.player2Color]for item in MainGame.piecesList:if type(item) ==pieces.King:if item.player == MainGame.player1Color:result.remove(MainGame.player1Color)if item.player == MainGame.player2Color:result.remove(MainGame.player2Color)if len(result)==0:returnif result[0] == MainGame.player1Color :txt = "失败!"else:txt = "胜利!"MainGame.window.blit(self.getTextSuface("%s" % txt), (constants.SCREEN_WIDTH - 100, 200))MainGame.Putdownflag = constants.overColordef getTextSuface(self, text):pygame.font.init()# print(pygame.font.get_fonts())font = pygame.font.SysFont('kaiti', 18)txt = font.render(text, True, constants.TEXT_COLOR)return txtdef endGame(self):print("exit")exit()if __name__ == '__main__':MainGame().start_game()constants.py 数据常量import pygameSCREEN_WIDTH=900SCREEN_HEIGHT=650Start_X = 50Start_Y = 50Line_Span = 60player1Color = 1player2Color = 2overColor = 3BG_COLOR=pygame.Color(200, 200, 200)Line_COLOR=pygame.Color(255, 255, 200)TEXT_COLOR=pygame.Color(255, 0, 0)# 定义颜⾊BLACK = ( 0, 0, 0)WHITE = (255, 255, 255)RED = (255, 0, 0)GREEN = ( 0, 255, 0)BLUE = ( 0, 0, 255)repeat = 0pieces_images = {'b_rook': pygame.image.load("imgs/s2/b_c.gif"),'b_elephant': pygame.image.load("imgs/s2/b_x.gif"),'b_king': pygame.image.load("imgs/s2/b_j.gif"),'b_knigh': pygame.image.load("imgs/s2/b_m.gif"),'b_mandarin': pygame.image.load("imgs/s2/b_s.gif"),'b_cannon': pygame.image.load("imgs/s2/b_p.gif"),'b_pawn': pygame.image.load("imgs/s2/b_z.gif"),'r_rook': pygame.image.load("imgs/s2/r_c.gif"),'r_elephant': pygame.image.load("imgs/s2/r_x.gif"),'r_king': pygame.image.load("imgs/s2/r_j.gif"),'r_knigh': pygame.image.load("imgs/s2/r_m.gif"),'r_mandarin': pygame.image.load("imgs/s2/r_s.gif"),'r_cannon': pygame.image.load("imgs/s2/r_p.gif"),'r_pawn': pygame.image.load("imgs/s2/r_z.gif"),}pieces.py 棋⼦类,⾛法,import pygameimport constantsclass Pieces():def __init__(self, player, x, y):self.imagskey = self.getImagekey()self.image = constants.pieces_images[self.imagskey]self.x = xself.y = yself.player = playerself.rect = self.image.get_rect()self.rect.left = constants.Start_X + x * constants.Line_Span - self.image.get_rect().width / 2self.rect.top = constants.Start_Y + y * constants.Line_Span - self.image.get_rect().height / 2def displaypieces(self,screen):#print(str(self.rect.left))self.rect.left = constants.Start_X + self.x * constants.Line_Span - self.image.get_rect().width / 2 self.rect.top = constants.Start_Y + self.y * constants.Line_Span - self.image.get_rect().height / 2 screen.blit(self.image,self.rect);#self.image = self.images#MainGame.window.blit(self.image,self.rect)def canmove(self, arr, moveto_x, moveto_y):passdef getImagekey(self):return Nonedef getScoreWeight(self,listpieces):return Noneclass Rooks(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_rook"else:return "b_rook"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y:return Falseif arr[moveto_x][moveto_y] ==self.player :return Falseif self.x == moveto_x:step = -1 if self.y > moveto_y else 1for i in range(self.y +step, moveto_y, step):if arr[self.x][i] !=0 :return False#print(" move y")return Trueif self.y == moveto_y:step = -1 if self.x > moveto_x else 1for i in range(self.x + step, moveto_x, step):if arr[i][self.y] != 0:return Falsereturn Truedef getScoreWeight(self, listpieces):score = 11return scoreclass Knighs(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_knigh"else:return "b_knigh"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y:return Falseif arr[moveto_x][moveto_y] == self.player:return False#print(str(self.x) +""+str(self.y))move_x = moveto_x-self.xmove_y = moveto_y - self.yif abs(move_x) == 1 and abs(move_y) == 2:step = 1 if move_y > 0 else -1if arr[self.x][self.y + step] == 0:return Trueif abs(move_x) == 2 and abs(move_y) == 1:step = 1 if move_x >0 else -1if arr[self.x +step][self.y] ==0 :return Truedef getScoreWeight(self, listpieces):score = 5return scoreclass Elephants(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_elephant"else:return "b_elephant"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y:return Falseif arr[moveto_x][moveto_y] == self.player:return Falseif self.y <=4 and moveto_y >=5 or self.y >=5 and moveto_y <=4: return Falsemove_x = moveto_x - self.xmove_y = moveto_y - self.yif abs(move_x) == 2 and abs(move_y) == 2:step_x = 1 if move_x > 0 else -1step_y = 1 if move_y > 0 else -1if arr[self.x + step_x][self.y + step_y] == 0:return Truedef getScoreWeight(self, listpieces):score = 2return scoreclass Mandarins(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_mandarin"else:return "b_mandarin"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y: return Falseif arr[moveto_x][moveto_y] == self.player:return Falseif moveto_x <3 or moveto_x >5:return Falseif moveto_y > 2 and moveto_y < 7:return Falsemove_x = moveto_x - self.xmove_y = moveto_y - self.yif abs(move_x) == 1 and abs(move_y) == 1:return Truedef getScoreWeight(self, listpieces):score = 2return scoreclass King(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_king"else:return "b_king"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y: return Falseif arr[moveto_x][moveto_y] == self.player:return Falseif moveto_x < 3 or moveto_x > 5:return Falseif moveto_y > 2 and moveto_y < 7:return Falsemove_x = moveto_x - self.xmove_y = moveto_y - self.yif abs(move_x) + abs(move_y) == 1:return Truedef getScoreWeight(self, listpieces):score = 150return scoreclass Cannons(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_cannon"else:return "b_cannon"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y: return Falseif arr[moveto_x][moveto_y] == self.player:return Falseoverflag = Falseif self.x == moveto_x:step = -1 if self.y > moveto_y else 1for i in range(self.y + step, moveto_y, step): if arr[self.x][i] != 0:if overflag:return Falseelse:overflag = Trueif overflag and arr[moveto_x][moveto_y] == 0: return Falseif not overflag and arr[self.x][moveto_y] != 0: return Falsereturn Trueif self.y == moveto_y:step = -1 if self.x > moveto_x else 1for i in range(self.x + step, moveto_x, step):if arr[i][self.y] != 0:if overflag:return Falseelse:overflag = Trueif overflag and arr[moveto_x][moveto_y] == 0:return Falseif not overflag and arr[moveto_x][self.y] != 0:return Falsereturn Truedef getScoreWeight(self, listpieces):score = 6return scoreclass Pawns(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_pawn"else:return "b_pawn"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y:return Falseif arr[moveto_x][moveto_y] == self.player:return Falsemove_x = moveto_x - self.xmove_y = moveto_y - self.yif self.player == constants.player1Color:if self.y > 4 and move_x != 0 :return Falseif move_y > 0:return Falseelif self.player == constants.player2Color:if self.y <= 4 and move_x != 0 :return Falseif move_y < 0:return Falseif abs(move_x) + abs(move_y) == 1:return Truedef getScoreWeight(self, listpieces):score = 2return scoredef listPiecestoArr(piecesList):arr = [[0 for i in range(10)] for j in range(9)]for i in range(0, 9):for j in range(0, 10):if len(list(filter(lambda cm: cm.x == i and cm.y == j and cm.player == constants.player1Color, piecesList))):arr[i][j] = constants.player1Colorelif len(list(filter(lambda cm: cm.x == i and cm.y == j and cm.player == constants.player2Color, piecesList))):arr[i][j] = constants.player2Colorreturn arrcomputer.py 电脑⾛法计算import constants#import timefrom pieces import listPiecestoArrdef getPlayInfo(listpieces):pieces = movedeep(listpieces ,1 ,constants.player2Color)return [pieces[0].x,pieces[0].y, pieces[1], pieces[2]]def movedeep(listpieces, deepstep, player):arr = listPiecestoArr(listpieces)listMoveEnabel = []for i in range(0, 9):for j in range(0, 10):for item in listpieces:if item.player == player and item.canmove(arr, i, j):#标记是否有⼦被吃如果被吃在下次循环时需要补会piecesremove = Nonefor itembefore in listpieces:if itembefore.x == i and itembefore.y == j:piecesremove= itembeforebreakif piecesremove != None:listpieces.remove(piecesremove)#记录移动之前的位置move_x = item.xmove_y = item.yitem.x = iitem.y = j#print(str(move_x) + "," + str(move_y) + "," + str(item.x) + " , " + str(item.y))scoreplayer1 = 0scoreplayer2 = 0for itemafter in listpieces:if itemafter.player == constants.player1Color:scoreplayer1 += itemafter.getScoreWeight(listpieces)elif itemafter.player == constants.player2Color:scoreplayer2 += itemafter.getScoreWeight(listpieces)#print("得分:"+item.imagskey +", "+str(len(moveAfterListpieces))+","+str(i)+","+str(j)+"," +str(scoreplayer1) +" , "+ str(scoreplayer2) )#print(str(deepstep))#如果得⼦判断对⾯是否可以杀过来,如果⼜被杀,⽽且⼦⼒评分低,则不⼲arrkill = listPiecestoArr(listpieces)if scoreplayer2 > scoreplayer1 :for itemkill in listpieces:if itemkill.player == constants.player1Color and itemkill.canmove(arrkill, i, j):scoreplayer2=scoreplayer1if deepstep > 0 :nextplayer = constants.player1Color if player == constants.player2Color else constants.player2Colornextpiecesbest= movedeep(listpieces, deepstep -1, nextplayer)listMoveEnabel.append([item, i, j, nextpiecesbest[3], nextpiecesbest[4], nextpiecesbest[5]])else:#print(str(len(listpieces)))#print("得分:" + item.imagskey + ", " + str(len(listpieces)) + "," + str(move_x) + "," + str(move_y) + "," + str(i) + " , " + str(j))if player == constants.player2Color:listMoveEnabel.append([item, i, j, scoreplayer1, scoreplayer2, scoreplayer1 - scoreplayer2])else:listMoveEnabel.append([item, i, j, scoreplayer1, scoreplayer2, scoreplayer2 - scoreplayer1])#print("得分:"+str(scoreplayer1))item.x = move_xitem.y = move_yif piecesremove != None:listpieces.append(piecesremove)list_scorepalyer1 = sorted(listMoveEnabel, key=lambda tm: tm[5], reverse=True)piecesbest = list_scorepalyer1[0]if deepstep ==1 :print(list_scorepalyer1)return piecesbest以上就是本次分享,另外很多⼈在学习Python的过程中,往往因为遇问题解决不了或者没好的教程从⽽导致⾃⼰放弃,为此我整理啦从基础的python脚本到web开发、爬⾍、django、数据挖掘等【PDF等】需要的可以进Python全栈开发交流.裙:⼀久武其⽽⽽流⼀思(数字的谐⾳)转换下可以找到了,⾥⾯有最新Python教程项⽬可拿,不懂的问题有⽼司机解决哦,⼀起相互监督共同进步本⽂的⽂字及图⽚来源于⽹络加上⾃⼰的想法,仅供学习、交流使⽤,不具有任何商业⽤途,版权归原作者所有,如有问题请及时联系我们以作处理。
C语言程序设计附源代码
C语言程序设计附源代码//中国象棋#include<stdio.h>#include<Windows.h>#include<stdlib.h>//定义棋盘int board[10][9] =0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0};//全局变量bool flag;//游戏函数声明void SetCursor(int, int); // 移动光标位置void PrintChessBoard(; // 打印棋盘void TravelChessBoard(; // 遍历棋子void MoveChess(int, int, int, int); // 移动棋子void DeleteChess(int, int); // 吃子bool CanMove(int, int, int, int); // 判断走法是否合理bool IsKing(int, int, int, int); // 是否将帅相对bool IsOver(; // 游戏是否结束//主函数int mainPrintChessBoard(;TravelChessBoard(;return 0;//打印棋盘void PrintChessBoardprintf("欢迎来到中国象棋\n");printf(" 1 2 3 4 5 6 7 8 9\n");printf(" +-----------------+\n");for(int i=0; i<9; i++) printf("%d,",i+1);for(int j=0; j<9; j++) switch(board[i][j]) case 0:printf(" ");break;case 1:printf("帅");break;case 2:printf("将");break;case 3:printf("兵");break;case 4:printf("马");break;printf("象");break;case 6:printf("炮");break;case 7:printf("车");break;}printf(" ");}printf(",\n");}printf(" +-----------------+\n"); //寻找棋子void TravelChessBoardwhile(!IsOver()//玩家1pswh = 1;。
C语言编写象棋软件源代码
"bmp\\bju.wfb","bmp\\bma.wfb","bmp\\bxiang.wfb","bmp\\bshi.wfb",
"bmp\\bjiang.wfb","bmp\\bpao.wfb","bmp\\bbin.wfb"
};
char *boardfile[10][9]={
{"bmp\\11.wfb","bmp\\1t.wfb","bmp\\1t.wfb","bmp\\14.wfb","bmp\\15.wfb","bmp\\16.wfb","bmp\\1t.wfb","bmp\\1t.wfb","bmp\\19.wfb"},
#define RED_DO 0x3900
#define RED_UNDO 0x1000
#define BLACK_UP 0x4800
#define BLACK_DOWN 0x5000
#define BLACK_LEFT 0x4b00
#define BLACK_RIGHT 0x4d00
#define BLACK_DO 0x1c00
{"bmp\\81.wfb","bmp\\8a.wfb","bmp\\8t.wfb","bmp\\84.wfb","bmp\\85.wfb","bmp\\86.wfb","bmp\\8t.wfb","bmp\\8a.wfb","bmp\\89.wfb"},
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
摘要象棋程序可以分为两大部分:人工智能和界面程序辅助。
人工智能的主要部分,反映了计算机下象棋的想法,电脑怎么想,最好的方法去完成下一步,优先搜索算法进行搜索,和各种可能的行动,评估,选择胜利面最大的一步;界面和程序协助部分主要是界面友好,以更好地适应用户下象棋的想法。
本文研究了中国象棋在电脑中如何表示,然后讨论如何产生走法的一系列相关技术。
使用MFC架构和Visual C + +开发工具,实现一定技能的中国象棋人机对弈功能。
关键词:中国象棋;人工智能;下棋Title The Design And Realize of human-computerChess GameAbstractChess program can be divided into two major auxiliary artificial intelligence and interface program. The AI part of the main reflected computer chess ideas, computer how to think and go to the best method to complete the next step, first search algorithm to search, and a variety of possible moves, valuations, choose victory surface step; the interface and the program assisted some of the major user-friendly game of chess by the previous step, to better adjust the chess ideas.This paper studies the Chinese chess computer, and then discuss how to generate a series of related moves. MFC architecture and Visual C development tools, to achieve a certain chess skills, Chinese chess, human-computer chess program.Keywords: Chess; artificial intelligence; chess目次1 引言 (1)1.1 象棋设计背景和研究意义 (1)1.2象棋设计研究方法 (1)2需求分析 (3)2.1 界面要求 (3)2.2规则要求 (3)2.3判定输赢 (4)3系统设计与实现 (6)3.1系统模块划分 (6)3.2系统主要流程图 (6)3.3相关数据定义 (8)4 系统测试运行 (10)4.1测试方案设计 (10)4.2测试过程及结果 (10)4.3系统的优缺点分析及改进方案 (11)4.4系统性能分析 (11)结论 (12)致谢 (13)参考文献 (14)1引言1.1 象棋设计背景和研究意义经过二十年的发展,电脑游戏行业已成为最重要的工作之一,以跟上全球电影,电视,音乐和其他娱乐行业,其年销售额超过好莱坞的全年收入的步伐。
游戏作为一种休闲活动。
由于早期人类社会的生产力和技术的限制,只有一些户外游戏。
随着生产力的发展和技术进步,一种新的方式来播放 - 视频游戏也将诞生。
当计算机的发明,电子游戏和另外一个新的载体。
在计算机行业作为一个整体的推动下,通过不断创新,开发电子游戏。
由于计算机的发明到发展到各个领域,成为每天的工作和生活这一进程的重要组成部分,电子游戏已逐渐渗透我们每个人的休闲活动。
电脑已经流行,人们可以使用的计算机程序编辑,开发自己的游戏,不再是一个梦想。
事实上,从游戏软件销售的占个人电脑软件市场份额约80%。
棋类游戏是休闲游戏,以及阶段的角色扮演游戏和实时战略游戏和其他游戏比上手快,比赛时间很短,但也有利于用户的放松,喜欢的人,尤其是棋类游戏,方便,快,操作简单,在休闲和娱乐活动中占主导地位。
中国象棋作为中华民族的古老文化的代表之一,不仅有悠久的历史和广泛的基础,作为一个智力活动,中国象棋开始走向世界。
随着计算机处理速度的迅速增加,提出一个长期的问题:计算机是否会超越人类?计算机击败世界国际象棋大师,计算机比人强吗?人工智能是一个高度跨学科的,其中心任务是研究如何使电脑做过去依靠人类的智慧可以做的工作。
因此,在游戏开发过程中的人工智能技术的研究自然成为行业的一个热门的研究方向。
1.2 象棋设计研究方法本程序的核心设计包括象棋的表示,人工智能算法的实现,以及在整个游戏的界面和程序内的MFC类库开发的辅助部分,使用Visual C++ 开发工具,使游戏开发更方便,使用人工智能相关搜索算法,用人工智能的方法来产生计算机走法,从而提高整个游戏的功能。
本文的目标是要实现具有一定的象棋水平和互动与友好的中国象棋人机对弈象棋程序。
整个程序可分为两个主要部分:人工智能算法设计一、如何让电脑下中国象棋游戏,其中涉及的基本理论和人机下棋的想法是该方案的核心部分,但也是这个项目的重点研究的一部分。
二,界面和程序计算机辅助设计光象棋引擎不能满足人机交互的基本要求,因此需要一个框架(接口)为载体。
下面分别介绍每个部分的实现。
由于界面和程序的辅助部分涉及的内容广泛和复杂,本文只介绍了关键的部分。
2 需求分析2.1界面要求如图棋子走的地方,被称为“棋盘”。
矩形平面画,共有90个点,9个平行的垂直线和平行的水平线10相交点,在交叉点上的碎片。
中间部分的第五,第六两条水平线板画垂直线之间的空白地带称为“河界”。
水平之间的第四至第六部分的两端,中间的两端构成的斜交叉线的“米”字框,称为“九宫”(它恰好有九个交叉点)。
棋盘被河界分为两等份。
为方便游戏记录和学习中国象棋,现行的规则:根据与中国数字由右至左的9个垂直线 - 个代表红方各垂直线,用阿拉伯数字'1'到'9 “代表黑色每个竖条。
中国象棋的开始之前,红色,黑色和双方应该是一个棋子放置在指定的位置。
任何棋子每走一步,进就写“进”退就写“退”之类的车,侧身上写“平”。
2.2 规则要求1.下棋在游戏中,由红棋先走,双方轮流走,直到一个赢家,每个人下棋,棋子从一个交叉点到另一个空的交叉点,或吃对方的棋子占领叉点,被认为是走了一着。
每一方都走过之后,被称为一个回合。
2.所有的棋子移动如下:帅()每个被允许走一步前进,后退,水平可以,但不能出了“九宫”。
帅和将不会被允许在同一条直线上直接对面,如果一方已经占用的,必须避免。
士每次只允许沿“九宫斜线一步,可以撤退。
象不能过河的边界,可进可退俗称相走田字。
当另一个在卍中心,俗称赛象眼,马走日,可以撤退到,当地另一个棋子挡住,俗称为”蹩马腿不能走过去,车可直进直退,横走,而不限步数。
跑在不吃子的时候,走法同车一样; 兵(卒)在没有过"河界"前,每着只许向前直走一步;过河后,也可以交叉步,但能不能转回来。
3.吃子走一招,如果自己的棋子的位置,有其他棋子存在,你可以把他吃掉而占领那个位置。
只有跑必须从一块分开(无论哪一方)跳吃,俗称“炮翻山”之称。
除了帅,其他字都可以让对方吃,或主动被吃。
4.将军、应将、将死一方攻击对方的帅(将),下一步将要吃掉它,被称为“将军”。
“将军”必须立即“应将”,使用自卫,以解决“将”的状态。
如果在“将军”不能”应将,即使是”死“。
2.3 判定输赢1.结果游戏时,有下列情形之一,即使输棋,对方的胜利:(一)帅被对方“将死”(二)帅(将)被“将军”,彼此无法避免(帅)直接对面;(三)“被困死”;(四)不规定的时限内,未走完应走的数量;(五)超过比赛规定的时限(一般为15分钟);(六)封棋着法有误;(七)走棋举动违反了禁令,应当变着而不变;(八)在相同的游戏棋中,单方面的第三个“违例”;(九)自称认输;(10)违反纪律。
和棋,有下列情形之一的,即使是平局:(一)从理论上确认当事人没有双赢的局面可能;(二)建议和棋,并应使双方机会均等。
世卫组织第一次抽签被拒绝(口头不同意,或走出去圆一招,被拒绝),由对方(也否认),不得再次提出,但下列(三)未提及( D)同属提到的特殊规定,不受此限。
如果双方提及,等权数,可以由任何一方再次提及。
提到和党明确指出,在另一方面,它不能撤回其报价。
只要是一方提和,另一方当事人已声明,双方同意不准回去。
此外,只提前按时钟的另一侧。
(三)双方下棋循环反复达三次,在象棋的有关规定,可由任何一方提议作和,经审查局面属实,即使另一方不同意,裁判员也有权判为和棋。
如果双方都没有提及,并循环反复的情况仍在继续,裁判不同意,决定判处各方的权利和行走方法有重复的情况与周期无关,你不能按照本条处理。
(四)符合60轮规则“(也称为自然限)。
3 系统设计与实现3.1 系统模块划分本系统主要功能模块如图:3.2 系统主要流程图系统初始化流程图计算机查找走法流程图3.3 相关数据定义const int MAN=0; //人const int COM=1; //计算机const int RED=0; //红方const int BLACK=1; //黑方const int RED_K=0; //红帅const int RED_S=1; //仕const int RED_X=2; //相const int RED_M=3; //马const int RED_J=4; //车const int RED_P=5; //炮const int RED_B=6; //兵const int BLACK_K=7; //黑将const int BLACK_S=8; //士const int BLACK_X=9; //象const int BLACK_M=10; //马const int BLACK_J=11; //车const int BLACK_P=12; //炮const int BLACK_B=13; //卒//把棋子序号转换为对应图标的序号const int ManToIcon[33]= {0,1,1,2,2,3,3,4,4,5,5, 6,6,6, 6,6,7,8,8,9,9,10,10,11,11,12,12,13,13,13,13,13,-1};//棋子类型与图标的序号相同#define ManToType ManToIconconst int ManToType7[33]= {0,1,1,2,2,3,3,4,4,5,5,6,6,6,6,6,0,1,1,2,2,3,3,4,4,5,5,6,6,6,6,6,-1};//给出棋子序号!!,判断是红是黑const int SideOfMan[33]= {0,0,0,0,0,0,0,0,0,0,0,0, 0,0, 0,0 ,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1};4 系统测试运行4.1测试方案设计编码过程完成后,最重要的是对系统的测试工作,系统测试阶段,有两个时期,通常在第一段做单元测试,另一段做全面系统测试。