五子棋源代码

合集下载

Java五子棋游戏源代码(人机对战)

Java五子棋游戏源代码(人机对战)

//Java编程:五子棋游戏源代码import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;import java.io.PrintStream;import javax.swing.JComponent;import javax.swing.JPanel;/**main方法创建了ChessFrame类的一个实例对象(cf),*并启动屏幕显示显示该实例对象。

**/public class FiveChessAppletDemo {public static void main(String args[]){ChessFrame cf = new ChessFrame();cf.show();}}/**类ChessFrame主要功能是创建五子棋游戏主窗体和菜单**/class ChessFrame extends JFrame implements ActionListener { private String[] strsize={"20x15","30x20","40x30"};private String[] strmode={"人机对弈","人人对弈"};public static boolean iscomputer=true,checkcomputer=true; private int width,height;private ChessModel cm;private MainPanel mp;//构造五子棋游戏的主窗体public ChessFrame() {this.setTitle("五子棋游戏");cm=new ChessModel(1);mp=new MainPanel(cm);Container con=this.getContentPane();con.add(mp,"Center");this.setResizable(false);this.addWindowListener(new ChessWindowEvent());MapSize(20,15);JMenuBar mbar = new JMenuBar();this.setJMenuBar(mbar);JMenu gameMenu = new JMenu("游戏");mbar.add(makeMenu(gameMenu, new Object[] {"开局", "棋盘","模式", null, "退出"}, this));JMenu lookMenu =new JMenu("视图");mbar.add(makeMenu(lookMenu,new Object[] {"Metal","Motif","Windows"},this));JMenu helpMenu = new JMenu("帮助");mbar.add(makeMenu(helpMenu, new Object[] {"关于"}, this));}//构造五子棋游戏的主菜单public JMenu makeMenu(Object parent, Object items[], Object target){ JMenu m = null;if(parent instanceof JMenu)m = (JMenu)parent;else if(parent instanceof String)m = new JMenu((String)parent);elsereturn null;for(int i = 0; i < items.length; i++)if(items[i] == null)m.addSeparator();else if(items[i] == "棋盘"){JMenu jm = new JMenu("棋盘");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int j=0;j<strsize.length;j++){rmenu=makeRadioButtonMenuItem(strsize[j],target);if (j==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}else if(items[i] == "模式"){JMenu jm = new JMenu("模式");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int h=0;h<strmode.length;h++){rmenu=makeRadioButtonMenuItem(strmode[h],target);if(h==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}elsem.add(makeMenuItem(items[i], target));return m;}//构造五子棋游戏的菜单项public JMenuItem makeMenuItem(Object item, Object target){ JMenuItem r = null;if(item instanceof String)r = new JMenuItem((String)item);else if(item instanceof JMenuItem)r = (JMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}//构造五子棋游戏的单选按钮式菜单项public JRadioButtonMenuItem makeRadioButtonMenuItem( Object item, Object target){JRadioButtonMenuItem r = null;if(item instanceof String)r = new JRadioButtonMenuItem((String)item);else if(item instanceof JRadioButtonMenuItem)r = (JRadioButtonMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}public void MapSize(int w,int h){setSize(w * 20+50 , h * 20+100 );if(this.checkcomputer)this.iscomputer=true;elsethis.iscomputer=false;mp.setModel(cm);mp.repaint();}public boolean getiscomputer(){return this.iscomputer;}public void restart(){int modeChess = cm.getModeChess();if(modeChess <= 3 && modeChess >= 1){cm = new ChessModel(modeChess);MapSize(cm.getWidth(),cm.getHeight());}else{System.out.println("\u81EA\u5B9A\u4E49");}}public void actionPerformed(ActionEvent e){String arg=e.getActionCommand();try{if (arg.equals("Windows"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");else if(arg.equals("Motif"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");elseUIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel" ); SwingUtilities.updateComponentTreeUI(this);}catch(Exception ee){}if(arg.equals("20x15")){this.width=20;this.height=15;cm=new ChessModel(1);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("30x20")){this.width=30;this.height=20;cm=new ChessModel(2);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("40x30")){this.width=40;this.height=30;cm=new ChessModel(3);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人机对弈")){this.checkcomputer=true;this.iscomputer=true;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人人对弈")){this.checkcomputer=false;this.iscomputer=false;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("开局")){restart();}if(arg.equals("关于"))JOptionPane.showMessageDialog(this, "五子棋游戏测试版本", "关于", 0);if(arg.equals("退出"))System.exit(0);}}/**类ChessModel实现了整个五子棋程序算法的核心*/class ChessModel {//棋盘的宽度、高度、棋盘的模式(如20×15)private int width,height,modeChess;//棋盘方格的横向、纵向坐标private int x=0,y=0;//棋盘方格的横向、纵向坐标所对应的棋子颜色,//数组arrMapShow只有3个值:1,2,3,-5,//其中1代表该棋盘方格上下的棋子为黑子,//2代表该棋盘方格上下的棋子为白子,//3代表为该棋盘方格上没有棋子,//-5代表该棋盘方格不能够下棋子private int[][] arrMapShow;//交换棋手的标识,棋盘方格上是否有棋子的标识符private boolean isOdd,isExist;public ChessModel() {}//该构造方法根据不同的棋盘模式(modeChess)来构建对应大小的棋盘public ChessModel(int modeChess){this.isOdd=true;if(modeChess == 1){PanelInit(20, 15, modeChess);}if(modeChess == 2){PanelInit(30, 20, modeChess);}if(modeChess == 3){PanelInit(40, 30, modeChess);}}//按照棋盘模式构建棋盘大小private void PanelInit(int width, int height, int modeChess){this.width = width;this.height = height;this.modeChess = modeChess;arrMapShow = new int[width+1][height+1];for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){arrMapShow[i][j] = -5;}}}//获取是否交换棋手的标识符public boolean getisOdd(){return this.isOdd;}//设置交换棋手的标识符public void setisOdd(boolean isodd){if(isodd)this.isOdd=true;elsethis.isOdd=false;}//获取某棋盘方格是否有棋子的标识值public boolean getisExist(){return this.isExist;}//获取棋盘宽度public int getWidth(){return this.width;}//获取棋盘高度public int getHeight(){return this.height;}//获取棋盘模式public int getModeChess(){return this.modeChess;}//获取棋盘方格上棋子的信息public int[][] getarrMapShow(){return arrMapShow;}//判断下子的横向、纵向坐标是否越界private boolean badxy(int x, int y){if(x >= width+20 || x < 0)return true;return y >= height+20 || y < 0;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public boolean chessExist(int i,int j){if(this.arrMapShow[i][j]==1 || this.arrMapShow[i][j]==2)return true;return false;}//判断该坐标位置是否可下棋子public void readyplay(int x,int y){if(badxy(x,y))return;if (chessExist(x,y))return;this.arrMapShow[x][y]=3;}//在该坐标位置下棋子public void play(int x,int y){if(badxy(x,y))return;if(chessExist(x,y)){this.isExist=true;return;}elsethis.isExist=false;if(getisOdd()){setisOdd(false);this.arrMapShow[x][y]=1;}else{setisOdd(true);this.arrMapShow[x][y]=2;}}//计算机走棋/**说明:用穷举法判断每一个坐标点的四个方向的的最大棋子数,*最后得出棋子数最大值的坐标,下子**/public void computerDo(int width,int height){int max_black,max_white,max_temp,max=0;setisOdd(true);System.out.println("计算机走棋...");for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){if(!chessExist(i,j)){//算法判断是否下子max_white=checkMax(i,j,2);//判断白子的最大值max_black=checkMax(i,j,1);//判断黑子的最大值max_temp=Math.max(max_white,max_black);if(max_temp>max){max=max_temp;this.x=i;this.y=j;}}}}setX(this.x);setY(this.y);this.arrMapShow[this.x][this.y]=2;}//记录电脑下子后的横向坐标public void setX(int x){this.x=x;}//记录电脑下子后的纵向坐标public void setY(int y){this.y=y;}//获取电脑下子的横向坐标public int getX(){return this.x;}//获取电脑下子的纵向坐标public int getY(){return this.y;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public int checkMax(int x, int y,int black_or_white){int num=0,max_num,max_temp=0;int x_temp=x,y_temp=y;int x_temp1=x_temp,y_temp1=y_temp;//judge rightfor(int i=1;i<5;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge leftx_temp1=x_temp;for(int i=1;i<5;i++){x_temp1-=1;if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num<5)max_temp=num;//judge upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge downy_temp1=y_temp;for(int i=1;i<5;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge left_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1-=1;y_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge right_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge right_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge left_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;max_num=max_temp;return max_num;}//判断胜负public boolean judgeSuccess(int x,int y,boolean isodd){ int num=1;int arrvalue;int x_temp=x,y_temp=y;if(isodd)arrvalue=2;elsearrvalue=1;int x_temp1=x_temp,y_temp1=y_temp;//判断右边for(int i=1;i<6;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}//判断左边x_temp1=x_temp;for(int i=1;i<6;i++){if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断上方x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断下方y_temp1=y_temp;for(int i=1;i<6;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断左上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断右下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width) break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断右上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断左下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}if(num==5)return true;return false;}//赢棋后的提示public void showSuccess(JPanel jp){JOptionPane.showMessageDialog(jp,"你赢了,好厉害!","win",RMATION_MESSAGE);}//输棋后的提示public void showDefeat(JPanel jp){JOptionPane.showMessageDialog(jp,"你输了,请重新开始!","lost",RMATION_MESSAGE);}}/**类MainPanel主要完成如下功能:*1、构建一个面板,在该面板上画上棋盘;*2、处理在该棋盘上的鼠标事件(如鼠标左键点击、鼠标右键点击、鼠标拖动等)**/class MainPanel extends JPanelimplements MouseListener,MouseMotionListener{private int width,height;//棋盘的宽度和高度private ChessModel cm;//根据棋盘模式设定面板的大小MainPanel(ChessModel mm){cm=mm;width=cm.getWidth();height=cm.getHeight();addMouseListener(this);}//根据棋盘模式设定棋盘的宽度和高度public void setModel(ChessModel mm){cm = mm;width = cm.getWidth();height = cm.getHeight();}//根据坐标计算出棋盘方格棋子的信息(如白子还是黑子),//然后调用draw方法在棋盘上画出相应的棋子public void paintComponent(Graphics g){super.paintComponent(g);for(int j = 0; j <= height; j++){for(int i = 0; i <= width; i++){int v = cm.getarrMapShow()[i][j];draw(g, i, j, v);}}}//根据提供的棋子信息(颜色、坐标)画棋子public void draw(Graphics g, int i, int j, int v){int x = 20 * i+20;int y = 20 * j+20;//画棋盘if(i!=width && j!=height){g.setColor(Color.white);g.drawRect(x,y,20,20);}//画黑色棋子if(v == 1 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.black);g.fillOval(x-8,y-8,16,16);}//画白色棋子if(v == 2 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.white);g.fillOval(x-8,y-8,16,16);}if(v ==3){g.setColor(Color.cyan);g.drawOval(x-8,y-8,16,16);}}//响应鼠标的点击事件,根据鼠标的点击来下棋,//根据下棋判断胜负等public void mousePressed(MouseEvent evt){int x = (evt.getX()-10) / 20;int y = (evt.getY()-10) / 20;System.out.println(x+" "+y);if (evt.getModifiers()==MouseEvent.BUTTON1_MASK){cm.play(x,y);System.out.println(cm.getisOdd()+" "+cm.getarrMapShow()[x][y]);repaint();if(cm.judgeSuccess(x,y,cm.getisOdd())){cm.showSuccess(this);evt.consume();ChessFrame.iscomputer=false;}//判断是否为人机对弈if(ChessFrame.iscomputer&&!cm.getisExist()){puterDo(cm.getWidth(),cm.getHeight());repaint();if(cm.judgeSuccess(cm.getX(),cm.getY(),cm.getisOdd())){cm.showDefeat(this);evt.consume();}}}}public void mouseClicked(MouseEvent evt){}public void mouseReleased(MouseEvent evt){}public void mouseEntered(MouseEvent mouseevt){}public void mouseExited(MouseEvent mouseevent){}public void mouseDragged(MouseEvent evt){}//响应鼠标的拖动事件public void mouseMoved(MouseEvent moveevt){int x = (moveevt.getX()-10) / 20;int y = (moveevt.getY()-10) / 20;cm.readyplay(x,y);repaint();}}class ChessWindowEvent extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0);}ChessWindowEvent(){}}。

五子棋游戏源代码

五子棋游戏源代码

import java.awt.*;import java.awt.event.*;import java.io.*;import .*;import java.util.*;class clientThread extends Thread {chessClient chessclient;clientThread(chessClient chessclient) {this.chessclient = chessclient;}public void acceptMessage(String recMessage) {if (recMessage.startsWith("/userlist ")) {StringTokenizer userToken = new StringTokenizer(recMessage, " ");int userNumber = 0;erList.removeAll();erChoice.removeAll();erChoice.addItem("所有人");while (userToken.hasMoreTokens()) {String user = (String) userToken.nextToken(" ");if (userNumber > 0 && !user.startsWith("[inchess]")) {erList.add(user);erChoice.addItem(user);}userNumber++;}erChoice.select("所有人");} else if (recMessage.startsWith("/yourname ")) {chessclient.chessClientName = recMessage.substring(10);chessclient.setTitle("Java五子棋客户端" + "用户名:"+ chessclient.chessClientName);} else if (recMessage.equals("/reject")) {try {chessclient.chesspad.statusText.setText("不能加入游戏");chessclient.controlpad.cancelGameButton.setEnabled(false);chessclient.controlpad.joinGameButton.setEnabled(true);chessclient.controlpad.creatGameButton.setEnabled(true);} catch (Exception ef) {chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭");}chessclient.controlpad.joinGameButton.setEnabled(true);} else if (recMessage.startsWith("/peer ")) {chessclient.chesspad.chessPeerName = recMessage.substring(6);if (chessclient.isServer) {chessclient.chesspad.chessColor = 1;chessclient.chesspad.isMouseEnabled = true;chessclient.chesspad.statusText.setText("请黑棋下子");} else if (chessclient.isClient) {chessclient.chesspad.chessColor = -1;chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子...");}} else if (recMessage.equals("/youwin")) {chessclient.isOnChess = false;chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接");chessclient.chesspad.isMouseEnabled = false;} else if (recMessage.equals("/OK")) {chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入...");} else if (recMessage.equals("/error")) {chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入\n");} else {chessclient.chatpad.chatLineArea.append(recMessage + "\n");chessclient.chatpad.chatLineArea.setCaretPosition(chessclient.chatpad.chatLineArea.getText().length());}}public void run() {String message = "";try {while (true) {message = chessclient.in.readUTF();acceptMessage(message);}} catch (IOException es) {}}}public class chessClient extends Frame implements ActionListener, KeyListener { userPad userpad = new userPad();chatPad chatpad = new chatPad();controlPad controlpad = new controlPad();chessPad chesspad = new chessPad();inputPad inputpad = new inputPad();Socket chatSocket;DataInputStream in;DataOutputStream out;String chessClientName = null;String host = null;int port = 4331;boolean isOnChat = false; // 在聊天?boolean isOnChess = false; // 在下棋?boolean isGameConnected = false; // 下棋的客户端连接?boolean isServer = false; // 如果是下棋的主机boolean isClient = false; // 如果是下棋的客户端Panel southPanel = new Panel();Panel northPanel = new Panel();Panel centerPanel = new Panel();Panel westPanel = new Panel();Panel eastPanel = new Panel();chessClient() {super("Java五子棋客户端");setLayout(new BorderLayout());host = controlpad.inputIP.getText();westPanel.setLayout(new BorderLayout());westPanel.add(userpad, BorderLayout.NORTH);westPanel.add(chatpad, BorderLayout.CENTER);westPanel.setBackground(Color.pink);inputpad.inputWords.addKeyListener(this);chesspad.host = controlpad.inputIP.getText();centerPanel.add(chesspad, BorderLayout.CENTER);centerPanel.add(inputpad, BorderLayout.SOUTH);centerPanel.setBackground(Color.pink);controlpad.connectButton.addActionListener(this);controlpad.creatGameButton.addActionListener(this);controlpad.joinGameButton.addActionListener(this);controlpad.cancelGameButton.addActionListener(this);controlpad.exitGameButton.addActionListener(this);controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(false);southPanel.add(controlpad, BorderLayout.CENTER);southPanel.setBackground(Color.pink);addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {if (isOnChat) {try {chatSocket.close();} catch (Exception ed) {}}if (isOnChess || isGameConnected) {try {chesspad.chessSocket.close();} catch (Exception ee) {}}System.exit(0);}public void windowActivated(WindowEvent ea) {}});add(westPanel, BorderLayout.WEST);add(centerPanel, BorderLayout.CENTER);add(southPanel, BorderLayout.SOUTH);pack();setSize(670, 548);setVisible(true);setResizable(false);validate();}public boolean connectServer(String serverIP, int serverPort)throws Exception {try {chatSocket = new Socket(serverIP, serverPort);in = new DataInputStream(chatSocket.getInputStream());out = new DataOutputStream(chatSocket.getOutputStream());clientThread clientthread = new clientThread(this);clientthread.start();isOnChat = true;return true;} catch (IOException ex) {chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序\n");}return false;}public void actionPerformed(ActionEvent e) {if (e.getSource() == controlpad.connectButton) {host = chesspad.host = controlpad.inputIP.getText();try {if (connectServer(host, port)) {chatpad.chatLineArea.setText("");controlpad.connectButton.setEnabled(false);controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);chesspad.statusText.setText("连接成功,请创建游戏或加入游戏");}} catch (Exception ei) {chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序\n");}}if (e.getSource() == controlpad.exitGameButton) {if (isOnChat) {try {chatSocket.close();} catch (Exception ed) {}}if (isOnChess || isGameConnected) {try {chesspad.chessSocket.close();} catch (Exception ee) {}}System.exit(0);}if (e.getSource() == controlpad.joinGameButton) {String selectedUser = erList.getSelectedItem();if (selectedUser == null || selectedUser.startsWith("[inchess]")|| selectedUser.equals(chessClientName)) {chesspad.statusText.setText("必须先选定一个有效用户");} else {try {if (!isGameConnected) {if (chesspad.connectServer(chesspad.host, chesspad.port)) {isGameConnected = true;isOnChess = true;isClient = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/joingame "+ erList.getSelectedItem() + " "+ chessClientName);}} else {isOnChess = true;isClient = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/joingame "+ erList.getSelectedItem() + " "+ chessClientName);}} catch (Exception ee) {isGameConnected = false;isOnChess = false;isClient = false;controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chatpad.chatLineArea.setText("chesspad.connectServer无法连接\n" + ee);}}}if (e.getSource() == controlpad.creatGameButton) {try {if (!isGameConnected) {if (chesspad.connectServer(chesspad.host, chesspad.port)) {isGameConnected = true;isOnChess = true;isServer = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/creatgame "+ "[inchess]" + chessClientName);}} else {isOnChess = true;isServer = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/creatgame "+ "[inchess]" + chessClientName);}} catch (Exception ec) {isGameConnected = false;isOnChess = false;isServer = false;controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);ec.printStackTrace();chatpad.chatLineArea.setText("chesspad.connectServer无法连接\n"+ ec);}}if (e.getSource() == controlpad.cancelGameButton) {if (isOnChess) {chesspad.chessthread.sendMessage("/giveup " + chessClientName);chesspad.chessVictory(-1 * chesspad.chessColor);controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chesspad.statusText.setText("请建立游戏或者加入游戏");}if (!isOnChess) {controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chesspad.statusText.setText("请建立游戏或者加入游戏");}isClient = isServer = false;}}public void keyPressed(KeyEvent e) {TextField inputWords = (TextField) e.getSource();if (e.getKeyCode() == KeyEvent.VK_ENTER) {if (erChoice.getSelectedItem().equals("所有人")) {try {out.writeUTF(inputWords.getText());inputWords.setText("");} catch (Exception ea) {chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接\n");erList.removeAll();erChoice.removeAll();inputWords.setText("");controlpad.connectButton.setEnabled(true);}} else {try {out.writeUTF("/" + erChoice.getSelectedItem()+ " " + inputWords.getText());inputWords.setText("");} catch (Exception ea) {chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接\n");erList.removeAll();erChoice.removeAll();inputWords.setText("");controlpad.connectButton.setEnabled(true);}}}}public void keyTyped(KeyEvent e) {}public void keyReleased(KeyEvent e) {}public static void main(String args[]) {chessClient chessClient = new chessClient();}}。

五子棋源代码

五子棋源代码

/*turboc2.0下编译通过*/#include#include#include#include#define N 15#define B 7#define STOP -10000#define OK 1#define NO 0#define UP 328#define DOWN 336#define LEFT 331#define RIGHT 333/*定义了两个数,n为棋盘的大小。

b为背景颜色的数值*/ int a[N+1][N+1];intzx,zy;int write=1,biaoji=0;structzn{long sum;int y;int x;}w[N+1][N+1],max,max1;void cbar(inti,intx,inty,int r);void map(int a[][]);intgetkey();int key();void zuobiao(intx,inty,inti);inttu(int a[][],int write);intwtu(int a[][],int write);intzhineng(int a[][]);int zh5(inty,intx,int a[][]);long zzh5(int b[][],inti);main(){inti,j;intgdriver=DETECT;intgmode;initgraph(&gdriver,&gmode,);zy=(N+1)/2;for(i=1;i<=N;i++)for(j=1;j<=N;j++)a[i][j]=0;map(a);i=1;while(i){intk,n;k=wtu(a,write);if(k==STOP) goto end;map(a);n=zhineng(a);if(n==STOP) goto end;map(a);}end:;}/* 实现对局的程序,计算全部N*N个格中,最应该填的格子*/ intzhineng(int a[N+1][N+1]){inti,j;int k;max.sum=-1;for(i=0;i<=N;i++)for(j=0;j<+N;j++){w[i][j].sum=0;w[i][j].x=i;w[i][j].y=j;}for(i=1;i<=N-4;i++)for(j=1;j<=N-4;j++){if(k==STOP) return (STOP);}for(i=1;i<=N;i++)for(j=1;j<=N;j++){if(max.sum {max.sum=w[i][j].sum;max.y=i;max.x=j;}else if(max.sum==w[i][j].sum){if(((max.y-zy)*(max.y-zy)+(max.x-zx)*(max.x-zx))>((i-zy)*(i-zy)+(j-zx)*(j-zx))) max.sum=w[i][j].sum;max.y=i;max.x=j;}}if(a[max.y][max.x]==0){a[max.y][max.x]=-1;zy=max.y;zx=max.x;}}/* 转换成5*5的数组,计算出在二十五个格子中,最应该填的格*/ int zh5(inty,intx,int a[N+1][N+1]){inti,j;int b[6][6];long c[13];long d[6][6];long temp;for(i=y;i<=y+4;i++)for(j=x;j<=x+4;j++)b[i+1-y][j+1-x]=a[i][j];c[1]=b[1][1]+b[1][2]+b[1][3]+b[1][4]+b[1][5];c[2]=b[2][1]+b[2][2]+b[2][3]+b[2][4]+b[2][5]; c[3]=b[3][1]+b[3][2]+b[3][3]+b[3][4]+b[3][5]; c[4]=b[4][1]+b[4][2]+b[4][3]+b[4][4]+b[4][5]; c[5]=b[5][1]+b[5][2]+b[5][3]+b[5][4]+b[5][5];c[6]=b[1][1]+b[2][1]+b[3][1]+b[4][1]+b[5][1]; c[7]=b[1][2]+b[2][2]+b[3][2]+b[4][2]+b[5][2]; c[8]=b[1][3]+b[2][3]+b[3][3]+b[4][3]+b[5][3]; c[9]=b[1][4]+b[2][4]+b[3][4]+b[4][4]+b[5][4]; c[10]=b[1][5]+b[2][5]+b[3][5]+b[4][5]+b[5][5];c[11]=b[1][1]+b[2][2]+b[3][3]+b[4][4]+b[5][5]; c[12]=b[1][5]+b[2][4]+b[3][3]+b[4][2]+b[5][1];for(i=1;i<=12;i++){switch(c[i]){case 5:biaoji=1;return(STOP);case -5:biaoji=-1;return(STOP);case -4:c[i]=100000;break;case 4:c[i]=100000;break;case -3:c[i]=150;break;case 3:c[i]=150;break;case -2:c[i]=120;break;case 2:c[i]=100;break;case -1:c[i]=1;break;case 1:c[i]=1;break;default: c[i]=0;}}for(i=1;i<=12;i++){if(c[i]==150)c[i]+=zzh5(b,i);}for(i=1;i<=5;i++)for(j=1;j<=5;j++)d[i][j]=0;for(i=1;i<=5;i++)for(j=1;j<=5;j++){if(i==j) d[i][j]+=c[11];if((i+j)==6) d[i][j]+=c[12];d[i][j]+=c[i]+c[j+5];}for(i=1;i<=5;i++)for(j=1;j<=5;j++){if(b[i][j]!=0)d[i][j]=-2;}max1.sum=-1;max1.y=0;max1.x=0;for(i=1;i<=5;i++)for(j=1;j<=5;j++){if(max1.sum {max1.sum=d[i][j];max1.y=i;max1.x=j;w[i+y-1][j+x-1].sum+=max1.sum;}else if(max1.sum==d[i][j]){if(((i+y-1-zy)*(i+y-1-zy)+(j+x-1-zx)*(j+x-1-zx))>((max1.y+y-1-zy)*(max1.y+y-1-zy)+(max1.x+x-1-zx)* (max1.x+x-1-zx))){max1.sum=d[i][j];max1.y=i;max1.x=j;}}}}long zzh5(int b[6][6],int n){inti,j,k,l,m;switch(n){case 1:i=b[1][1];j=b[1][2];k=b[1][3];l=b[1][4];m=b[1][5];break;case 2:i=b[2][1];j=b[2][2];k=b[2][3];l=b[2][4];m=b[2][5];break;case 3:i=b[3][1];j=b[3][2];k=b[3][3];l=b[3][4];m=b[3][5];break;case 4:i=b[4][1];j=b[4][2];k=b[4][3];l=b[4][4];m=b[4][5];break;case 5:i=b[5][1];j=b[5][2];k=b[5][3];l=b[5][4];m=b[5][5];break;case 6:i=b[1][1];j=b[2][1];k=b[3][1];l=b[4][1];m=b[5][1];break;case 7:i=b[1][2];j=b[2][2];k=b[3][2];l=b[4][2];m=b[5][2];break;case 8:i=b[1][3];j=b[2][3];k=b[3][3];l=b[4][3];m=b[5][3];break;case 9:i=b[1][4];j=b[2][4];k=b[3][4];l=b[4][4];m=b[5][4];break;case 10:i=b[1][5];j=b[2][5];k=b[3][5];l=b[4][5];m=b[5][5];break;case 11:i=b[1][1];j=b[2][2];k=b[3][3];l=b[4][4];m=b[5][5];break;case 12:i=b[1][5];j=b[2][4];k=b[3][3];l=b[4][2];m=b[5][1];break;}if((i==0&&j==1&&k==1&&l==1&&m==0))return (900);if((i==0&&j==-1&&k==-1&&l==-1&&m==0))return(1000);if((i==0&&j==0&&k==1&&l==1&&m==1)||(i==1&&j==1&&k==1&&l==0&&m==0))return(20);if((i==0&&j==0&&k==-1&&l==-1&&m==-1)||(i==-1&&j==-1&&k==-1&&l==0&&m==0))return(20);if((i==-1&&j==1&&k==1&&l==1&&m==1)||(i==1&&j==-1&&k==1&&l==1&&m==1)||(i==1&&j==1 &&k==-1&&l==1&&m==1)||(i==1&&j==1&&k==1&&l==-1&&m==1)||(i==1&&j==1&&k==1&&l== 1&&m==-1))return(-60);if((i==1&&j==-1&&k==-1&&l==-1&&m==-1)||(i==-1&&j==1&&k==-1&&l==-1&&m==-1)||(i==-1& &j==1&&k==-1&&l==-1&&m==-1)||(i==-1&&j==-1&&k==-1&&l==1&&m==-1)||(i==-1&&j==-1&& k==-1&&l==-1&&m==1))return(-60);}/* 循环执行坐标的选择,直到按回车,空格或ESC键*/intwtu(int a[N+1][N+1],int write){inti=1;map(a);zuobiao(zx,zy,1);while(i){int k;k=tu(a,write);if(k==OK) i=0;if(k==STOP) return (STOP);}}/*从键盘获得输入的值*/intgetkey(){intkey,lo,hi;key=bioskey(0);lo=key&0x00ff;hi=(key&0xff00)>>8;return((lo==0) ? hi+256:lo);}/*对获得的值进行判断*//*对应的码值分别如下*//* 上:328 下:336 左:331 右:333 */ /* 回车:13 ESC键:27 */int key(){int k;k=getkey();switch(k){case 27: return (STOP);case 13:case ' ': return (OK);case 328: return (UP);case 336: return (DOWN);case 331: return (LEFT);case 333: return (RIGHT);default: return (NO);}}/*用来显示坐标的位置*/void zuobiao(intx,inty,inti){int r;if(i!=0){setcolor(GREEN);for(r=1;r<=5;r++)circle(75+25*x,25+25*y,r);}else{if(a[zy][zx]==1){setcolor(8);for(r=1;r<=5;r++)circle(75+25*x,25+25*y,r);}else if(a[zy][zx]==-1){setcolor(WHITE);for(r=1;r<=5;r++)circle(75+25*x,25+25*y,r);}else{setcolor(B);for(r=1;r<=5;r++)circle(75+25*x,25+25*y,r);setcolor(RED); line(75+25*zx-5,25+25*zy,75+25*x+5,25+25*zy); line(75+25*zx,25+25*zy-5,75+25*zx,25+25*zy+5);}}}/*从键盘获得的值进行判断,反映在显示的图上*/inttu(int a[N+1][N+1],int write){int k;re:k=key();if(k==OK){if(a[zy][zx]==0){a[zy][zx]=write;}elsegoto re;}if(k==STOP) return(STOP); if(k==NO) goto re;if(k==UP){inti,j;if(zy==1) j=zy;else j=zy-1;zuobiao(zx,zy,0); zuobiao(zx,j,1);zy=j;goto re;}if(k==DOWN){inti,j;if(zy==N) j=zy;else j=zy+1;zuobiao(zx,zy,0); zuobiao(zx,j,1);zy=j;goto re;}if(k==LEFT){inti,j;if(zx==1) i=zx;else i=zx-1;zuobiao(zx,zy,0); zuobiao(i,zy,1);zx=i;goto re;}if(k==RIGHT){inti,j;if(zx==N) i=zx;else i=zx+1;zuobiao(zx,zy,0);zuobiao(i,zy,1);zx=i;goto re;}}/* 根据数组中(存储棋子位置)各位置的数,画实心圆(画出棋子)*/ void cbar(inti,intx,inty,int r){if(i!=0){if(i==1)setcolor(8);else if(i==-1)setcolor(WHITE);for(i=1;i<=r;i++){circle(x,y,i);}}}/*画出棋盘,和各个棋子*/void map(int a[N+1][N+1]){inti,j;cleardevice();setbkcolor(B);setcolor(RED);for(i=0;i {line(100,50+25*i,75+N*25,50+25*i);line(100+25*i,50,100+25*i,25+N*25);}for(i=1;i<=N;i++)for(j=1;j<=N;j++)cbar(a[i][j],75+25*j,25+25*i,10); }。

C语言实现五子棋小游戏源代码

C语言实现五子棋小游戏源代码
}
break;
case ESC:
break;
case SPACE:
if(chessx>=1&&chessx<=19&&chessy>=1&&chessy<=19)
{
if(chess[chessx][chessy]==0)
}
if(flag==2)
{
cleardevice();
setfont(36, 0, "宋体", 900, 900, 0, false, false, false);
outtextxy(80,200,"RED win!");
getch();
closegraph();
exit(0);
}
}
if(flag==1)
flag=2;
else
flag=1;
break;
}
void draw_pixel(int x,int y,int color)
{
x=(x+2)*20;
y=(y+2)*20;
{
putpixel(x+8,y,color);
putpixel(x,y-8,color);
putpixel(x+8,y+8,color);
{
chess[chessx][chessy]=flag;
if(result(chessx,chessy)==1)
{
if(flag==1)
{
cleardevice();
n1=0;
n2=0;

C语言五子棋游戏源代码

C语言五子棋游戏源代码

C语言五子棋游戏源代码标准化管理处编码[BBX968T-XBB8968-NNJ668-MM9N]#define N 10void welcome();void initqipan();void showqi(int i);void save(int p);void panduan(int p);void heqi();void over();int zouqihang();int zouqilie();/******************结构体*****************/ struct zuobiao{int x[N*N];int y[N*N];}weizhi[N*N];/******************主函数*****************/ void main(){int p=0;welcome();initqipan();for(p=1;p<=N*N;p++){weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();save(p);showqi(p);panduan(p);}if(p==N*N)heqi();over();}/******************建立棋盘*****************/ void initqipan(){int i,j;for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=0;j<N;j++){if(j==0)printf("%d",i);elseprintf("·");}printf("\n");}}/******************显示棋子*****************/ void showqi(int p){int i,j,k,m;int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=N*N;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp);a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}for(m=1;m<p;m++){while(weizhi[p].x[p]==a[m]&&weizhi[p].y[p]==b[m]) {printf("error!\n");weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();m=1;}}for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=1;j<N;j++){if(j==1)printf("%d",i);for(k=1;k<=p;k++){if(i==weizhi[k].x[k]&&j==weizhi[k].y[k]) {if(k%2==1){printf("○");break;} else if(k%2==0){printf("●");break;} }}if(k>p)printf("·");else continue;}printf("\n");}}/******************走棋行*****************/ int zouqihang(){int x;printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d",&x);while(x>N-1||x<1){printf("error!\n");printf("请输入要走棋子所在行数!\n"); printf("x=");scanf("%d",&x);}return x;}/******************走棋列*****************/ int zouqilie(){int y;printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d",&y);while(y>N-1||y<1){printf("error!\n");printf("请输入要走棋子所在列数!\n"); printf("y=");scanf("%d",&y);}return y;}/******************文件保存*****************/ void save(int i){FILE *fp;fp=fopen("wuzi_list","wb");fwrite(&weizhi[i],sizeof(struct zuobiao),1,fp);}/****************判断输赢*******************/void panduan(int p){int i,j,k[8]={1,1,1,1,1,1,1,1,};int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=p;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp); a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}/*****************判断行******************/for(i=1;i<=p;i++){if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)){k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)) {k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-3)) {k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4)) {k[0]++;continue;}else if(k[0]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[0]==5)break;k[0]=1;}else if(k[0]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-3)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4)) {k[1]++;continue;}else if(k[1]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[1]==5)break;k[1]=1;}}/**********************判断列************************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[2]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])) {k[2]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])) {k[2]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])) {k[2]++;continue;}else if(k[2]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[2]==5)break;k[2]=1;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[3]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])) {k[3]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])) {k[3]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])) {k[3]++;continue;}else if(k[3]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[3]==5)break;k[3]=1;}}/****************判断对角(左上-右下)******************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[4]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)) {k[4]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)) {k[4]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)) {k[4]++;continue;}else if(k[4]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[4]==5)break;k[4]=1;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[5]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)) {k[5]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)) {k[5]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)) {k[5]++;continue;}else if(k[5]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[5]==5)break;k[5]=1;}}/**********判断对角(左下-右上)************/for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5||k[4]==5||k[5]==5) break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[6]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)) {k[6]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3)) {k[6]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4))k[6]++;continue;}else if(k[6]==5){printf("Player 1 wins!!!\n"); }elsecontinue;}if(k[6]==5)break;k[6]=1;}else if(k[6]==5)else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[7]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)) {k[7]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3))k[7]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4)) {k[7]++;continue;}else if(k[7]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[7]==5)break;k[7]=1;}}}/****************和棋*******************/void heqi(){printf("************************************\n"); printf(" Tie!!!\n");printf("************************************\n"); }/****************游戏结束*******************/void over(){printf("************************************\n"); printf(" game over!!!\n");printf("************************************\n"); }/****************游戏开始*******************/void welcome(){printf("************************************\n"); printf(" Welcome!!!\n");printf("************************************\n"); }。

五子棋JAVA源代码

五子棋JAVA源代码

五子棋Java实现代码import java.awt.*;import java.awt.event.*;import java.applet.Applet;import java.awt.Color;public class WUZIQI extends Applet implements ActionListener, MouseListener, MouseMotionListener, ItemListener {int color = 0;// 棋子的颜色标识0:白子1:黑子boolean isStart = false;// 游戏开始标志int bodyArray[][] = new int[16][16]; // 设置棋盘棋子状态0 无子1 白子2 黑子Button b1 = new Button("游戏开始");Button b2 = new Button("重新开始");Label lblWin = new Label(" ");Checkbox ckbHB[] = new Checkbox[2];CheckboxGroup ckgHB = new CheckboxGroup();public void init() {setLayout(null);addMouseListener(this);add(b1);b1.setBounds(330, 50, 80, 30);b1.addActionListener(this);add(b2);b2.setBounds(330, 90, 80, 30);b2.addActionListener(this);ckbHB[0] = new Checkbox("白子先", ckgHB, false);ckbHB[0].setBounds(320, 20, 60, 30);ckbHB[1] = new Checkbox("黑子先", ckgHB, false);ckbHB[1].setBounds(380, 20, 60, 30);add(ckbHB[0]);add(ckbHB[1]);ckbHB[0].addItemListener(this);ckbHB[1].addItemListener(this);add(lblWin);lblWin.setBounds(330, 130, 80, 30);gameInit();this.resize(new Dimension(450,350));}public void itemStateChanged(ItemEvent e) {if (ckbHB[0].getState()) // 选择黑子先还是白子先{color = 0;}else {color= 1;}}public void actionPerformed(ActionEvent e) {if (e.getSource() == b1) {gameStart();}else {reStart();}}public void mousePressed(MouseEvent e) {}public void mouseClicked(MouseEvent e) {int x1, y1;x1 = e.getX();y1 = e.getY();if (e.getX() < 20 || e.getX() > 300 || e.getY() < 20 || e.getY() > 300) { return;}if (x1 % 20 > 10) {x1 += 20;}if (y1 % 20 > 10) {y1 += 20;}x1 = x1 / 20 * 20;y1 = y1 / 20 * 20;setDown(x1, y1);}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}public void mouseDragged(MouseEvent e) {}public void mouseMoved(MouseEvent e) {}public void paint(Graphics g) {g.setColor(Color.pink);g.fill3DRect(10, 10, 300, 300, true);g.setColor(Color.black);for (int i = 1; i < 16; i++) {g.drawLine(20, 20 * i, 300, 20 * i);g.drawLine(20 * i, 20, 20 * i, 300);}}public void setDown(int x, int y) // 落子{if (!isStart) // 判断游戏未开始{return;}if (bodyArray[x / 20][y / 20] != 0) {return;}Graphics g = getGraphics();if (color == 1)// 判断黑子还是白子{g.setColor(Color.black);color = 0;}else {g.setColor(Color.white);color = 1;}g.fillOval(x - 10, y - 10, 20, 20);bodyArray[x / 20][y / 20] = color + 1;if (gameWin1(x / 20, y / 20)) // 判断输赢{lblWin.setText(startColor(color) + "赢了!");isStart = false;}if (gameWin2(x / 20, y / 20)) // 判断输赢{lblWin.setText(startColor(color) + "赢了!");isStart = false;}if (gameWin3(x / 20, y / 20)) // 判断输赢{lblWin.setText(startColor(color) + "赢了!");isStart = false;}if (gameWin4(x / 20, y / 20)) // 判断输赢{lblWin.setText(startColor(color) + "赢了!");isStart = false;}}public String startColor(int x) {if (x == 0) {return "黑子";}else {return "白子";}}public void gameStart() // 游戏开始{isStart = true;enableGame(false);b2.setEnabled(true);}public void gameInit() // 游戏开始初始化{isStart = false;enableGame(true);b2.setEnabled(false);ckbHB[0].setState(true);for (int i = 0; i < 16; i++) {for (int j = 0; j < 16; j++) {bodyArray[i][j] = 0;}}lblWin.setText("");}public void reStart() // 游戏重新开始{repaint();gameInit();}public void enableGame(boolean e) // 设置组件状态{b1.setEnabled(e);b2.setEnabled(e);ckbHB[0].setEnabled(e);ckbHB[1].setEnabled(e);}public boolean gameWin1(int x, int y) // 判断输赢横{int x1, y1, t = 1;x1 = x;y1 = y;for (int i = 1; i < 5; i++) {if (x1 > 15) {break;}if (bodyArray[x1 + i][y1] == bodyArray[x][y]) {t += 1;}else {break;}}for (int i = 1; i < 5; i++) {if (x1 < 1) {break;}if (bodyArray[x1 - i][y1] == bodyArray[x][y]) {t += 1;}else {break;}}if (t > 4) {return true;}else {return false;}}public boolean gameWin2(int x, int y) // 判断输赢竖{int x1, y1, t = 1;x1 = x;y1 = y;for (int i = 1; i < 5; i++) {if (x1 > 15) {break;}if (bodyArray[x1][y1 + i] == bodyArray[x][y]) {t += 1;}else {break;}}for (int i = 1; i < 5; i++) {if (x1 < 1) {break;if (bodyArray[x1][y1 - i] == bodyArray[x][y]) {t += 1;}else {break;}}if (t > 4) {return true;}else {return false;}}public boolean gameWin3(int x, int y) // 判断输赢左斜{int x1, y1, t = 1;x1 = x;y1 = y;for (int i = 1; i < 5; i++) {if (x1 > 15) {break;}if (bodyArray[x1 + i][y1 - i] == bodyArray[x][y]) { t += 1;}else {break;}}for (int i = 1; i < 5; i++) {if (x1 < 1) {break;}if (bodyArray[x1 - i][y1 + i] == bodyArray[x][y]) { t += 1;}else {break;}}if (t > 4) {return true;else {return false;}}public boolean gameWin4(int x, int y) // 判断输赢左斜{int x1, y1, t = 1;x1 = x;y1 = y;for (int i = 1; i < 5; i++) {if (x1 > 15) {break;}if (bodyArray[x1 + i][y1 + i] == bodyArray[x][y]) {t += 1;}else {break;}}for (int i = 1; i < 5; i++) {if (x1 < 1) {break;}if (bodyArray[x1 - i][y1 - i] == bodyArray[x][y]) {t+=1;}else {break;}}if (t > 4) {return true;}else {return false;}}}。

五子棋源代码-Java_Applet小程序

五子棋源代码-Java_Applet小程序

五子棋源代码-Java_Applet小程序importjava.applet.Applet; importjava.awt.*;importjava.util.Random;public class wzq extends Applet implements Runnable{public void stop(){LoopThread = null;}privateintCalcZi(inti, int j, byte byte0){CXY cxy = new CXY(); int k = 0;int l = 0;do{int i1 = 0;int j1 = 0;do{cxy.x = i;cxy.y = j;if(MoveAGrid(cxy, l + 4 * j1) &&QiPan[cxy.x][cxy.y] == byte0) do{ if(QiPan[cxy.x][cxy.y] == 0 || QiPan[cxy.x][cxy.y] != byte0) break;i1++;} while(MoveAGrid(cxy, l + 4 * j1));}while(++j1 < 2);if(i1 > k)k = i1;}while(++l < 4);return ++k;}privatebooleanCanDo(){return steps < ((GRIDSUM * GRIDSUM) / 100) * 80;}//电脑下棋privateintCPUDo(CXY cxy, byte byte0){intai[] = new int[2];int ai1[] = new int[2];int ai2[] = new int[2];boolean flag = false;EnterTimes++;ai2[0] = 0;for(inti = recLU.x; i<= recRD.x; i++){for(int k = recLU.y; k <= recRD.y; k++){int l = 0;if(QiPan[i][k] == 0){DoAStep(i, k, byte0);l = CalcCPU(i, k, byte0);}if(l > 0){int i1 = 0;byte byte1;if(byte0 == 1)byte1 = 2; elsebyte1 = 1; if(EnterTimes<= level && steps < ((GRIDSUM * GRIDSUM) / 100) * 80)i1 = CPUDo(cxy, byte1);l += i1;if(l + Math.abs(rd.nextInt()) % 5 > ai2[0] || !flag){ai[0] = i;ai1[0] = k;ai2[0] = l;flag = true;}QiPan[i][k] = 0;}}}if(EnterTimes<= 1){cxy.x = ai[0];cxy.y = ai1[0];int j = 0;do{try{Thread.sleep(300L);}catch(InterruptedException _ex) { } QiPan[cxy.x][cxy.y] = byte0;repaint();try{Thread.sleep(300L);}catch(InterruptedException _ex) { } QiPan[cxy.x][cxy.y] = 0; repaint(); }while(++j < 2);}EnterTimes--;return ai2[0];}public void ClearPan(){for(inti = 0; i< GRIDSUM; i++){for(int j = 0; j < GRIDSUM; j++) QiPan[i][j] = 0;}scHong = 0;scHei = 0;steps = 0;recLU.x = 8;recRD.x = 9;recLU.y = 8;recRD.y = 9;}privatebooleanMoveAGrid(CXY cxy, inti){boolean flag = false;i %= 8;int j = cxy.x + oAdd[i][0]; int k = cxy.y + oAdd[i][1]; if(j >= 0 && j < GRIDSUM && k >= 0 && k < GRIDSUM){cxy.x = j;cxy.y = k;flag = true;}return flag;}public void paint(Graphics g){super.paint(g);for(inti = 0; i< GRIDSUM + 1; i++){g.drawLine(0, i * GRIDWIDTH, GRIDSUM * GRIDWIDTH, i * GRIDWIDTH);g.drawLine(i * GRIDWIDTH, 0, i * GRIDWIDTH, GRIDSUM * GRIDWIDTH);}for(int j = 0; j < GRIDSUM; j++){for(int k = 0; k < GRIDSUM; k++) drawQi(g, j, k, QiPan[j][k]);}}private void CPUInit(){PosAdd[0][0] = 8;PosAdd[0][1] = -2;PosAdd[1][0] = -2;PosAdd[0][2] = 3;PosAdd[2][0] = 3;PosAdd[0][3] = 2;PosAdd[3][0] = 2; PosAdd[1][1] = -7; PosAdd[1][2] = -1; PosAdd[2][1] = -1; PosAdd[1][3] = -1; PosAdd[3][1] = -1;PosAdd[2][2] = 4; PosAdd[3][3] = 4; PosAdd[2][3] = 4; PosAdd[3][2] = 4;}public void mouseDOWNThis(Event event){if(playerdo)xiazi.put(event.x, event.y);}privateintDoAStep(inti, int j, byte byte0){if(QiPan[i][j] != 0 || byte0 == 0 || byte0 > 2){return 0;}else{QiPan[i][j] = byte0; return 1;}}private void FreshRec(inti, int j){if(i - recLU.x< 2){recLU.x = i - 2;if(recLU.x< 0)recLU.x = 0;}if(recRD.x - i< 2){recRD.x = i + 2;if(recRD.x>= GRIDSUM) recRD.x = GRIDSUM - 1; }if(j - recLU.y< 2){recLU.y = j - 2;if(recLU.y< 0)recLU.y = 0;}if(recRD.y - j < 2){recRD.y = j + 2;if(recRD.y>= GRIDSUM) recRD.y = GRIDSUM - 1;}}publicwzq(){GRIDWIDTH = 18;GRIDSUM = 18; QiPan = new byte[GRIDSUM][GRIDSUM];oAdd = new int[8][2]; playing = false;playerdo = true;xy = new CXY();xiazi = new CXiaZi(); rd = new Random(); recLU = new CXY(); recRD = new CXY(); PosAdd = new int[4][4];}public void update(Graphics g){paint(g);}//画棋public void drawQi(Graphics g, inti, int j, int k){switch(k){case 0: // '\0'g.clearRect(i * GRIDWIDTH + 1, j * GRIDWIDTH + 1, GRIDWIDTH -2,GRIDWIDTH - 2);return;case 1: // '\001'g.setColor(Color.red);g.fillArc(i * GRIDWIDTH + 2, j * GRIDWIDTH + 2, GRIDWIDTH -4,GRIDWIDTH - 4, 0, 360);return;case 2: // '\002'g.setColor(Color.black);break;}g.fillArc(i * GRIDWIDTH + 2, j * GRIDWIDTH + 2, GRIDWIDTH -4,GRIDWIDTH - 4, 0, 360);}public void start(){if(LoopThread == null)LoopThread = new Thread(this, "wbqloop"); LoopThread.setPriority(1);LoopThread.start();}public void run(){for(; Thread.currentThread() == LoopThread; xiazi.get(xy)) {ClearPan();repaint();playing = true;//谁先下随机who = (byte)(Math.abs(rd.nextInt()) % 2 + 1); for(passes = 0; playing && passes < 2;){if(who == 1){lblStatus.setText("\u7EA2\u65B9\u4E0B");lblStatus.setForeground(Color.red);}else{lblStatus.setText("\u9ED1\u65B9\u4E0B");lblStatus.setForeground(Color.black);}if(steps < ((GRIDSUM * GRIDSUM) / 100) * 80){passes = 0;if(who == 1) //人下棋{xiazi.get(xy);for(; DoAStep(xy.x, xy.y, who) == 0; xiazi.get(xy)); scHong = CalcZi(xy.x, xy.y, who); FreshRec(xy.x, xy.y); steps++;}else //机器下棋{if(scHong == 0 &&scHei == 0){ xy.x = 9;xy.y = 9;} else{ CPUDo(xy, who);} for(; DoAStep(xy.x, xy.y, who) == 0; CPUDo(xy, who)); scHei = CalcZi(xy.x, xy.y, who); FreshRec(xy.x, xy.y); steps++;}}else{passes = 2;}if(scHong>= 5 || scHei>= 5) playing = false; repaint();//交换下棋方who = (byte)((1 - (who - 1)) + 1); Thread.yield(); }if(scHong>= 5) //红方胜{Status = "\u7EA2\u65B9\u80DC!";lblStatus.setForeground(Color.red); LoseTimes++; }else if(scHei>= 5)//黑方胜{Status = "\u9ED1\u65B9\u80DC!";lblStatus.setForeground(Color.black);if(LoseTimes> 0)LoseTimes--;}else //平局{Status = "\u4E0D\u5206\u80DC\u8D1F!";}lblStatus.setText(Status); repaint();}}//入口,开始下棋,初始化public void init() {super.init(); LoopThread = null; oAdd[0][0] = 0; oAdd[0][1] = -1; oAdd[1][0] = 1; oAdd[1][1] = -1; oAdd[2][0] = 1; oAdd[2][1] = 0; oAdd[3][0] = 1; oAdd[3][1] = 1; oAdd[4][0] = 0; oAdd[4][1] = 1; oAdd[5][0] = -1; oAdd[5][1] = 1; oAdd[6][0] = -1; oAdd[6][1] = 0; oAdd[7][0] = -1; oAdd[7][1] = -1; CPUInit();setLayout(null);resize(325, 352);lblStatus = new Label("Welcome"); lblStatus.setFont(new Font("Dialog", 1, 14));add(lblStatus);lblStatus.reshape(14, 332, 175, 15);lblLevel = new Label("JAVA\u4E94\u5B50\u68CB");lblLevel.setFont(new Font("Dialog", 1, 14));add(lblLevel);lblLevel.reshape(196, 332, 119, 15);}publicbooleanhandleEvent(Event event){if(event.id != 501 || event.target != this){returnsuper.handleEvent(event);}else{mouseDOWNThis(event);return true;}}privateintCalcCPU(inti, int j, byte byte0){CXY cxy = new CXY();String s = "";String s2 = "";String s4 = ""; byte byte1 = 0;CalcTimes++;if(byte0 == 1)byte1 = 2; elseif(byte0 == 2)byte1 = 1; int k = 0;int l = 0;do{int i1 = 0;String s1 = "";String s3 = "";String s5 = ""; int j1 = 0;do{int k1 = 0;cxy.x = i;for(cxy.y = j; MoveAGrid(cxy, l + 4 * j1) && k1 < 6 &&QiPan[cxy.x][cxy.y] != byte1; k1++) if(QiPan[cxy.x][cxy.y] == byte0) {if(j1 == 0)s3 += "1"; elses5 = "1" + s5; i1++;}elseif(j1 == 0)s3 += "0"; elses5 = "0" + s5;if(j1 == 0)s3 += "2";elses5 = "2" + s5;}while(++j1 < 2);i1++;s1 = s5 + "1" + s3;if(s1.indexOf("11111") != -1)i1 += 1000;elseif(s1.indexOf("011110") != -1)i1 += 500;elseif(s1.indexOf("211110") != -1 || s1.indexOf("011112") != -1 || s1.indexOf("01110") != -1 || s1.indexOf("01110") != -1 ||s1.indexOf("011010")!= -1 || s1.indexOf("010110") != -1 || s1.indexOf("11101") != -1 || s1.indexOf("10111") != -1 ||s1.indexOf("11011") != -1)i1 += 100;elseif(s1.indexOf("21110") != -1 || s1.indexOf("01112") != -1 ||s1.indexOf("0110") != -1 || s1.indexOf("211010") != -1 ||s1.indexOf("210110")!= -1)i1 += 20;if(l == 1 || l == 3)i1 += (i1 * 20) / 100;k += i1;}while(++l < 4); if(CalcTimes<= 1)k += CalcCPU(i, j, byte1);elseif(k > 10)k -= 10; CalcTimes--;return k;}int GRIDWIDTH; //网格宽度int GRIDSUM; //网格总数byte QiPan[][]; //棋盘intoAdd[][];Thread LoopThread;intscHong; //红方intscHei; //黑方byte who; //byte winner; //赢方boolean playing; booleanplayerdo; CXY xy;CXiaZixiazi; //下子String Status; //状态Random rd; //随机数 int passes;int steps;intLoseTimes;CXY recLU;CXY recRD; intPosAdd[][]; int level; intEnterTimes; intCalcTimes;Label lblStatus;Label lblLevel; }classCXiaZi{public synchronized void get(CXY cxy) {ready = false;notify();while(!ready)try{wait();}catch(InterruptedException _ex) { }ready = false;notify();cxy.x = xy.x;cxy.y = xy.y;}public synchronized void put(inti, int j){if(i< GRIDWIDTH * GRIDSUM && j < GRIDWIDTH * GRIDSUM) {xy.x = i / GRIDWIDTH; xy.y = j / GRIDWIDTH; ready = true; notify();}}publicCXiaZi(){GRIDWIDTH = 18;GRIDSUM = 18; xy = new CXY();ready = false;}private CXY xy;privateboolean ready; privateint GRIDWIDTH; privateint GRIDSUM; } class CXY{public CXY(){x = 0;y = 0;}publicint x; publicint y; }内部资料,请勿外传~。

C语言五子棋游戏源代码

C语言五子棋游戏源代码

#include<stdio.h>#define N 10void welcome();void initqipan();void showqi(int i);void save(int p);void panduan(int p);void heqi();void over();int zouqihang();int zouqilie();/******************结构体*****************/ struct zuobiao{int x[N*N];int y[N*N];}weizhi[N*N];/******************主函数*****************/ void main(){int p=0;welcome();initqipan();for(p=1;p<=N*N;p++){weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();save(p);showqi(p);panduan(p);}if(p==N*N)heqi();over();}/******************建立棋盘*****************/ void initqipan(){int i,j;for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=0;j<N;j++){if(j==0)printf("%d",i);elseprintf("·");}printf("\n");}}/******************显示棋子*****************/void showqi(int p){int i,j,k,m;int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=N*N;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp);a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}for(m=1;m<p;m++){while(weizhi[p].x[p]==a[m]&&weizhi[p].y[p]==b[m]){printf("error!\n");weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();m=1;}}for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=1;j<N;j++){if(j==1)printf("%d",i);for(k=1;k<=p;k++){if(i==weizhi[k].x[k]&&j==weizhi[k].y[k]){if(k%2==1){printf("○");break;}else if(k%2==0){printf("●");break;}}}if(k>p)printf("·");else continue;}printf("\n");}}/******************走棋行*****************/int zouqihang(){int x;printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d",&x);while(x>N-1||x<1){printf("error!\n");printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d",&x);}return x;}/******************走棋列*****************/int zouqilie(){int y;printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d",&y);while(y>N-1||y<1){printf("error!\n");printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d",&y);}return y;}/******************文件保存*****************/ void save(int i){FILE *fp;fp=fopen("wuzi_list","wb");fwrite(&weizhi[i],sizeof(struct zuobiao),1,fp);}/****************判断输赢*******************/ void panduan(int p){int i,j,k[8]={1,1,1,1,1,1,1,1,};int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=p;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp);a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}/*****************判断行******************/ for(i=1;i<=p;i++){if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)){k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)){k[0]++;continue;else if((a[i]==a[j])&&(b[i]==b[j]-3)){k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4)){k[0]++;continue;}else if(k[0]==5){printf("Player 1 wins\n");}elsecontinue;}if(k[0]==5)break;k[0]=1;}else if(k[0]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)){k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)){k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-3)){k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4))k[1]++;continue;}else if(k[1]==5){printf("Player 2 wins\n");}elsecontinue;}if(k[1]==5)break;k[1]=1;}}/**********************判断列************************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[2]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])){k[2]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])){k[2]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])){k[2]++;continue;else if(k[2]==5){printf("Player 1 wins\n");}elsecontinue;}if(k[2]==5)break;k[2]=1;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[3]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])){k[3]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])){k[3]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])){k[3]++;continue;}else if(k[3]==5){printf("Player 2 wins\n");}elsecontinue;}if(k[3]==5)break;k[3]=1;}}/****************判断对角(左上-右下)******************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[4]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)){k[4]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)){k[4]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)){k[4]++;continue;}else if(k[4]==5){printf("Player 1 wins\n");}elsecontinue;}if(k[4]==5)break;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[5]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)){k[5]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)){k[5]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)){k[5]++;continue;}else if(k[5]==5){printf("Player 2 wins\n");}elsecontinue;}if(k[5]==5)break;k[5]=1;}}/**********判断对角(左下-右上)************/for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5||k[4]==5||k[5]==5)else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[6]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)){k[6]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3)){k[6]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4)){k[6]++;continue;}else if(k[6]==5){printf("Player 1 wins\n");}elsecontinue;}if(k[6]==5)break;k[6]=1;}else if(k[6]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[7]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)){k[7]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3)){k[7]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4)){k[7]++;continue;}else if(k[7]==5){printf("Player 2 wins\n");}elsecontinue;}if(k[7]==5)break;k[7]=1;}}}/****************和棋*******************/void heqi(){printf("************************************\n");printf(" Tie\n");printf("************************************\n"); }/****************游戏结束*******************/void over(){printf("************************************\n");printf(" game over\n");printf("************************************\n");}/****************游戏开始*******************/void welcome(){printf("************************************\n");printf(" Welcome\n");printf("************************************\n"); }。

五子棋人机对战源代码

五子棋人机对战源代码

#include "stdafx.h"#include "FiveStone.h"#include "FiveKernel.h"#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#define new DEBUG_NEW#endif//////////////////////////////////////////////////////////////////////// Construction/Destruction////////////////////////////////////////////////////////////////////// FiveKernel::FiveKernel(){const char * readstring[9]={"长连","五","活四","冲四","活三","冲三","活二","可能为五","不可能为五"};int ItemNum;FILE * f;//read opentable filef=fopen("openlib.txt","r");fscanf(f,"%3x\n", &ItemNum);int j;for (int i=0;i<ItemNum;i++){fscanf(f, "%3x: %8x\n", &j, &OpenT able[i]);};fclose(f);//read valuetable filef=fopen("valuelib.txt","r");char str1[5], str2[10], str[2][11];for (i=0;i<3281;i++){ValueT able[i][0]=0;ValueT able[i][1]=0;}for (i=0;i<6561;i++){fscanf(f, "%s %s %s %s\n\n", str1, str2, str[0], str[1]);for (j=0;j<2;j++){for (int k=0;k<9;k++){if (strcmp(str[j],readstring[k])==0){if (i<=3280){ValueT able[i][j]+=(k+1)*16; //k+1 because value can not be 0 }if (i>=3280){ValueT able[6560-i][j]+=(k+1);break;}}}}fclose(f);Result=rsNotPlayed;}FiveKernel::~FiveKernel(){}bool FiveKernel::NewGame(HARDLEVEL hardlevel, RULE rule){if (Result==rsNotOut){if (IDYES!=MessageBox(GetActiveWindow(), "Are you sure to cancel the curre nt game?","New game",MB_YESNO)){return false;}}HardLevel=hardlevel;Rule=rule;HandLimit=(rule!=rlNormal);Result=rsNotOut;int i,j;//initialize Boardfor (i=0;i<16;i++){for (j=0;j<16;j++){Board[i][j]=vlCanBeFive*16+vlCanBeFive;}}StepNum=0;Turn=tnBlackTurn;return true;}bool FiveKernel::InputChess(POS pos){if((_ValidPos(pos))&&((Board[pos.x][pos.y]>>4)>=1)&&(Result==rsNotOut)){ BYTE value=(Turn==tnBlackTurn)?((Board[pos.x][pos.y]>>4)):((Board[pos.x][pos.y]&0x0f));if (value==vlHandLimit){MessageBox(GetActiveWindow(), "Invalid chess!","Hand limit",MB_OK); return false;_GoAStep(pos);return true;}else return false;}bool FiveKernel::OutputChess(POS * pos) {if (Result!=rsNotOut){return false;}if (StepNum==0){pos->x=7;pos->y=7;_GoAStep(*pos);return true;}if (_SearchInLib(pos)){_GoAStep(*pos);return true;}if (_ThinkOut(pos)){_GoAStep(*pos);return true;}return false;}bool FiveKernel::Retract(POS * pos){if ((Result==rsNotOut)&&(StepNum>0)){int i, j;StepNum--;//initialize Board and TurnTurn=tnBlackTurn;for (i=0;i<16;i++){for (j=0;j<16;j++){Board[i][j]=vlCanBeFive*16+vlCanBeFive; }}//place each chess stored in StepTablefor (i=0;i<StepNum;i++){_PlaceChess(&Board, StepTable[i], Turn); Turn=_GetOtherTurn(Turn);}}return true;}bool FiveKernel::GetResult(RESULT * result) {*result=Result;return (Result==rsNotPlayed)?false:true;}bool FiveKernel::GetBoard(BOARD * board) {if (Result==rsNotPlayed) return false;for (int i=0;i<16;i++){for (int j=0;j<16;j++){(*board)[i][j]=Board[i][j];}}return true;}bool FiveKernel::GetTurn(TURN * turn){if (Result==rsNotOut){*turn=Turn;return true;}else return false;}bool FiveKernel::GetLastPos(POS * pos) {if (StepNum>1){*pos=StepT able[StepNum-1];return true;}else return false;}//convert x and y to POSPOS FiveKernel::_Pos(BYTE x, BYTE y){POS pos;pos.x=x;pos.y=y;return pos;}//NOTICE: This routine has no error check void FiveKernel::_GoAStep(POS pos){StepT able[StepNum]=pos;StepNum++;BYTE value=(Turn==tnBlackTurn)?((Board[pos.x][pos.y]>>4)):((Board[pos.x][pos.y]&0x0f));if (value==vlFive){Result=(Turn==tnBlackTurn)?rsBlackWin:rsWhiteWin;}else if (StepNum==225){Result=rsDraw;}else{Board[pos.x][pos.y]=_Chess(Turn);bool CanBeDraw=true;for (int i=0;i<15;i++){for (int j=0;j<15;j++){BYTE value1=Board[i][j]>>4, value2=Board[i][j]&0x0f;if ((value1>0)&&(((value1!=vlHandLimit)&&(value1!=vlNoUse))||(value2!=vlNoUse))) CanBeDraw=false; }}if (CanBeDraw) Result=rsDraw;}_PlaceChess(&Board, pos, Turn);Turn=_GetOtherTurn(Turn);}TURN FiveKernel::_GetOtherTurn(TURN turn){return !turn;}//NOTICE: This routine has no error checkvoid FiveKernel::_PlaceChess(BOARD * board, POS pos, TURN turn) {(*board)[pos.x][pos.y]=_Chess(turn);BYTE i1=(pos.x>=4)?pos.x-4:0;BYTE i2=(pos.x<=10)?pos.x+4:14;BYTE j1=(pos.y>=4)?pos.y-4:0;BYTE j2=(pos.y<=10)?pos.y+4:14;for (BYTE i=i1;i<=i2;i++){for (BYTE j=j1;j<=j2;j++){if (((*board)[i][j]>>4)==0) continue;(*board)[i][j]=_PosValue(board, _Pos(i, j));}}}PLACE FiveKernel::_Chess(TURN turn){return (turn==tnBlackTurn?plBlackChess:plWhiteChess);}bool FiveKernel::_ValidPos(POS pos){return (pos.x>=0)&&(pos.x<15)&&(pos.y>=0)&&(pos.y<15);}bool FiveKernel::_SearchInLib(POS * pos){POS FoundPosT able[255];BYTE FoundPosNum=0;unsigned long x, y, z;int j=0;for (int i=0;i<StepNum;i++){x=StepT able[i].x;y=StepT able[i].y;z=x<<4|y;while ((OpenTable[j]&0xff000000)!=(z*0x1000000)){if ((OpenT able[j]&0xfff)==0xfff){return false;}else j=OpenT able[j]&0xfff;}if ((OpenTable[j]&0xfff000)==0xfff000) return false;j=(OpenT able[j]&0xfff000)/0x1000;if (i==StepNum-1){do{z=(OpenT able[j]&0xff000000)/0x1000000;x=z>>4;y=z&0x0f;FoundPosT able[FoundPosNum++]=_Pos((BYTE)x, (BYTE)y);j=OpenTable[j]&0xfff;} while (j!=0xfff);int RandomNum=-1;while ((RandomNum<0)||(RandomNum>=FoundPosNum)) RandomNum=rand();*pos=FoundPosTable[RandomNum];return true;}}return false;}bool FiveKernel::_ThinkOut(POS * pos){const BYTE ValueRank[2][16]={{0,0,255,253,100,100,100,100,1,1,253,100,100,0,0,0},{0,100,254,100,100,100,100,100,1,1,100,100,100,0,0,0},};const long ValueScore[2][16]={{0,0,10000000,200000,2000,1000,200,100,10,1,100000,10000,200000,0, 0,0},{0,1,1000000, 40000, 200, 100 ,20 ,10, 1, 1,40000, 2000, 20000, 0,0,0} };struct{POS Pos;long Score;}Prob[225];BYTE FoundNum=0;BYTE BestRank=0;BYTE value[2];BYTE ownrank, otherrank, temprank;long tempscore;int i, j;for (i=0;i<15;i++){for (j=0;j<15;j++){value[0]=Board[i][j]>>4;value[1]=Board[i][j]&0x0f;//if the place have chess then continueif (value[0]==0) continue;if (Turn==tnBlackTurn){ownrank=ValueRank[0][value[0]];otherrank=ValueRank[1][value[1]];tempscore=ValueScore[0][value[0]]+ValueScore[1][value[1]];}else{ownrank=ValueRank[0][value[1]];otherrank=ValueRank[1][value[0]];tempscore=ValueScore[0][value[1]]+ValueScore[1][value[0]];}if (ownrank==0) temprank=0;else temprank=(ownrank>otherrank)?ownrank:otherrank;if (temprank>BestRank){BestRank=temprank;FoundNum=1;Prob[0].Pos=_Pos(i,j);Prob[0].Score=tempscore;}else if(temprank==BestRank){int k=FoundNum;while ((k>=1)&&(Prob[k-1].Score<tempscore)){Prob[k]=Prob[k-1];k--;}Prob[k].Pos=_Pos(i,j);Prob[k].Score=tempscore;FoundNum++;}}}int w1=0;while ((w1<FoundNum)&&(Prob[w1].Score==Prob[0].Score)) w1++;int w2=rand()%w1;POS temppos=Prob[w2].Pos;Prob[w2].Pos=Prob[0].Pos;Prob[0].Pos=temppos;if (BestRank>100){*pos=Prob[0].Pos;return true;}if ((HardLevel==hlBeginner)&&(rand()%4==0)||(HardLevel==hlAmateur)&&(rand()%4!=0)){if (_CanWinByFour(&Board, pos, Turn, 6, false)) return true;if (_CanWinByFour(&Board, pos, Turn, 6, true)) return true;if (_CanWinByThree(&Board, pos, Turn, 2)) return true;}bool OtherCanWinFour_ThreeEnable=false;bool OtherCanWinFour_ThreeDisable=false;bool OtherCanWinThree=false;if (HardLevel==hlExpert){if (_CanWinByFour(&Board, pos, Turn, 6, false)) return true;POS OtherWinPos;if (_CanWinByFour(&Board, &OtherWinPos, _GetOtherTurn(Turn), 6, false)) OtherCanWinFour_ThreeDisable=true;else{if (_CanWinByFour(&Board, pos, Turn, 6, true)) return true;if (_CanWinByFour(&Board, &OtherWinPos, _GetOtherTurn(Turn), 6, true)) OtherCanWinFour_ThreeEnable=true;else{if (_CanWinByThree(&Board, pos, Turn, 2)) return true;if (_CanWinByThree(&Board, &OtherWinPos, _GetOtherTurn(Turn), 2)) OtherCanWinThree=true;}}}const char DirDis[8][2]={{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};BYTE SaveC;char SaveX, SaveY;char tempx, tempy;BYTE tempvalue;for (int t=0;t<FoundNum;t++){SaveX=Prob[t].Pos.x;SaveY=Prob[t].Pos.y;SaveC=Board[SaveX][SaveY];if (Turn==tnBlackTurn)Prob[t].Score=2*ValueScore[0][SaveC&0x0f]-ValueScore[1][SaveC>>4];else Prob[t].Score=2*ValueScore[0][SaveC>>4]-ValueScore[1][SaveC&0x0f]; Board[SaveX][SaveY]=_Chess(Turn);for (i=0;i<8;i++){for (j=1;j<=4;j++){tempx=SaveX+j*DirDis[i][0];tempy=SaveY+j*DirDis[i][1];if (_ValidPos(_Pos(tempx, tempy))&&((Board[tempx][tempy]>>4)>=1)){ tempvalue=Board[tempx][tempy];if (Turn==tnBlackTurn)Prob[t].Score-=(ValueScore[1][tempvalue>>4]-ValueScore[0][tempvalu e&0x0f]);else Prob[t].Score-=(ValueScore[1][tempvalue&0x0f]-ValueScore[0][tempva lue>>4]);tempvalue=_PosValue(&Board, _Pos(tempx, tempy));if (Turn==tnBlackTurn)Prob[t].Score+=(ValueScore[1][tempvalue>>4]-ValueScore[0][tempvalu e&0x0f]);else Prob[t].Score+=(ValueScore[1][tempvalue&0x0f]-ValueScore[0][tempva lue>>4]);}}}Board[SaveX][SaveY]=SaveC;int k=t;POS temppos=Prob[t].Pos;tempscore=Prob[t].Score;while ((k>=1)&&(Prob[k-1].Score<tempscore)){Prob[k]=Prob[k-1];k--;}Prob[k].Pos=temppos;Prob[k].Score=tempscore;}w1=0;while ((w1<FoundNum)&&(Prob[w1].Score==Prob[0].Score)) w1++;w2=rand()%w1;temppos=Prob[w2].Pos;Prob[w2].Pos=Prob[0].Pos;Prob[0].Pos=temppos;if ((HardLevel==hlBeginner)||(HardLevel==hlAmateur)){*pos=Prob[0].Pos;return true;}if (FoundNum>MaxFoundPosNum) FoundNum=MaxFoundPosNum;BOARD tempboard;temppos;for (t=0;t<FoundNum;t++){memcpy(&tempboard, &Board, sizeof(BOARD));_PlaceChess(&tempboard, Prob[t].Pos, Turn);if (OtherCanWinFour_ThreeDisable){if (!_CanWinByFour(&tempboard, &temppos, _GetOtherTurn(Turn), 6, false)){*pos=Prob[t].Pos;return true;}}else if (OtherCanWinFour_ThreeEnable){if (!_CanWinByFour(&tempboard, &temppos, _GetOtherTurn(Turn), 6, true)){*pos=Prob[t].Pos;return true;}}else if (OtherCanWinThree){if (!_CanWinByThree(&tempboard, &temppos, _GetOtherTurn(Turn), 2)){ *pos=Prob[t].Pos;return true;}}else{if (_CanWinByFour(&tempboard, &temppos, Turn, 6, true)){*pos=Prob[t].Pos;return true;}if (_CanWinByThree(&tempboard, &temppos, Turn, 2)){*pos=Prob[t].Pos;return true;}}}*pos=Prob[0].Pos;return true;}VALUE FiveKernel::_PosDirectionValue(BOARD * board, POS pos, DIR dir) {VALUE blackvalue, whitevalue;const char dis[4][2]={{0,1},{1,1},{1,0},{1,-1}};unsigned int address;int j, k;for (int chess=0;chess<=2;chess+=2){address=0;for (int i=-4;i<=4;i++){if (i==0) continue;j=pos.x+i*dis[dir][0];k=pos.y+i*dis[dir][1];if (_ValidPos(_Pos(j, k))){if ((*board)[j][k]==plBlackChess) address+=(address<<1);else if ((*board)[j][k]==plWhiteChess) address+=(address<<1)+2;else address+=(address<<1)+1;}else{address+=(address<<1)+chess;}}if (address>=3280){if (chess==0){whitevalue=ValueT able[6560-address][0]>>4;}else{if (HandLimit) blackvalue=ValueTable[6560-address][1]&0x0f;else blackvalue=ValueTable[6560-address][0]&0x0f;}}else{if (chess==0){whitevalue=ValueT able[address][0]&0x0f;}else{if (HandLimit) blackvalue=ValueTable[address][1]>>4;else blackvalue=ValueTable[address][0]>>4;}}}return (blackvalue<<4)|whitevalue;}VALUE FiveKernel::_PosValue(BOARD * board, POS pos, TURN turn){BYTE FourNum=0, LiveThreeNum=0;VALUE v, value=vlNoUse;for (int i=0;i<4;i++){v=_PosDirectionValue(board, pos, i);if (turn==tnBlackTurn) v=v>>4; else v=v&0x0f;if (v==vlHandLimit) return vlHandLimit;else value=(v<value)?v:value;if ((v==vlLiveFour)||(v==vlDeadFour)) FourNum++;else if (v==vlLiveThree) LiveThreeNum++;}if (FourNum>=2){if ((HandLimit)&&(turn==tnBlackTurn)) return vlHandLimit;else return (value>vlFive)?vlDoubleFour:value;}if (LiveThreeNum>=2){if ((HandLimit)&&(turn==tnBlackTurn)) return vlHandLimit;else value=vlDoubleLiveThree;}if ((FourNum==1)&&(LiveThreeNum>=1))return (value>vlLiveFour)?vlFourLiveThree:value;return value;}VALUE FiveKernel::_PosValue(BOARD * board, POS pos){VALUE blackvalue, whitevalue;blackvalue=_PosValue(board, pos, tnBlackTurn);whitevalue=_PosValue(board, pos, tnWhiteTurn);return (blackvalue<<4)|whitevalue;}VALUE FiveKernel::_PosDirectionValue(BOARD * board, POS pos, DIR dir, TURN turn){VALUE value;value=_PosDirectionValue(board, pos, dir);return (turn==tnBlackTurn)?value>>4:value&0x0f;}bool FiveKernel::_CanWinByFour(BOARD * board, POS * pos, TURN turn, BYTE depth, bool ThreeEnable){const BYTE ValueRank[16]={0,0,255,254,252,0,0,0,0,0,254,251,253,0,0,0}; _InitStack();_OccupyNode(0);char NowIndex=0;NODE * NowNode=&(Stack[0]);NowNode->father=-1;NowNode->son=-1;NowNode->brother=-1;NowNode->pos=_Pos(-1, -1);BOARD NowBoard;memcpy(&NowBoard, board, sizeof(BOARD));TURN NowTurn=turn;BYTE NowDepth=depth;while (1){BYTE FoundNum=0;POS Prob[225];if (NowTurn==turn){for (BYTE i=0;i<15;i++){for (BYTE j=0;j<15;j++){BYTE tempRank;if (NowTurn==tnBlackTurn) tempRank=ValueRank[NowBoard[i][j]>>4];else tempRank=ValueRank[NowBoard[i][j]&0x0f];if ((tempRank>=253)||((tempRank==251)&&(ThreeEnable))){NowNode->Win=true;if (NowIndex==0) NowNode->pos=_Pos(i, j);goto labelBACK;}else if (tempRank>=252){Prob[FoundNum]=_Pos(i, j);FoundNum++;}}}}else{BYTE i1=(NowNode->pos.x>=4)?NowNode->pos.x-4:0;BYTE i2=(NowNode->pos.x<=10)?NowNode->pos.x+4:14;BYTE j1=(NowNode->pos.y>=4)?NowNode->pos.y-4:0;BYTE j2=(NowNode->pos.y<=10)?NowNode->pos.y+4:14;for (BYTE i=i1;i<=i2;i++){for (BYTE j=j1;j<=j2;j++){if ((NowBoard[i][j]>>4)==0) continue;BYTE tempRank, tempRank1;if (NowTurn==tnBlackTurn){tempRank=ValueRank[NowBoard[i][j]&0x0f];tempRank1=ValueRank[NowBoard[i][j]>>4];}else{tempRank=ValueRank[NowBoard[i][j]>>4];tempRank1=ValueRank[NowBoard[i][j]&0x0f];}if (tempRank==255){if (tempRank1>=252){NowNode->Win=false;if (NowIndex==0) NowNode->pos=_Pos(i, j);goto labelBACK;}Prob[FoundNum]=_Pos(i, j);FoundNum++;}}}}if ((NowDepth==0)||(FoundNum==0)){NowNode->Win=false;goto labelBACK;}char SonIndex;if (_GetVoidNode(&SonIndex)){NODE * tempNode;char tempIndex;NowNode->son=SonIndex;if (NowTurn==turn) NowNode->Win=false; else NowNode->Win=true; for (short t=0;t<FoundNum;t++){if (_GetVoidNode(&tempIndex)){if (t>0) tempNode->brother=tempIndex;_OccupyNode(tempIndex);tempNode=&(Stack[tempIndex]);tempNode->father=NowIndex;tempNode->son=-1;tempNode->pos=Prob[t];}else break;}tempNode->brother=-1;NowIndex=SonIndex;NowNode=&(Stack[NowNode->son]);_PlaceChess(&NowBoard, NowNode->pos, NowTurn);NowTurn=_GetOtherTurn(NowTurn);NowDepth--;}else{NowNode->Win=false;goto labelBACK;}continue;labelBACK:;NODE * tempNode=NowNode;char tempIndex=NowIndex;while ((NowNode->brother==-1)||(NowTurn==turn)&&(!NowNode->Win) ||(NowTurn!=turn)&&(NowNode->Win)){if (NowNode->father==-1){*pos=NowNode->pos;return NowNode->Win;}else{tempNode=NowNode;NowIndex=NowNode->father;_RemoveChess(&NowBoard, NowNode->pos);NowNode=&(Stack[NowIndex]);NowTurn=_GetOtherTurn(NowTurn);NowDepth++;if (NowTurn==turn){if (tempNode->Win){NowNode->Win=true;if (NowIndex==0) NowNode->pos=tempNode->pos;}}else{if (!tempNode->Win){NowNode->Win=false;if (NowIndex==0) NowNode->pos=tempNode->pos;}}tempIndex=NowNode->son;do {tempNode=&(Stack[tempIndex]);_FreeNode(tempIndex);tempIndex=tempNode->brother;}while (tempIndex!=-1);}}_RemoveChess(&NowBoard, NowNode->pos);NowIndex=NowNode->brother;NowNode=&(Stack[NowIndex]);_PlaceChess(&NowBoard, NowNode->pos, _GetOtherTurn(NowTurn));}return false;}bool FiveKernel::_CanWinByThree(BOARD * board, POS * pos, TURN turn, BYTE depth){const BYTE ValueRank[16]={0,0,255,254,252,250,0,0,0,0,254,251,253,0,0,0};const BYTE OwnFive=255;const BYTE OtherFive=254;const BYTE OwnLiveFour=253;const BYTE OtherLiveFour=252;const BYTE OwnTwoLiveThree=251;_InitStack();_OccupyNode(0);char NowIndex=0;NODE * NowNode=&(Stack[0]);NowNode->father=-1;NowNode->son=-1;NowNode->brother=-1;NowNode->pos=_Pos(-1, -1);BOARD NowBoard;memcpy(&NowBoard, board, sizeof(BOARD));TURN NowTurn=turn;BYTE NowDepth=depth;while (1){BYTE FoundNum=0;typedef struct {POS pos; BYTE rank;} PROB;PROB Prob[225];BYTE BestRank=0;if (NowTurn==turn){for (BYTE i=0;i<15;i++){for (BYTE j=0;j<15;j++){BYTE OwnRank, OtherRank;if (NowTurn==tnBlackTurn){OwnRank=ValueRank[NowBoard[i][j]>>4];OtherRank=ValueRank[NowBoard[i][j]&0x0f];}else{OwnRank=ValueRank[NowBoard[i][j]&0x0f];OtherRank=ValueRank[NowBoard[i][j]>>4];}if (OwnRank==255){BestRank=OwnFive;if (NowIndex==0) NowNode->pos=_Pos(i, j);}if ((OtherRank==255)&&(BestRank<OtherFive)) BestRank=OtherFive;if (((OwnRank==254)||(OwnRank==253))&&(BestRank<OwnLiveFour)){ BestRank=OwnLiveFour;if (NowIndex==0) NowNode->pos=_Pos(i, j);}if (((OtherRank==254)||(OwnRank==253))&&(BestRank<OtherLiveFour)) BestRank=OtherLiveFour;if ((OwnRank==251)&&(BestRank<OwnTwoLiveThree)){BestRank=OwnTwoLiveThree;if (NowIndex==0) NowNode->pos=_Pos(i, j);}if (OwnRank>0){int k=FoundNum;while ((k>=1)&&(Prob[k-1].rank<OwnRank)){Prob[k]=Prob[k-1];k--;}Prob[k].pos=_Pos(i,j);Prob[k].rank=OwnRank;FoundNum++;}}}if (BestRank==OwnFive) {NowNode->Win=true;goto labelBACK;}if (BestRank==OtherFive) {NowNode->Win=false;goto labelBACK;}if (BestRank==OwnLiveFour) {NowNode->Win=true;goto labelBACK;}if (BestRank==OtherLiveFour)while ((FoundNum>0)&&(Prob[FoundNum-1].rank<252)) FoundNum--;if (BestRank==OwnTwoLiveThree) {NowNode->Win=true;goto labelBACK;}}else{BYTE i1=(NowNode->pos.x>=4)?NowNode->pos.x-4:0;BYTE i2=(NowNode->pos.x<=10)?NowNode->pos.x+4:14;BYTE j1=(NowNode->pos.y>=4)?NowNode->pos.y-4:0;BYTE j2=(NowNode->pos.y<=10)?NowNode->pos.y+4:14;for (BYTE i=i1;i<=i2;i++){for (BYTE j=j1;j<=j2;j++){if ((NowBoard[i][j]>>4)==0) continue;BYTE tempRank;if (NowTurn==tnBlackTurn)tempRank=ValueRank[NowBoard[i][j]&0x0f];else tempRank=ValueRank[NowBoard[i][j]>>4];if ((tempRank>=254)){int k=FoundNum;while ((k>=1)&&(Prob[k-1].rank<tempRank)){Prob[k]=Prob[k-1];k--;}Prob[k].pos=_Pos(i,j);Prob[k].rank=tempRank;FoundNum++;}}}}if ((NowDepth==0)||(FoundNum==0)){NowNode->Win=false;goto labelBACK;}char SonIndex;if (_GetVoidNode(&SonIndex)){NODE * tempNode;char tempIndex;NowNode->son=SonIndex;if (NowTurn==turn) NowNode->Win=false; else NowNode->Win=true; for (short t=0;t<FoundNum;t++){if (_GetVoidNode(&tempIndex)){if (t>0) tempNode->brother=tempIndex;_OccupyNode(tempIndex);tempNode=&(Stack[tempIndex]);tempNode->father=NowIndex;tempNode->son=-1;tempNode->pos=Prob[t].pos;}else break;}tempNode->brother=-1;NowIndex=SonIndex;NowNode=&(Stack[NowNode->son]);_PlaceChess(&NowBoard, NowNode->pos, NowTurn);NowTurn=_GetOtherTurn(NowTurn);NowDepth--;}else{NowNode->Win=false;goto labelBACK;}continue;labelBACK:;NODE * tempNode=NowNode;char tempIndex=NowIndex;while ((NowNode->brother==-1)||(NowTurn==turn)&&(!NowNode->Win) ||(NowTurn!=turn)&&(NowNode->Win)){if (NowNode->father==-1){*pos=NowNode->pos;return NowNode->Win;}else{tempNode=NowNode;NowIndex=NowNode->father;_RemoveChess(&NowBoard, NowNode->pos);NowNode=&(Stack[NowIndex]);NowTurn=_GetOtherTurn(NowTurn);NowDepth++;if (NowTurn==turn){if (tempNode->Win){NowNode->Win=true;if (NowIndex==0) NowNode->pos=tempNode->pos;}}else{if (!tempNode->Win){NowNode->Win=false;if (NowIndex==0) NowNode->pos=tempNode->pos;}}tempIndex=NowNode->son;do {tempNode=&(Stack[tempIndex]);_FreeNode(tempIndex);tempIndex=tempNode->brother;}while (tempIndex!=-1);}}_RemoveChess(&NowBoard, NowNode->pos);NowIndex=NowNode->brother;NowNode=&(Stack[NowIndex]);_PlaceChess(&NowBoard, NowNode->pos, _GetOtherTurn(NowTurn));}return false;}//function _GetVoidNode has no error check//if NodeNum less than MaxNodeNum, there must be one void node at least bool FiveKernel::_GetVoidNode(char * nodeindex){if (SearchedPosNum==MaxSearchPosNum) return false;if (NodeNum==MaxNodeNum) return false;else{char i=0;while (!Stack[i].NodeVoid) i++;*nodeindex=i;SearchedPosNum++;return true;}}//function _FreeNode has no error check//the Node to be free must not be void nodevoid FiveKernel::_FreeNode(char nodeindex){Stack[nodeindex].NodeVoid=true;NodeNum--;}//function _OccupyNode has no error check//the Node to be Occupied must be void nodevoid FiveKernel::_OccupyNode(char nodeindex){Stack[nodeindex].NodeVoid=false;NodeNum++;}void FiveKernel::_InitStack(){NodeNum=0;SearchedPosNum=0;for (unsigned short i=0;i<MaxNodeNum;i++) Stack[i].NodeVoid=true;}void FiveKernel::_RemoveChess(BOARD * board, POS pos){(*board)[pos.x][pos.y]=0xff;BYTE i1=(pos.x>=4)?pos.x-4:0;BYTE i2=(pos.x<=10)?pos.x+4:14;BYTE j1=(pos.y>=4)?pos.y-4:0;BYTE j2=(pos.y<=10)?pos.y+4:14;for (BYTE i=i1;i<=i2;i++){for (BYTE j=j1;j<=j2;j++){if (((*board)[i][j]>>4)==0) continue;(*board)[i][j]=_PosValue(board, _Pos(i, j)); }}}。

五子棋游戏 C语言 代码 源代码

五子棋游戏 C语言 代码 源代码

#include <stdio.h>#include <stdlib.h>#define m 30int main (void){int count;//计数器算横纵行的结果int w,h;int u;int l;int i,size;//i声明步数。

size声明int r[m][m] = {0};//数组声明(棋子位置)int x, y;//声明落子坐标int n;//声明棋盘大小nchar a[20],b[20];printf ("请输入棋盘大小n\n");//编辑棋盘直到棋盘长度宽度大于4小于30 scanf ("%d", &n);if (n<=4 || n>m){do{printf ("输入的棋盘大小:4<n<%d\n", m);scanf ("%d", &n);}while (n<=4 || n>m);}getchar ();//声明玩家printf ("请输入玩家1姓名:\n");gets(a);printf ("请输入玩家2姓名:\n");gets(b);for ( i = 1, size = n*n;i <= size; i++)//编辑棋盘{if (i%2 == 1)//如果i能被2整除,为玩家a相关信息{do//玩家a棋子信息{printf ("%s该你下棋了,第%d个棋子\n", a, i);scanf ("%d%d", &x, &y);if (x > n || x < 0)//判断坐标是否在棋盘内,如果不是则重新输入{do{printf ("0<=横坐标<=%d请重新输入横坐标\n", n);scanf ("%d", &x);}while (x>m || x<0);}if (y > n || y < 0)//判断坐标是否在棋盘内,如果不是则重新输入{do{printf ("0<=纵坐标<=%d请重新输入纵坐标\n", n);scanf ("%d", &y);}while (y < 0 || y > n);}}while ((r[x][y] == 1 && (printf ("这个位置上已经有棋子了,请重新输入\n")))|| r[x][y] == 2&& (printf ("这个位置上已经有棋子了,请重新输入\n")) );r[x][y] = 1;for (u = 0;u < n; u++)//不同情况下判断玩家a获胜方式{for (l = 0;l < n;l++){count = 0;for (w = u,h = l;r[w][h] == 1 && h < n; h++)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;//直接跳转,其余代码不在运行count = 0;for (w = u, h = l; r[w][h] == 1 && w < n; w++)count ++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}count = 0;for (w = u,h = l; r[w][h] == 1 && w < n && h<n;w++,h++)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}count = 0;for (w =u ,h =l;r[w][h] == 1 && h > 0;h--)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}}}}system("cls");for (int j = n;j>=0;j--){printf ("%-2d", j);for (int k = 0;k < n;k++)//画棋盘,声明两玩家棋子图片{if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●"); }printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k);}else if (i%2 == 0)//如果i不能被2整除,为玩家b相关信息{do{printf ("\n%s该你下棋了,第%d个棋子\n", b, i);scanf ("%d%d", &x, &y);if (x > n || x < 0){do{printf ("0<=横坐标<=%d请重新输入横坐标\n", n);scanf ("%d", &x);}while (x>n || x<0);}if (y >n|| y < 0){do{printf ("0<=纵坐标<=%d请重新输入纵坐标\n", n);scanf ("%d", &y);}while (y < 0 || y > n);}}while ((r[x][y] == 1 && (printf ("这个位置上已经有棋子了,请重新输入\n")))|| r[x][y] == 2&& (printf ("这个位置上已经有棋子了,请重新输入\n")) );r[x][y] = 2;system("cls");for (int j = n;j>=0;j--){printf ("%-2d", j);for (int k = 0;k < n;k++){if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●");}printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k); printf ("\n");count = 0;for (u = 0;u < n; u++){for (l = 0;l < n;l++){count = 0;for (w = u,h = l;r[w][h] == 2 && h < n; h++)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w = u, h = l; r[w][h] == 2 && w < n; w++)count ++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w = u,h = l; r[w][h] == 2 && w < n && h<n;w++,h++)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w =u ,h =l;r[w][h] == 2 && h > 0;h--)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}}}}}e: for (int j = n;j>=0;j--)//游戏结束界面棋盘固定重新显示{printf ("%-2d", j);for (int k = 0;k < n;k++){if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●");}printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k); printf ("\n");printf ("\a游戏愉快,Powered by Techmessager\n");//结束语句return 0;}。

五子棋代码

五子棋代码

final JDialog dialog = new JDialog(this, "叫匡", true);
Font font=new Font("new_font", Font.BOLD, 20);
Grid grids[][] = new Grid[length][length];
direction=oblique_2;
break;
case oblique_2: displace_x=displace_y=1;
direction=horizontal;
int[][] dir = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
boolean[] dir2 = new boolean[8];
boolean turn;
String message;
break;
}
x=locX+displace_x;
y=locY+displace_y;
while(x>=0 && x<length && y>=0 && y<length && grid[x][y]==check)
{
count=count+1;
final static int End =3;
final static int nil=-1; /* 礚よ */
final static int oblique_1 =0; /* オ */
final static int oblique_2 =1; /* オ */

5子棋源代码

5子棋源代码

package org;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Toolkit;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import javax.swing.JFrame;import javax.swing.JOptionPane;public class FiveChess extends JFrame implements MouseListener, Runnable { // 背景图片BufferedImage bgImage = null;// 保存棋子坐標int x = 0;int y = 0;// 用數組來表示所有下過的棋子// 其內容數據:0--表示沒有棋子、1--表示黑子、2--表示白子int[][] allChess = new int[19][19];// 标识下一步棋子的颜色boolean isBlack = true;// 标识游戏是否结束boolean canPlay = false;// 创建游戏信息标识String gameMessage = "黑方先行";// 创建黑白双方的游戏时间信息String blackTimeMessage = "无限制";String whiteTimeMessage = "无限制";// 保存游戲最大時間(秒)int maxTime = 0;// 保存黑白雙方游戲時間int blackTime = 0;int whiteTime = 0;// 保存黑白雙方游戲時間信息String blackMessage = "無限制";String whiteMessage = "無限制";// 創建線程,用來建立倒計時Thread t = new Thread(this);public FiveChess() {this.setTitle("五子棋");this.setSize(500, 500);this.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - 500) / 2,(Toolkit.getDefaultToolkit().getScreenSize().height - 500) / 2);this.setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);// 实例化背景图片try {bgImage = ImageIO.read(new File("F:" + File.separator + "image"+ File.separator + "background.jpg"));} catch (IOException e) {e.printStackTrace();}// 加入鼠标监听this.addMouseListener(this);t.start();// 啟動線程t.suspend();//掛起線程this.repaint();// 刷新屏幕}public void paint(Graphics g) {// 利用双缓冲技术,防止点击时屏幕闪烁。

Java五子棋游戏源代码(人机对战)

Java五子棋游戏源代码(人机对战)

//Java编程:五子棋游戏源代码import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;import java.io.PrintStream;import javax.swing.JComponent;import javax.swing.JPanel;/**main方法创建了ChessFrame类的一个实例对象(cf),*并启动屏幕显示显示该实例对象。

**/public class FiveChessAppletDemo {public static void main(String args[]){ChessFrame cf = new ChessFrame();cf.show();}}/**类ChessFrame主要功能是创建五子棋游戏主窗体和菜单**/class ChessFrame extends JFrame implements ActionListener { private String[] strsize={"20x15","30x20","40x30"};private String[] strmode={"人机对弈","人人对弈"};public static boolean iscomputer=true,checkcomputer=true; private int width,height;private ChessModel cm;private MainPanel mp;//构造五子棋游戏的主窗体public ChessFrame() {this.setTitle("五子棋游戏");cm=new ChessModel(1);mp=new MainPanel(cm);Container con=this.getContentPane();con.add(mp,"Center");this.setResizable(false);this.addWindowListener(new ChessWindowEvent());MapSize(20,15);JMenuBar mbar = new JMenuBar();this.setJMenuBar(mbar);JMenu gameMenu = new JMenu("游戏");mbar.add(makeMenu(gameMenu, new Object[] {"开局", "棋盘","模式", null, "退出"}, this));JMenu lookMenu =new JMenu("视图");mbar.add(makeMenu(lookMenu,new Object[] {"Metal","Motif","Windows"},this));JMenu helpMenu = new JMenu("帮助");mbar.add(makeMenu(helpMenu, new Object[] {"关于"}, this));}//构造五子棋游戏的主菜单public JMenu makeMenu(Object parent, Object items[], Object target){ JMenu m = null;if(parent instanceof JMenu)m = (JMenu)parent;else if(parent instanceof String)m = new JMenu((String)parent);elsereturn null;for(int i = 0; i < items.length; i++)if(items[i] == null)m.addSeparator();else if(items[i] == "棋盘"){JMenu jm = new JMenu("棋盘");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int j=0;j<strsize.length;j++){rmenu=makeRadioButtonMenuItem(strsize[j],target);if (j==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}else if(items[i] == "模式"){JMenu jm = new JMenu("模式");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int h=0;h<strmode.length;h++){rmenu=makeRadioButtonMenuItem(strmode[h],target);if(h==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}elsem.add(makeMenuItem(items[i], target));return m;}//构造五子棋游戏的菜单项public JMenuItem makeMenuItem(Object item, Object target){ JMenuItem r = null;if(item instanceof String)r = new JMenuItem((String)item);else if(item instanceof JMenuItem)r = (JMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}//构造五子棋游戏的单选按钮式菜单项public JRadioButtonMenuItem makeRadioButtonMenuItem( Object item, Object target){JRadioButtonMenuItem r = null;if(item instanceof String)r = new JRadioButtonMenuItem((String)item);else if(item instanceof JRadioButtonMenuItem)r = (JRadioButtonMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}public void MapSize(int w,int h){setSize(w * 20+50 , h * 20+100 );if(this.checkcomputer)this.iscomputer=true;elsethis.iscomputer=false;mp.setModel(cm);mp.repaint();}public boolean getiscomputer(){return this.iscomputer;}public void restart(){int modeChess = cm.getModeChess();if(modeChess <= 3 && modeChess >= 1){cm = new ChessModel(modeChess);MapSize(cm.getWidth(),cm.getHeight());}else{System.out.println("\u81EA\u5B9A\u4E49");}}public void actionPerformed(ActionEvent e){String arg=e.getActionCommand();try{if (arg.equals("Windows"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");else if(arg.equals("Motif"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");elseUIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel" ); SwingUtilities.updateComponentTreeUI(this);}catch(Exception ee){}if(arg.equals("20x15")){this.width=20;this.height=15;cm=new ChessModel(1);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("30x20")){this.width=30;this.height=20;cm=new ChessModel(2);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("40x30")){this.width=40;this.height=30;cm=new ChessModel(3);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人机对弈")){this.checkcomputer=true;this.iscomputer=true;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人人对弈")){this.checkcomputer=false;this.iscomputer=false;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("开局")){restart();}if(arg.equals("关于"))JOptionPane.showMessageDialog(this, "五子棋游戏测试版本", "关于", 0);if(arg.equals("退出"))System.exit(0);}}/**类ChessModel实现了整个五子棋程序算法的核心*/class ChessModel {//棋盘的宽度、高度、棋盘的模式(如20×15)private int width,height,modeChess;//棋盘方格的横向、纵向坐标private int x=0,y=0;//棋盘方格的横向、纵向坐标所对应的棋子颜色,//数组arrMapShow只有3个值:1,2,3,-5,//其中1代表该棋盘方格上下的棋子为黑子,//2代表该棋盘方格上下的棋子为白子,//3代表为该棋盘方格上没有棋子,//-5代表该棋盘方格不能够下棋子private int[][] arrMapShow;//交换棋手的标识,棋盘方格上是否有棋子的标识符private boolean isOdd,isExist;public ChessModel() {}//该构造方法根据不同的棋盘模式(modeChess)来构建对应大小的棋盘public ChessModel(int modeChess){this.isOdd=true;if(modeChess == 1){PanelInit(20, 15, modeChess);}if(modeChess == 2){PanelInit(30, 20, modeChess);}if(modeChess == 3){PanelInit(40, 30, modeChess);}}//按照棋盘模式构建棋盘大小private void PanelInit(int width, int height, int modeChess){this.width = width;this.height = height;this.modeChess = modeChess;arrMapShow = new int[width+1][height+1];for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){arrMapShow[i][j] = -5;}}}//获取是否交换棋手的标识符public boolean getisOdd(){return this.isOdd;}//设置交换棋手的标识符public void setisOdd(boolean isodd){if(isodd)this.isOdd=true;elsethis.isOdd=false;}//获取某棋盘方格是否有棋子的标识值public boolean getisExist(){return this.isExist;}//获取棋盘宽度public int getWidth(){return this.width;}//获取棋盘高度public int getHeight(){return this.height;}//获取棋盘模式public int getModeChess(){return this.modeChess;}//获取棋盘方格上棋子的信息public int[][] getarrMapShow(){return arrMapShow;}//判断下子的横向、纵向坐标是否越界private boolean badxy(int x, int y){if(x >= width+20 || x < 0)return true;return y >= height+20 || y < 0;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public boolean chessExist(int i,int j){if(this.arrMapShow[i][j]==1 || this.arrMapShow[i][j]==2)return true;return false;}//判断该坐标位置是否可下棋子public void readyplay(int x,int y){if(badxy(x,y))return;if (chessExist(x,y))return;this.arrMapShow[x][y]=3;}//在该坐标位置下棋子public void play(int x,int y){if(badxy(x,y))return;if(chessExist(x,y)){this.isExist=true;return;}elsethis.isExist=false;if(getisOdd()){setisOdd(false);this.arrMapShow[x][y]=1;}else{setisOdd(true);this.arrMapShow[x][y]=2;}}//计算机走棋/**说明:用穷举法判断每一个坐标点的四个方向的的最大棋子数,*最后得出棋子数最大值的坐标,下子**/public void computerDo(int width,int height){int max_black,max_white,max_temp,max=0;setisOdd(true);System.out.println("计算机走棋...");for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){if(!chessExist(i,j)){//算法判断是否下子max_white=checkMax(i,j,2);//判断白子的最大值max_black=checkMax(i,j,1);//判断黑子的最大值max_temp=Math.max(max_white,max_black);if(max_temp>max){max=max_temp;this.x=i;this.y=j;}}}}setX(this.x);setY(this.y);this.arrMapShow[this.x][this.y]=2;}//记录电脑下子后的横向坐标public void setX(int x){this.x=x;}//记录电脑下子后的纵向坐标public void setY(int y){this.y=y;}//获取电脑下子的横向坐标public int getX(){return this.x;}//获取电脑下子的纵向坐标public int getY(){return this.y;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public int checkMax(int x, int y,int black_or_white){int num=0,max_num,max_temp=0;int x_temp=x,y_temp=y;int x_temp1=x_temp,y_temp1=y_temp;//judge rightfor(int i=1;i<5;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge leftx_temp1=x_temp;for(int i=1;i<5;i++){x_temp1-=1;if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num<5)max_temp=num;//judge upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge downy_temp1=y_temp;for(int i=1;i<5;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge left_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1-=1;y_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge right_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge right_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge left_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;max_num=max_temp;return max_num;}//判断胜负public boolean judgeSuccess(int x,int y,boolean isodd){ int num=1;int arrvalue;int x_temp=x,y_temp=y;if(isodd)arrvalue=2;elsearrvalue=1;int x_temp1=x_temp,y_temp1=y_temp;//判断右边for(int i=1;i<6;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}//判断左边x_temp1=x_temp;for(int i=1;i<6;i++){if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断上方x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断下方y_temp1=y_temp;for(int i=1;i<6;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断左上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断右下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width) break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断右上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断左下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}if(num==5)return true;return false;}//赢棋后的提示public void showSuccess(JPanel jp){JOptionPane.showMessageDialog(jp,"你赢了,好厉害!","win",RMATION_MESSAGE);}//输棋后的提示public void showDefeat(JPanel jp){JOptionPane.showMessageDialog(jp,"你输了,请重新开始!","lost",RMATION_MESSAGE);}}/**类MainPanel主要完成如下功能:*1、构建一个面板,在该面板上画上棋盘;*2、处理在该棋盘上的鼠标事件(如鼠标左键点击、鼠标右键点击、鼠标拖动等)**/class MainPanel extends JPanelimplements MouseListener,MouseMotionListener{private int width,height;//棋盘的宽度和高度private ChessModel cm;//根据棋盘模式设定面板的大小MainPanel(ChessModel mm){cm=mm;width=cm.getWidth();height=cm.getHeight();addMouseListener(this);}//根据棋盘模式设定棋盘的宽度和高度public void setModel(ChessModel mm){cm = mm;width = cm.getWidth();height = cm.getHeight();}//根据坐标计算出棋盘方格棋子的信息(如白子还是黑子),//然后调用draw方法在棋盘上画出相应的棋子public void paintComponent(Graphics g){super.paintComponent(g);for(int j = 0; j <= height; j++){for(int i = 0; i <= width; i++){int v = cm.getarrMapShow()[i][j];draw(g, i, j, v);}}}//根据提供的棋子信息(颜色、坐标)画棋子public void draw(Graphics g, int i, int j, int v){int x = 20 * i+20;int y = 20 * j+20;//画棋盘if(i!=width && j!=height){g.setColor(Color.white);g.drawRect(x,y,20,20);}//画黑色棋子if(v == 1 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.black);g.fillOval(x-8,y-8,16,16);}//画白色棋子if(v == 2 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.white);g.fillOval(x-8,y-8,16,16);}if(v ==3){g.setColor(Color.cyan);g.drawOval(x-8,y-8,16,16);}}//响应鼠标的点击事件,根据鼠标的点击来下棋,//根据下棋判断胜负等public void mousePressed(MouseEvent evt){int x = (evt.getX()-10) / 20;int y = (evt.getY()-10) / 20;System.out.println(x+" "+y);if (evt.getModifiers()==MouseEvent.BUTTON1_MASK){cm.play(x,y);System.out.println(cm.getisOdd()+" "+cm.getarrMapShow()[x][y]);repaint();if(cm.judgeSuccess(x,y,cm.getisOdd())){cm.showSuccess(this);evt.consume();ChessFrame.iscomputer=false;}//判断是否为人机对弈if(ChessFrame.iscomputer&&!cm.getisExist()){puterDo(cm.getWidth(),cm.getHeight());repaint();if(cm.judgeSuccess(cm.getX(),cm.getY(),cm.getisOdd())){cm.showDefeat(this);evt.consume();}}}}public void mouseClicked(MouseEvent evt){}public void mouseReleased(MouseEvent evt){}public void mouseEntered(MouseEvent mouseevt){}public void mouseExited(MouseEvent mouseevent){}public void mouseDragged(MouseEvent evt){}//响应鼠标的拖动事件public void mouseMoved(MouseEvent moveevt){int x = (moveevt.getX()-10) / 20;int y = (moveevt.getY()-10) / 20;cm.readyplay(x,y);repaint();}}class ChessWindowEvent extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0);}ChessWindowEvent(){}}。

五子棋源代码(C++),完美版

五子棋源代码(C++),完美版

#include <iostream>#include <conio.h>using namespace std;#define WIDE_AND_LONG 20 //棋盘的长和宽#define NAME_LEN 20 //输入姓名的长度typedef class Gobang{public:int InitPlayerName(char *, char *);int CheckInput(char,int);int CheckIndexInput(char, char, char);int GetPlayerName();int InitBoard();int WriteBoard(char, char, bool);int BeginOrNot();int CheckRow();int CheckColumn();int CheckTopLeft();int CheckTopRight();int CheckDownLeft();int CheckDownRight();int CheckDraw();int CheckFinish();int Chess();int ShowBoard();private:char acBoard[WIDE_AND_LONG][WIDE_AND_LONG];char acPlayerOneName[NAME_LEN];char acPlayerTwoName[NAME_LEN];}GOBANG;//初始化姓名的缺省值int GOBANG::InitPlayerName(char *pPlayerOne,char *pPlayerTwo) {strcpy(acPlayerOneName,pPlayerOne);strcpy(acPlayerTwoName,pPlayerTwo);return 0;}//检查输入姓名时是否含非法字符空格和Tab键int GOBANG::CheckInput(char ch, int iNameLen){if(' ' == ch || '\t' == ch){cout<<"含有非法字符!"<<endl;return -1;}if(iNameLen > NAME_LEN - 1){cout<<"输入超出限定长度!"<<endl;return -1;}return 0;}//将棋子放到棋盘中int GOBANG::WriteBoard(char cRow, char cColumn, bool bJudge){int iRow = 0;int iColumn = 0;if(cRow >= '0' && cRow <= '9'){iRow = static_cast<int>(cRow - '0');}else if(cRow >= 'A' && cRow <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)){iRow = static_cast<int>((cRow - 'A') + 10);}else{iRow = static_cast<int>((cRow - 'a') + 10);}if(cColumn >= '0' && cColumn <= '9'){iColumn = static_cast<int>(cColumn - '0');}else if(cColumn >= 'A' && cColumn <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)) {iColumn = static_cast<int>((cColumn - 'A') + 10);}else{iColumn = static_cast<int>((cColumn - 'a') + 10);}if('+' != acBoard[iRow][iColumn]){cout<<"此处已有棋子!"<<endl;return -1;}if(!bJudge){acBoard[iRow][iColumn] = static_cast<char>(1);}else{acBoard[iRow][iColumn] = static_cast<char>(2);}return 0;}//检查坐标输入是否合法int GOBANG::CheckIndexInput(char cRow,char cSeparator,char cColumn){if(!cRow || !cSeparator || !cColumn){return -1;}if(!((cRow >= '0' && cRow <= '9') || \(cRow >= 'A' && cRow <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)) || \ (cRow >= 'a' && cRow <= static_cast<char>('a' + WIDE_AND_LONG - 10 - 1)))){return -1;}if(' ' != cSeparator && '\t' != cSeparator && ',' != cSeparator){return -1;}if(!((cColumn >= '0' && cColumn <= '9') || \(cColumn >= 'A' && cColumn <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)) || \ (cColumn >= 'a' && cColumn <= static_cast<char>('a' + WIDE_AND_LONG - 10 - 1)))){return -1;}return 0;}//获取玩家的昵称int GOBANG::GetPlayerName(){fflush(stdin);char cTemp = 0;int iNameLen = 0;cout<<"是否自己定义昵称?是(Y),否(任意键):";cTemp = getch();cout<<endl;if(('y' != cTemp) && ('Y' != cTemp)){return 0;}fflush(stdin);memset(acPlayerOneName,0,sizeof(acPlayerOneName)); memset(acPlayerTwoName,0,sizeof(acPlayerTwoName)); cout<<"请玩家一输入昵称:";while('\n' != (cTemp = getchar())){if(-1 == CheckInput(cTemp,iNameLen)){fflush(stdin);cout<<"请玩家一输入昵称:";continue;}acPlayerOneName[iNameLen] = cTemp;iNameLen++;}if(0 == iNameLen){strcpy(acPlayerOneName,"玩家一");}iNameLen = 0;fflush(stdin);cout<<"请玩家二输入昵称:";while('\n' != (cTemp = getchar())){if(-1 == CheckInput(cTemp,iNameLen)){fflush(stdin);cout<<"请玩家二输入昵称:";continue;}acPlayerTwoName[iNameLen] = cTemp;iNameLen++;}if(0 == iNameLen){strcpy(acPlayerTwoName,"玩家一");}return 0;}//初始化棋盘int GOBANG::InitBoard(){int iRow = 0;int iColumn = 0;for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn++) {acBoard[iRow][iColumn] = '+';}}return 0;}//检查棋盘横向是否存在五子连珠int GOBANG::CheckRow(){int iRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 0; iRow < WIDE_AND_LONG; iRow ++){while(iColumn < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;}else if(static_cast<char>(2) == acBoard[iRow][iColumn]){iPlayerTwoLen ++;iPlayerOneLen = 0;}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iColumn ++;}if(iPlayerOneLen >= 5){return 1;if(iPlayerTwoLen >= 5){return 2;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = 0;}return 0;}//检查棋盘竖向是否存在五子连珠int GOBANG::CheckColumn(){int iRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn ++) {while(iRow < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;}else if(static_cast<char>(2) == acBoard[iRow][iColumn]){iPlayerTwoLen ++;iPlayerOneLen = 0;}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iRow ++;}if(iPlayerOneLen >= 5){return 1;}if(iPlayerTwoLen >= 5)return 2;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iRow = 0;}return 0;}//检查棋盘左上方(包括对角线)是否存在五子连珠int GOBANG::CheckTopLeft(){int iRow = 0;int iTempRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 4; iRow < WIDE_AND_LONG; iRow ++){iTempRow = iRow;while(iTempRow >= 0){if(static_cast<char>(1) == acBoard[iTempRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iTempRow][iColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;iTempRow --;iColumn ++;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = 0;}return 0;}//检查棋盘右上方(包括对角线)是否存在五子连珠int GOBANG::CheckTopRight(){int iRow = 0;int iColumn = 0;int iTempColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iColumn = 0; iColumn < WIDE_AND_LONG - 4; iColumn ++) {iTempColumn = iColumn;while(iTempColumn < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iRow][iTempColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iRow][iTempColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iRow ++;iTempColumn ++;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iRow = 0;}return 0;}//检查棋盘左下方(不包括对角线)是否存在五子连珠int GOBANG::CheckDownLeft(){int iRow = 0;int iTempRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 1; iRow < WIDE_AND_LONG - 4; iRow ++){iTempRow = iRow;while(iTempRow < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iTempRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iTempRow][iColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iTempRow ++;iColumn ++;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = 0;}return 0;}//检查棋盘右下方(不包括对角线)是否存在五子连珠int GOBANG::CheckDownRight(){int iRow = 0;int iTempRow = 0;int iColumn = WIDE_AND_LONG - 1;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 1; iRow < WIDE_AND_LONG - 4; iRow ++){iTempRow = iRow;while(iTempRow < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iTempRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iTempRow][iColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iTempRow ++;iColumn --;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = WIDE_AND_LONG - 1;}return 0;}//检查是否平局int GOBANG::CheckDraw(){int iRow = 0;int iColumn = 0;for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn++) {if('+' == acBoard[iRow][iColumn]){return 1;}}}return 0;}//检查是否达到结束的条件(五子连珠或平局)int GOBANG::CheckFinish(){int iJudgeRow = 0;int iJudgeColumn = 0;int iJudgeTopLeft = 0;int iJudgeTopRight = 0;int iJudgeDownLeft = 0;int iJudgeDownRight = 0;int iJudgeDraw = 0;iJudgeRow = CheckRow();iJudgeColumn = CheckColumn();iJudgeTopLeft = CheckTopLeft();iJudgeTopRight = CheckTopRight();iJudgeDownLeft = CheckDownLeft();iJudgeDownRight = CheckDownRight();iJudgeDraw = CheckDraw();if(1 == iJudgeRow || 1 == iJudgeColumn || 1 == iJudgeTopLeft || \1 == iJudgeTopRight || 1 == iJudgeDownLeft || 1 == iJudgeDownRight) {cout<<"恭喜玩家<"<<acPlayerOneName<<">获胜!"<<endl;return 1;}if(2 == iJudgeRow || 2 == iJudgeColumn || 2 == iJudgeTopLeft || \2 == iJudgeTopRight || 2 == iJudgeDownLeft || 2 == iJudgeDownRight) {cout<<"恭喜玩家<"<<acPlayerTwoName<<">获胜!"<<endl;return 1;}if(0 == iJudgeDraw){cout<<"平局!"<<endl;return 1;}return 0;}//显示棋盘到控制台int GOBANG::ShowBoard(){int iRow = 0;int iColumn = 0;system("cls");cout<<" ";for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){if(9 < iRow){cout<<static_cast<char>('A' + iRow - 10)<<" ";}else{cout<<iRow<<" ";}}cout<<endl;for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){if(9 < iRow){cout<<static_cast<char>('A' + iRow - 10)<<" ";}else{cout<<iRow<<" ";}for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn++){cout<<acBoard[iRow][iColumn]<<' ';}cout<<endl;}return 0;}//开始下棋int GOBANG::Chess(){bool bJudge = false;while(1){char cRow = 0;char cSeparator = 0;char cColumn = 0;char cTemp = 0;int iLen =1;fflush(stdin);if(!bJudge){cout<<"请<"<<acPlayerOneName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):"; }else{cout<<"请<"<<acPlayerTwoName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):"; }while('\n' != (cTemp = getchar())){if(iLen > 3){cout<<"输入有误!"<<endl;fflush(stdin);if(!bJudge){cout<<"请<"<<acPlayerOneName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):"; }else{cout<<"请<"<<acPlayerTwoName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):"; }iLen = 1;continue;}if(1 == iLen){cRow = cTemp;}else if(2 == iLen){cSeparator = cTemp;}else{cColumn = cTemp;}iLen++;}if(-1 == CheckIndexInput(cRow,cSeparator,cColumn)){cout<<"输入有误!"<<endl;continue;}if(-1 == WriteBoard(cRow,cColumn,bJudge)){continue;}ShowBoard();if(1 == CheckFinish()){BeginOrNot();}bJudge = !bJudge;}return 0;}//判断游戏结束后玩家是否选择继续还是退出int GOBANG::BeginOrNot(){char cTemp = 0;cout<<"是否继续?是(Y),退出(任意键):"; fflush(stdin);cTemp = getch();if('y' == cTemp || 'Y' == cTemp){InitBoard();ShowBoard();Chess();}else{exit(0); //程序的出口}return 0;}int main(){GOBANG gobang;memset(&gobang,0,sizeof(GOBANG)); gobang.InitPlayerName("玩家一","玩家二"); gobang.GetPlayerName();gobang.InitBoard();gobang.ShowBoard();gobang.Chess();return 0;}。

Python五子棋游戏代码

Python五子棋游戏代码

Python五子棋游戏代码五子棋游戏涉及到的内容较多,这里给出一个简化版的五子棋游戏实现。

首先需要安装pygame库,可以使用以下命令安装:bashpip install pygame接下来是五子棋游戏的代码:import pygameimport sys# 初始化pygamepygame.init()# 设置屏幕大小screen_size = (600, 600)screen = pygame.display.set_mode(screen_size)# 设置颜色white = (255, 255, 255)black = (0, 0, 0)# 加载棋盘图片board_image = pygame.image.load("board.png")# 设置棋盘大小board_size = board_image.get_rect().size# 设置棋盘坐标def get_position(x, y):return x * board_size[0], y * board_size[1]# 绘制棋盘def draw_board():for x in range(15):for y in range(15):rect = get_position(x, y)screen.blit(board_image, rect)pygame.draw.line(screen, black, get_position(x, y), get_position((x + 1) % 15, y), 2)pygame.draw.line(screen, black, get_position(x, y), get_position((x - 1) % 15, y), 2)# 主循环player = 1while True:for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()elif event.type == pygame.MOUSEBUTTONDOWN:x, y = event.posx, y = x // board_size[0], y // board_size[1]if board_image.get_at((x, y)) == (0, 0, 0):if player == 1:player = 2else:player = 1screen.fill(white)draw_board()pygame.display.flip()注意:这个示例需要你提供一张名为"board.png"的棋盘图片。

C语言五子棋游戏源代码

C语言五子棋游戏源代码

C语言五子棋游戏源代码Company Document number:WTUT-WT88Y-W8BBGB-BWYTT-19998#i n c l u d e<> #defineN10voidwelcome();voidinitqipan();voidshowqi(inti);voidsave(intp);voidpanduan(intp);voidheqi();voidover();intzouqihang();intzouqilie();/******************结构体*****************/structzuobiao{intx[N*N];inty[N*N];}weizhi[N*N];/******************主函数*****************/voidmain(){intp=0;welcome();initqipan();for(p=1;p<=N*N;p++){weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();save(p);showqi(p);panduan(p);}if(p==N*N)heqi();over();}/******************建立棋盘*****************/voidinitqipan(){inti,j;for(i=0;i<N;i++)printf("%d",i);printf("");}printf("\n");for(i=1;i<N;i++){for(j=0;j<N;j++){if(j==0)printf("%d",i);elseprintf("·");}printf("\n");}}/******************显示棋子*****************/ voidshowqi(intp){inti,j,k,m;inta[N*N],b[N*N];FILE*fp;fp=fopen("wuzi_list","rb");for(i=1;i<=N*N;i++){fread(&weizhi[i],sizeof(structzuobiao),1,fp);a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}for(m=1;m<p;m++){while(weizhi[p].x[p]==a[m]&&weizhi[p].y[p]==b[m]) {printf("error!\n");weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();m=1;}}for(i=0;i<N;i++){printf("%d",i);printf("");}for(i=1;i<N;i++){for(j=1;j<N;j++){if(j==1)printf("%d",i);for(k=1;k<=p;k++){if(i==weizhi[k].x[k]&&j==weizhi[k].y[k]){if(k%2==1){printf("○");break;}elseif(k%2==0){printf("●");break;}}}if(k>p)printf("·");elsecontinue;}printf("\n");}}/******************走棋行*****************/ intzouqihang(){intx;printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d",&x);while(x>N-1||x<1){printf("error!\n");printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d",&x);}returnx;}/******************走棋列*****************/{inty;printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d",&y);while(y>N-1||y<1){printf("error!\n");printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d",&y);}returny;}/******************文件保存*****************/ voidsave(inti){FILE*fp;fp=fopen("wuzi_list","wb");fwrite(&weizhi[i],sizeof(structzuobiao),1,fp);}/****************判断输赢*******************/ voidpanduan(intp){inti,j,k[8]={1,1,1,1,1,1,1,1,};inta[N*N],b[N*N];FILE*fp;fp=fopen("wuzi_list","rb");for(i=1;i<=p;i++){fread(&weizhi[i],sizeof(structzuobiao),1,fp);a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}/*****************判断行******************/ for(i=1;i<=p;i++){if(i%2==1){for(j=1;j<=p;j=j+2)if((a[i]==a[j])&&(b[i]==b[j]-1)) {k[0]++;continue;}elseif((a[i]==a[j])&&(b[i]==b[j]-2)) {k[0]++;continue;}elseif((a[i]==a[j])&&(b[i]==b[j]-3)) {k[0]++;continue;}elseif((a[i]==a[j])&&(b[i]==b[j]-4)) {k[0]++;continue;}elseif(k[0]==5){printf("Player1wins!!!\n");}elsecontinue;}if(k[0]==5)break;k[0]=1;}elseif(k[0]==5)break;elseif(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)) {k[1]++;continue;}elseif((a[i]==a[j])&&(b[i]==b[j]-2)) {k[1]++;}elseif((a[i]==a[j])&&(b[i]==b[j]-3)){k[1]++;continue;}elseif((a[i]==a[j])&&(b[i]==b[j]-4)){k[1]++;continue;}elseif(k[1]==5){printf("Player2wins!!!\n");}elsecontinue;}if(k[1]==5)break;k[1]=1;}}/**********************判断列************************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5)break;elseif(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[2]++;continue;}elseif((a[i]==a[j]-2)&&(b[i]==b[j])){k[2]++;continue;}elseif((a[i]==a[j]-3)&&(b[i]==b[j])){continue;}elseif((a[i]==a[j]-4)&&(b[i]==b[j])) {k[2]++;continue;}elseif(k[2]==5){printf("Player1wins!!!\n");}elsecontinue;}if(k[2]==5)break;k[2]=1;}elseif(k[2]==5)break;elseif(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])) {k[3]++;continue;}elseif((a[i]==a[j]-2)&&(b[i]==b[j])) {k[3]++;continue;}elseif((a[i]==a[j]-3)&&(b[i]==b[j])) {k[3]++;continue;}elseif((a[i]==a[j]-4)&&(b[i]==b[j])) {k[3]++;continue;}elseif(k[3]==5)printf("Player2wins!!!\n");}elsecontinue;}if(k[3]==5)break;k[3]=1;}}/****************判断对角(左上-右下)******************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5)break;elseif(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[4]++;continue;}elseif((a[i]==a[j]-2)&&(b[i]==b[j]-2)){k[4]++;continue;}elseif((a[i]==a[j]-3)&&(b[i]==b[j]-3)){k[4]++;continue;}elseif((a[i]==a[j]-4)&&(b[i]==b[j]-4)){k[4]++;continue;}elseif(k[4]==5){printf("Player1wins!!!\n");}else}if(k[4]==5)break;k[4]=1;}elseif(k[2]==5)break;elseif(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[5]++;continue;}elseif((a[i]==a[j]-2)&&(b[i]==b[j]-2)){k[5]++;continue;}elseif((a[i]==a[j]-3)&&(b[i]==b[j]-3)){k[5]++;continue;}elseif((a[i]==a[j]-4)&&(b[i]==b[j]-4)){k[5]++;continue;}elseif(k[5]==5){printf("Player2wins!!!\n");}elsecontinue;}if(k[5]==5)break;k[5]=1;}}/**********判断对角(左下-右上)************/{if(k[0]==5||k[1]==5||k[2]==5||k[3]==5||k[4]==5||k[5]==5) break;elseif(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[6]++;continue;}elseif((a[i]==a[j]+2)&&(b[i]==b[j]-2)){k[6]++;continue;}elseif((a[i]==a[j]+3)&&(b[i]==b[j]-3)){k[6]++;continue;}elseif((a[i]==a[j]+4)&&(b[i]==b[j]-4)){k[6]++;continue;}elseif(k[6]==5){printf("Player1wins!!!\n");}elsecontinue;}if(k[6]==5)break;k[6]=1;}elseif(k[6]==5)break;elseif(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[7]++;continue;}elseif((a[i]==a[j]+2)&&(b[i]==b[j]-2)){k[7]++;continue;}elseif((a[i]==a[j]+3)&&(b[i]==b[j]-3)){k[7]++;continue;}elseif((a[i]==a[j]+4)&&(b[i]==b[j]-4)){k[7]++;continue;}elseif(k[7]==5){printf("Player2wins!!!\n");}elsecontinue;}if(k[7]==5)break;k[7]=1;}}}/****************和棋*******************/ voidheqi(){printf("************************************\n"); printf("Tie!!!\n");printf("************************************\n"); }/****************游戏结束*******************/ voidover(){printf("************************************\n"); printf("gameover!!!\n");printf("************************************\n");}/****************游戏开始*******************/ voidwelcome(){printf("************************************\n"); printf("Welcome!!!\n");printf("************************************\n"); }。

五子棋源代码

五子棋源代码

package resource;import java.awt.BasicStroke;import java.awt.Color;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.geom.Ellipse2D;import java.awt.geom.Line2D;import javax.swing.JPanel;publicclass DrawPanel extends JPanel{privateint[][] a;privateint n,m;public DrawPanel(int k[][],int n1,int m1){a=k;n=n1;m=m1;}publicvoid paintComponent(Graphics g){super.paintComponent(g);Graphics2D g2=(Graphics2D)g;Graphics2D g3=(Graphics2D)g;double X=20;double Y=20;double width=480;double height=480;double jiange=30;// 画棋盘网格for(int i=0;i<=width/jiange;i++){g2.draw(new Line2D.Double(X+i*jiange,Y,X+i*jiange,height+Y));g2.draw(new Line2D.Double(X,Y+i*jiange,width+X,Y+i*jiange));}//画中间点的标记g3.setPaint(Color.RED);g3.draw(new Line2D.Double(254,245,254,254));g3.draw(new Line2D.Double(245,254,254,254));g3.draw(new Line2D.Double(267,245,267,254));g3.draw(new Line2D.Double(267,254,275,254));g3.draw(new Line2D.Double(245,266,254,266));g3.draw(new Line2D.Double(254,266,254,275));g3.draw(new Line2D.Double(266,275,266,266));g3.draw(new Line2D.Double(266,266,275,266));//画旗子for(int i=1;i<a.length-1;i++){for(int j=1;j<a[i].length-1;j++){Ellipse2D circle=new Ellipse2D.Double();circle.setFrame(j*30-25, i*30-25, 28, 28);if(a[i][j]==1){g2.setPaint(Color.BLACK);g2.fill(circle);}elseif(a[i][j]==2){g2.setPaint(Color.WHITE);g2.fill(circle);}}}//画旗子上的标记if(n>0&&m>0){g2.setPaint(Color.RED);g2.setStroke(new BasicStroke(1.5f));g2.draw(new Line2D.Double(30*m-16,30*n-16,30*m-4,30*n-4));g2.draw(new Line2D.Double(30*m-16,30*n-4,30*m-4,30*n-16));}}}package resource;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.Toolkit;import java.awt.Dimension;import javax.swing.JColorChooser;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;publicclass PlayerVsPC {private JFrame frame; //整个窗口private JMenuBar bar; //菜单栏private JMenuItem[][] jit;//菜单项数组private JMenuItem[] mode;//模式项数组private JMenu[] jm; //菜单publicboolean isBlack; //是否为黑方下子状态privateint[][] qipan; //棋盘数组privateint row; //当前行privateint col; //当前列privateint prow;privateint pcol;private DrawPanel panel; //棋盘面板private JLabel label; //棋盘上方的标签private JPanel panel0; //棋盘上方条形面板privateboolean isEnd;privateint[][] qixingPC;privateint[][] qixingPlayer;privateboolean isPC = true; //记录当前下棋模式privateboolean cMode = true; //记录选择的对弈模式public PlayerVsPC(){frame=new JFrame("五子棋游戏");bar=new JMenuBar();jm=new JMenu[2];jit=new JMenuItem[2][];qipan=newint[19][19];qixingPC = newint[17][17];qixingPlayer = newint[17][17];for(int i=0;i<19;i++){for(int j=0;j<19;j++){qipan[i][j]=0;}}for(int i=0;i<17;i++){for(int j=0;j<17;j++){qixingPC[i][j]=0;qixingPlayer[i][j]=0;}}label = new JLabel("人"+(isPC?"机":"人")+"对弈模式,请按开局开始游戏!");panel0=new JPanel();addItems();addEventAction();printqipan(0,0);}publicvoid addItems(){jm[0]=new JMenu("游戏");jm[1]=new JMenu("选项");jit[0]=new JMenuItem[3];jit[0][0]=new JMenuItem("开局");jit[0][1]=new JMenuItem("重新开始");jit[0][2]=new JMenuItem("结束游戏");jit[1]=new JMenuItem[2];jit[1][0]=new JMenu("对弈模式");mode=new JMenuItem[2];mode[0] = new JMenuItem("人人对弈");mode[1] = new JMenuItem("人机对弈");jit[1][0].add(mode[0]);jit[1][0].add(mode[1]);jit[1][1]=new JMenuItem("悔棋");for(int i=0;i<jm.length;i++){for(int j=0;j<jit[i].length;j++){jm[i].add(jit[i][j]);}}panel0.add(label);bar.add(jm[0]);bar.add(jm[1]);frame.setJMenuBar(bar);frame.add(panel0,"North");}//给菜单项设定事件publicvoid addEventAction(){jit[0][0].addActionListener(new ActionListener(){ //开局publicvoid actionPerformed(ActionEvent e) {row=prow=0;col=pcol=0;isPC=cMode;isBlack = true;isEnd = false;for(int i=0;i<19;i++){for(int j=0;j<19;j++){if(i==0||j==0||i==(qipan.length-1)||j==(qipan.length-1)){qipan[i][j] = -1;}else{qipan[i][j]=0;}}}if(isPC){ //人机对弈模式label.setText("游戏开始,请玩家先下棋!");}else{ //人人对弈模式label.setText("游戏开始,请"+(isBlack?"黑":"白")+"方先下棋!");}printqipan(row,col);addEventHandler();}});jit[0][1].addActionListener(new ActionListener(){ //重新开始publicvoid actionPerformed(ActionEvent e) {row=prow=0;col=pcol=0;isBlack = true;isEnd = false;for(int i=0;i<19;i++){for(int j=0;j<19;j++){if(i==0||j==0||i==(qipan.length-1)||j==(qipan.length-1)){qipan[i][j] = -1;}else{qipan[i][j]=0;}}}if(isPC){ //人机对弈模式label.setText("游戏开始,请玩家先下棋!");}else{ //人人对弈模式label.setText("游戏开始,请"+(isBlack?"黑":"白")+"方先下棋!");}printqipan(row,col);addEventHandler();}});//给模式选项添加事件监听mode[0].addActionListener(new ActionListener(){publicvoid actionPerformed(ActionEvent e) {cMode = false;label.setText("已选择人"+(cMode?"机":"人")+"对弈模式,重新开局将生效!");}});mode[1].addActionListener(new ActionListener(){publicvoid actionPerformed(ActionEvent e) {cMode = true;label.setText("已选择人"+(cMode?"机":"人")+"对弈模式,重新开局将生效!");}});jit[0][2].addActionListener(new ActionListener(){ //结束游戏publicvoid actionPerformed(ActionEvent e) {label.setText("游戏结束,请按开局开始游戏!");isEnd=true;}});jit[1][1].addActionListener(new ActionListener(){ //悔棋publicvoid actionPerformed(ActionEvent e) {if(!isPC){huiqi();}else{pchuiqi();}}});}// 监听鼠标事件,下棋以及判断本盘是否结束,电脑是白方,玩家是黑方publicvoid addEventHandler(){panel.addMouseListener(new MouseAdapter(){publicvoid mousePressed(MouseEvent e) {if(!isEnd){int x=(e.getX()-5)/30;int y=(e.getY()-5)/30;if(qipan[y+1][x+1]==0){load(x+1,y+1);}else{label.setText("此处已经有棋子,请重新下子!");}}}});}//电脑下棋publicvoid pcLoad(){qixing();int count = 0;int hang = 0;int lie = 0;for(int i=0;i<17;i++){for(int j=0;j<17;j++){if(qixingPC[i][j]>count){count = qixingPC[i][j];hang = i+1;lie = j+1;}if(qixingPlayer[i][j]>count){count = qixingPlayer[i][j];hang = i+1;lie = j+1;}}}if(qipan[hang][lie]==0){load(lie,hang);return;}}//下棋子publicvoid load(int x,int y){col=x;row=y;if(isBlack){prow=row;pcol=col;qipan[row][col]=1;isBlack = false;}else{qipan[row][col]=2;isBlack = true;}printqipan(row,col);if(panduan(row-1,col-1)){if(isPC){label.setText("本局结束,恭喜"+(isBlack?"电脑":"玩家")+"获胜!");isEnd = true;}else{label.setText("本局结束,恭喜"+(isBlack?"黑":"白")+"方获胜!");isEnd = true;}}else{if(isPC){label.setText((isBlack?"电脑":"玩家")+"在("+row+":"+col+")处下子,"+"现在"+(isBlack?"玩家":"电脑")+"下子!");}else{label.setText((isBlack?"白":"黑")+"方在("+row+":"+col+")处下子,"+"现在"+(isBlack?"黑":"白")+"下子!");}if(!isBlack){if(isPC){pcLoad();}}}}//刷新棋盘publicvoid printqipan(int n,int m){panel=new DrawPanel(qipan,n,m);//panel.setBackground(c);frame.add(panel,"Center");}//人人对弈悔棋publicvoid huiqi(){if(isEnd){label.setText("游戏已经结束不能悔棋,请重新开局!");return;}isBlack=!isBlack;qipan[row][col]=0;printqipan(row,col);label.setText((isBlack?"黑":"白")+"方悔棋,请重新下棋!");}//人机对弈悔棋publicvoid pchuiqi(){if(isEnd){label.setText("游戏已经结束不能悔棋,请重新开局!");return;}qipan[row][col]=0;qipan[prow][pcol]=0;printqipan(row,col);label.setText((isBlack?"玩家":"电脑")+"悔棋,请重新下棋!");}//算出双方的棋形数组publicvoid qixing(){for(int i=0;i<17;i++){for(int j=0;j<17;j++){if(qipan[i+1][j+1]==0){//说明此处没有棋子qixingPC[i][j] =heiheng(i,j,2)+heishu(i,j,2)+heizuoxie(i,j,2)+heiyouxie(i,j,2);qixingPlayer[i][j] =heiheng(i,j,1)+heishu(i,j,1)+heizuoxie(i,j,1)+heiyouxie(i,j,1);}else{qixingPC[i][j] = 0;qixingPlayer[i][j] = 0;}}}}// 算出黑子横方向的棋型数值publicint heiheng(int hang,int lie,int num){int k = 0;//记录空白处的个数int count = 1;//记录可以形成几连int n = hang+1;//对应棋盘的行int m = lie+1;//对应棋盘的列boolean left = false;//判断左边是否有黑子boolean liveLeft = false;//判断左边是活还是死boolean liveRight = false;//判断右边是活还是死while((qipan[n][m-1]!=-1)&&(qipan[n][m-1]==num||qipan[n][m-1]==0)){ if(qipan[n][m-1]==0&&k<1){//第一个空白if(qipan[n][m-2]!=num){liveLeft = true;break;}k++;m--;}elseif(qipan[n][m-1]==num){//黑子left = true;m--;}else{//第二个空白liveLeft = true;break;}}if(!left){k = 0;m = lie+1;}while((qipan[n][m+1]!=-1)&&(qipan[n][m+1]==num||qipan[n][m+1]==0)){ int t = qipan[n][m+1];if(m==lie){count++;m++;continue;}if(t==0&&k<1){//第一个空白if(qipan[n][m+2]!=num){liveRight = true;break;}k++;m++;}elseif(t==0&&k>0){//第二个空白liveRight = true;break;}else{//黑子m++;count++;}}return jieguo(liveLeft,liveRight,count,k,num);}// 算出黑子竖方向的棋型数值publicint heishu(int hang,int lie,int num){int k = 0;//记录空白处的个数int count = 1;//记录可以形成几连int n = hang+1;//对应棋盘的行int m = lie+1;//对应棋盘的列boolean top = false;//判断上边是否有黑子boolean liveLeft = false;boolean liveRight = false;while((qipan[n-1][m]!=-1)&&(qipan[n-1][m]==num||qipan[n-1][m]==0)){ if(qipan[n-1][m]==0&&k<1){//第一个空白if(qipan[n-2][m]!=num){liveLeft = true;break;}k++;n--;}elseif(qipan[n-1][m]==num){//黑子top = true;n--;}else{//第二个空白liveLeft = true;break;}}if(!top){k = 0;n = hang+1;}while((qipan[n+1][m]!=-1)&&(qipan[n+1][m]==num||qipan[n+1][m]==0)){ int t = qipan[n+1][m];if(n==hang){count++;n++;continue;}if(t==0&&k<1){//第一个空白if(qipan[n+2][m]!=num){liveRight = true;break;}k++;n++;}elseif(t==0&&k>0){//第二个空白liveRight = true;break;}else{//黑子n++;count++;}}return jieguo(liveLeft,liveRight,count,k,num);}// 算出黑子左斜方向的棋型数值publicint heizuoxie(int hang,int lie,int num){int k = 0;//记录空白处的个数int count = 1;//记录可以形成几连int n = hang+1;//对应棋盘的行int m = lie+1;//对应棋盘的列boolean top = false;//判断上边是否有黑子boolean liveLeft = false;boolean liveRight = false;while((qipan[n+1][m-1]!=-1)&&(qipan[n+1][m-1]==num||qipan[n+1][m-1]==0)){ if(qipan[n+1][m-1]==0&&k<1){//第一个空白if(qipan[n+2][m-2]!=num){liveLeft = true;break;}k++;n++;m--;}elseif(qipan[n+1][m-1]==num){//黑子top = true;n++;m--;}else{//第二个空白liveLeft = true;break;}}if(!top){k = 0;n = hang+1;m = lie+1;}while((qipan[n-1][m+1]!=-1)&&(qipan[n-1][m+1]==num||qipan[n-1][m+1]==0)){ int t = qipan[n-1][m+1];if(n==(hang+2)&&m==lie){count++;n--;m++;continue;}if(t==0&&k<1){//第一个空白if(qipan[n-2][m+2]!=num){liveRight = true;break;}k++;n--;m++;}elseif(t==0&&k>0){//第二个空白liveRight = true;break;}else{//黑子n--;m++;count++;}}return jieguo(liveLeft,liveRight,count,k,num);}// 算出黑子右斜方向的棋型数值publicint heiyouxie(int hang,int lie,int num){int k = 0;//记录空白处的个数int count = 1;//记录可以形成几连int n = hang+1;//对应棋盘的行int m = lie+1;//对应棋盘的列boolean top = false;//判断上边是否有黑子boolean liveLeft = false;boolean liveRight = false;while((qipan[n-1][m-1]!=-1)&&(qipan[n-1][m-1]==num||qipan[n-1][m-1]==0)){ if(qipan[n-1][m-1]==0&&k<1){//第一个空白if(qipan[n-2][m-2]!=num){liveLeft = true;break;}k++;n--;m--;}elseif(qipan[n-1][m-1]==num){//黑子top = true;n--;m--;}else{//第二个空白liveLeft = true;break;}}if(!top){k = 0;n = hang+1;m = lie+1;}while((qipan[n+1][m+1]!=-1)&&(qipan[n+1][m+1]==num||qipan[n+1][m+1]==0)){ int t = qipan[n+1][m+1];if(n==hang&&m==lie){count++;n++;m++;continue;}if(t==0&&k<1){//第一个空白if(qipan[n+2][m+2]!=num){liveRight = true;break;}k++;n++;m++;}elseif(t==0&&k>0){//第二个空白liveRight = true;break;}else{//黑子n++;m++;count++;}}return jieguo(liveLeft,liveRight,count,k,num);}publicint jieguo(boolean left,boolean right,int count,int k,int num){ if(count==1){return 0;}elseif(count==2){if(left&&right){if(k==0){if(num==2){return 60;}else{return 50;}}else{if(num==2){return 40;}else{return 35;}}}elseif(!left&&!right){return 0;}else{return 10;}}elseif(count==3){if(left&&right){if(k==0){if(num==2){return 950;}else{return 700;}}else{if(num==2){return 900;}else{return 650;}}}elseif(!left&&!right){return 0;}else{return 100;}}elseif(count==4){if(left&&right){if(k==0){if(num==2){return 6000;}else{return 3500;}}else{if(num==2){return 5000;}else{return 3000;}}}elseif(!left&&!right){return 0;}else{if(k==0){if(num==2){return 4000;}else{return 800;}}else{if(num==2){return 3600;}else{return 750;}}}}else{if(k==0){if(num==2){return 20000;}else{return 15000;}}else{if(num==2){return 10000;}else{return 3300;}}}}publicvoid showMe(){frame.setSize(530,600);Toolkit kit = Toolkit.getDefaultToolkit();Dimension screenSize = kit.getScreenSize();int width = screenSize.width;int height = screenSize.height;int x = (int)(width-600)/2;int y = (int)(height-530)/2-50;frame.setLocation(x,y);frame.setVisible(true);frame.setResizable(false);frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); }publicstaticvoid main(String[] args) {new PlayerVsPC().showMe();}publicboolean panduan(int n,int m){if(heng(n,m)||shu(n,m)||zuoxie(n,m)||youxie(n,m)){ returntrue;}returnfalse;}publicboolean heng(int n,int m){int i=n+1,j=m+1;int count=1;while(qipan[i][j-1]==qipan[n+1][m+1]){ j--;}while(qipan[i][j+1]==qipan[n+1][m+1]){ count++;j++;}if(count>4){returntrue;}returnfalse;}publicboolean shu(int n,int m){int i=n+1,j=m+1;int count=1;while(qipan[i-1][j]==qipan[n+1][m+1]){ i--;}while(qipan[i+1][j]==qipan[n+1][m+1]){ count++;i++;}if(count>4){returntrue;}returnfalse;}publicboolean youxie(int n,int m){int i=n+1,j=m+1;int count=1;while(qipan[i-1][j-1]==qipan[n+1][m+1]){ i--;j--;}while(qipan[i+1][j+1]==qipan[n+1][m+1]){ count++;i++;j++;}if(count>4){returntrue;}returnfalse;}publicboolean zuoxie(int n,int m){int i=n+1,j=m+1;int count=1;while(qipan[i+1][j-1]==qipan[n+1][m+1]){i++;j--;}while(qipan[i-1][j+1]==qipan[n+1][m+1]){count++;i--;j++;}if(count>4){returntrue;}returnfalse;}}。

五子棋源代码

五子棋源代码

#include<stdio.h>#include<stdlib.h>#include<graphics.h>#include<bios.h>#include<conio.h>#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011b#define SPACE 0x3920#define BILI 20#define JZ 4#define JS 3#define N 19int box[N][N];int step_x,step_y ;int key ;int flag=1 ;void draw_box();void draw_cicle(int x,int y,int color);void change();void judgewho(int x,int y);void judgekey();int judgeresult(int x,int y);void attentoin();void attention(){char ch ;window(1,1,80,25);textbackground(LIGHTBLUE);textcolor(YELLOW);clrscr();gotoxy(15,2);printf("游戏操作规则:");gotoxy(15,4);printf("Play Rules:");gotoxy(15,6);printf("1、按左右上下方向键移动棋子");gotoxy(15,8);printf("1. Press Left,Right,Up,Down Key to move Piece");gotoxy(15,10);printf("2、按空格确定落棋子");gotoxy(15,12);printf("2. Press Space to place the Piece");gotoxy(15,14);printf("3、禁止在棋盘外按空格");gotoxy(15,16);printf("3. DO NOT press Space outside of the chessboard");gotoxy(15,18);printf("你是否接受上述的游戏规则(Y/N)");gotoxy(15,20);printf("Do you accept the above Playing Rules? [Y/N]:");while(1){gotoxy(60,20);ch=getche();if(ch=='Y'||ch=='y')break ;else if(ch=='N'||ch=='n'){window(1,1,80,25);textbackground(BLACK);textcolor(LIGHTGRAY);clrscr();exit(0);}gotoxy(51,12);printf(" ");}}void draw_box(){int x1,x2,y1,y2 ;setbkcolor(LIGHTBLUE);setcolor(YELLOW);gotoxy(7,2);printf("Left, Right, Up, Down KEY to move, Space to put, ESC-quit."); for(x1=1,y1=1,y2=18;x1<=18;x1++)line((x1+JZ)*BILI,(y1+JS)*BILI,(x1+JZ)*BILI,(y2+JS)*BILI);for(x1=1,y1=1,x2=18;y1<=18;y1++)line((x1+JZ)*BILI,(y1+JS)*BILI,(x2+JZ)*BILI,(y1+JS)*BILI);for(x1=1;x1<=18;x1++)for(y1=1;y1<=18;y1++)box[x1][y1]=0 ;}void draw_circle(int x,int y,int color) {setcolor(color);setlinestyle(SOLID_LINE,0,1);x=(x+JZ)*BILI ;y=(y+JS)*BILI ;circle(x,y,8);}void judgekey(){int i ;int j ;switch(key){case LEFT :if(step_x-1<0)break ;else{for(i=step_x-1,j=step_y;i>=1;i--)if(box[i][j]==0){draw_circle(step_x,step_y,LIGHTBLUE); break ;}if(i<1)break ;step_x=i ;judgewho(step_x,step_y);break ;}case RIGHT :if(step_x+1>18)break ;else{for(i=step_x+1,j=step_y;i<=18;i++)if(box[i][j]==0){draw_circle(step_x,step_y,LIGHTBLUE); break ;}if(i>18)break ;step_x=i ;judgewho(step_x,step_y);break ;}case DOWN :if((step_y+1)>18)break ;else{for(i=step_x,j=step_y+1;j<=18;j++)if(box[i][j]==0){draw_circle(step_x,step_y,LIGHTBLUE); break ;}if(j>18)break ;step_y=j ;judgewho(step_x,step_y);break ;}case UP :if((step_y-1)<0)break ;else{for(i=step_x,j=step_y-1;j>=1;j--)if(box[i][j]==0){draw_circle(step_x,step_y,LIGHTBLUE); break ;}if(j<1)break ;step_y=j ;judgewho(step_x,step_y);break ;}case ESC :break ;case SPACE :if(step_x>=1&&step_x<=18&&step_y>=1&&step_y<=18) {if(box[step_x][step_y]==0){box[step_x][step_y]=flag ;if(judgeresult(step_x,step_y)==1){sound(1000);delay(1000);nosound();gotoxy(30,4);if(flag==1){setbkcolor(BLUE);cleardevice();setviewport(100,100,540,380,1);/*定义一个图形窗口*/setfillstyle(1,2);/*绿色以实填充*/setcolor(YELLOW);rectangle(0,0,439,279);floodfill(50,50,14);setcolor(12);settextstyle(1,0,5);/*三重笔划字体, 水平放?5倍*/outtextxy(20,20,"The White Win !");setcolor(15);settextstyle(3,0,5);/*无衬笔划字体, 水平放大5倍*/outtextxy(120,120,"The White Win !");setcolor(14);settextstyle(2,0,8);getch();closegraph();exit(0);}if(flag==2){setbkcolor(BLUE);cleardevice();setviewport(100,100,540,380,1);/*定义一个图形窗口*/setfillstyle(1,2);/*绿色以实填充*/setcolor(YELLOW);rectangle(0,0,439,279);floodfill(50,50,14);setcolor(12);settextstyle(1,0,8);/*三重笔划字体, 水平放大8倍*/ outtextxy(20,20,"The Red Win !"); setcolor(15);settextstyle(3,0,5);/*无衬笔划字体, 水平放大5倍*/ outtextxy(120,120,"The Red Win !"); setcolor(14);settextstyle(2,0,8);getch();closegraph();exit(0);}}change();break ;}}elsebreak ;}}void change(){if(flag==1)flag=2 ;elseflag=1 ;}void judgewho(int x,int y){if(flag==1)draw_circle(x,y,15);if(flag==2)draw_circle(x,y,4);}int judgeresult(int x,int y) {int j,k,n1,n2 ;while(1){n1=0 ;n2=0 ;/*水平向左数*/for(j=x,k=y;j>=1;j--) {if(box[j][k]==flag)n1++;elsebreak ;}/*水平向右数*/for(j=x,k=y;j<=18;j++) {if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){return(1);break ;}/*垂直向上数*/n1=0 ;n2=0 ;for(j=x,k=y;k>=1;k--) {if(box[j][k]==flag)n1++;elsebreak ;}/*垂直向下数*/for(j=x,k=y;k<=18;k++) {if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){return(1);break ;}/*向左上方数*/n1=0 ;n2=0 ;for(j=x,k=y;j>=1,k>=1;j--,k--) {if(box[j][k]==flag)n1++;elsebreak ;}/*向右下方数*/for(j=x,k=y;j<=18,k<=18;j++,k++) {if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){return(1);break ;}/*向右上方数*/n1=0 ;n2=0 ;for(j=x,k=y;j<=18,k>=1;j++,k--) {if(box[j][k]==flag)n1++;elsebreak ;/*向左下方数*/for(j=x,k=y;j>=1,k<=18;j--,k++) {if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){return(1);break ;}return(0);break ;}}void main(){int gdriver=VGA,gmode=VGAHI; clrscr();attention();initgraph(&gdriver,&gmode,"c:\\tc"); /* setwritemode(XOR_PUT);*/flag=1 ;draw_box();do{step_x=0 ;step_y=0 ;/*draw_circle(step_x,step_y,8); */ judgewho(step_x-1,step_y-1);do{while(bioskey(1)==0);key=bioskey(0);judgekey();}while(key!=SPACE&&key!=ESC); }while(key!=ESC);closegraph();。

C语言五子棋游戏源代码

C语言五子棋游戏源代码

#include<>#define N 10void welcome();void initqipan();void showqi(int i);void save(int p);void panduan(int p);void heqi();void over();int zouqihang();int zouqilie();/******************结构体*****************/ struct zuobiao{int x[N*N];int y[N*N];}weizhi[N*N];/******************主函数*****************/ void main(){int p=0;welcome();initqipan();for(p=1;p<=N*N;p++){weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();save(p);showqi(p);panduan(p);}if(p==N*N)heqi();over();}/******************建立棋盘*****************/ void initqipan(){int i,j;for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=0;j<N;j++){if(j==0)printf("%d",i);elseprintf("·");}printf("\n");}}/******************显示棋子*****************/void showqi(int p){int i,j,k,m;int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=N*N;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp);a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}for(m=1;m<p;m++){while(weizhi[p].x[p]==a[m]&&weizhi[p].y[p]==b[m]){printf("error!\n");weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();m=1;}}for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=1;j<N;j++){if(j==1)printf("%d",i);for(k=1;k<=p;k++){if(i==weizhi[k].x[k]&&j==weizhi[k].y[k]){if(k%2==1){printf("○");break;}else if(k%2==0){printf("●");break;}}}if(k>p)printf("·");else continue;}printf("\n");}}/******************走棋行*****************/int zouqihang(){int x;printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d",&x);while(x>N-1||x<1){printf("error!\n");printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d",&x);}return x;}/******************走棋列*****************/int zouqilie(){int y;printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d",&y);while(y>N-1||y<1){printf("error!\n");printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d",&y);}return y;}/******************文件保存*****************/ void save(int i){FILE *fp;fp=fopen("wuzi_list","wb");fwrite(&weizhi[i],sizeof(struct zuobiao),1,fp);}/****************判断输赢*******************/ void panduan(int p){int i,j,k[8]={1,1,1,1,1,1,1,1,};int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=p;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp);a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}/*****************判断行******************/ for(i=1;i<=p;i++){if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)){k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)){k[0]++;continue;else if((a[i]==a[j])&&(b[i]==b[j]-3)){k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4)){k[0]++;continue;}else if(k[0]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[0]==5)break;k[0]=1;}else if(k[0]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)){k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)){k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-3)){k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4))k[1]++;continue;}else if(k[1]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[1]==5)break;k[1]=1;}}/**********************判断列************************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[2]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])){k[2]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])){k[2]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])){k[2]++;continue;else if(k[2]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[2]==5)break;k[2]=1;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[3]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])){k[3]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])){k[3]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])){k[3]++;continue;}else if(k[3]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[3]==5)break;k[3]=1;}}/****************判断对角(左上-右下)******************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[4]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)){k[4]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)){k[4]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)){k[4]++;continue;}else if(k[4]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[4]==5)break;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[5]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)){k[5]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)){k[5]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)){k[5]++;continue;}else if(k[5]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[5]==5)break;k[5]=1;}}/**********判断对角(左下-右上)************/for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5||k[4]==5||k[5]==5)else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[6]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)){k[6]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3)){k[6]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4)){k[6]++;continue;}else if(k[6]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[6]==5)break;k[6]=1;}else if(k[6]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[7]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)){k[7]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3)){k[7]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4)){k[7]++;continue;}else if(k[7]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[7]==5)break;k[7]=1;}}}/****************和棋*******************/void heqi(){printf("************************************\n");printf(" Tie!!!\n");printf("************************************\n"); }/****************游戏结束*******************/void over(){printf("************************************\n");printf(" game over!!!\n");printf("************************************\n");}/****************游戏开始*******************/void welcome(){printf("************************************\n");printf(" Welcome!!!\n");printf("************************************\n"); }。

C语言五子棋游戏源代码

C语言五子棋游戏源代码

#define N 10void welcome();void initqipan();void showqi(int i);void save(int p);void panduan(int p);void heqi();void over();int zouqihang();int zouqilie();/******************结构体*****************/ struct zuobiao{int x[N*N];int y[N*N];}weizhi[N*N];/******************主函数*****************/ void main(){int p=0;welcome();initqipan();for(p=1;p<=N*N;p++){weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();save(p);showqi(p);panduan(p);}if(p==N*N)heqi();over();}/******************建立棋盘*****************/ void initqipan(){int i,j;for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=0;j<N;j++){if(j==0)printf("%d",i);elseprintf("·");}printf("\n");}}/******************显示棋子*****************/ void showqi(int p){int i,j,k,m;int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=N*N;i++)fread(&weizhi[i],sizeof(struct zuobiao),1,fp);a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}for(m=1;m<p;m++){while(weizhi[p].x[p]==a[m]&&weizhi[p].y[p]==b[m]) {printf("error!\n");weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();m=1;}}for(i=0;i<N;i++)printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=1;j<N;j++){if(j==1)printf("%d",i);for(k=1;k<=p;k++){if(i==weizhi[k].x[k]&&j==weizhi[k].y[k]) {if(k%2==1){printf("○");break;} else if(k%2==0){printf("●");break;} }}if(k>p)printf("·");else continue;}printf("\n");}}/******************走棋行*****************/ int zouqihang(){int x;printf("请输入要走棋子所在行数!\n");scanf("%d",&x);while(x>N-1||x<1){printf("error!\n");printf("请输入要走棋子所在行数!\n"); printf("x=");scanf("%d",&x);}return x;}/******************走棋列*****************/ int zouqilie(){int y;printf("请输入要走棋子所在列数!\n");scanf("%d",&y);while(y>N-1||y<1){printf("error!\n");printf("请输入要走棋子所在列数!\n"); printf("y=");scanf("%d",&y);}return y;}/******************文件保存*****************/ void save(int i){FILE *fp;fp=fopen("wuzi_list","wb");fwrite(&weizhi[i],sizeof(struct zuobiao),1,fp);}/****************判断输赢*******************/void panduan(int p){int i,j,k[8]={1,1,1,1,1,1,1,1,};int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=p;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp); a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}/*****************判断行******************/for(i=1;i<=p;i++){if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)){k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)) {k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-3)) {k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4)) {k[0]++;continue;}else if(k[0]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[0]==5)break;k[0]=1;}else if(k[0]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-3)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4)) {k[1]++;continue;}else if(k[1]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[1]==5)break;k[1]=1;}}/**********************判断列************************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[2]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])) {k[2]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])) {k[2]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])) {k[2]++;continue;}else if(k[2]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[2]==5)break;k[2]=1;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[3]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])) {k[3]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])) {k[3]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])) {k[3]++;continue;}else if(k[3]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[3]==5)break;k[3]=1;}}/****************判断对角(左上-右下)******************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[4]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)) {k[4]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)) {k[4]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)) {k[4]++;continue;}else if(k[4]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[4]==5)break;k[4]=1;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[5]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)) {k[5]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)) {k[5]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)) {k[5]++;continue;}else if(k[5]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[5]==5)break;k[5]=1;}}/**********判断对角(左下-右上)************/for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5||k[4]==5||k[5]==5) break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[6]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)) {k[6]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3)) {k[6]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4))k[6]++;continue;}else if(k[6]==5){printf("Player 1 wins!!!\n"); }elsecontinue;}if(k[6]==5)break;k[6]=1;}else if(k[6]==5)else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[7]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)) {k[7]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3))k[7]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4)) {k[7]++;continue;}else if(k[7]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[7]==5)break;k[7]=1;}}}/****************和棋*******************/void heqi(){printf("************************************\n"); printf(" Tie!!!\n");printf("************************************\n"); }/****************游戏结束*******************/void over(){printf("************************************\n"); printf(" game over!!!\n");printf("************************************\n"); }/****************游戏开始*******************/void welcome(){printf("************************************\n"); printf(" Welcome!!!\n");printf("************************************\n"); }。

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

Option Explicit
Dim blackturn As Boolean '轮到黑方下子
Dim whiteturn As Boolean '轮到黑方下子
Dim qipan(0 To 15, 0 To 15) As Integer '用此二维数组表示棋盘
Dim inti As Integer '数组元素
Dim intj As Integer
Dim boolF As Boolean '表示棋局状态:进行/结束
Private Sub begin_Click() '重新开始
Me.Cls '清除窗口
For inti = 0 To 15
For intj = 0 To 15
qipan(inti, intj) = 0 '数组清零
Next
Next
Form_Load '重画棋盘
End Sub
Private Sub exit_Click() '退出
Unload Me
Set Form1 = Nothing
End Sub
Private Sub Form_Load()
Form_Paint '画棋盘
blackturn = True '黑方先下
boolF = True '开始
Label1.Caption = "黑方先下"
End Sub
'下子
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
Dim intx As Integer '落子横向位置
Dim inty As Integer '落子竖向位置
If boolF = False Then '确定棋局是否在进行中,否,跳出
Label1.Caption = "结束"
Exit Sub
End If
'确定落子的确切位置
'如果鼠标点击位置不在棋盘中,则跳出
If x < 10 Or x > 310 Or y < 10 Or y > 310 Then
Exit Sub
End If
'如果鼠标点击位置在棋盘中,则转化为相应棋盘落子点的坐标If (x - 10) Mod 20 < 10 Then
intx = x - (x - 10) Mod 20
Else
intx = x + 20 - (x - 10) Mod 20
End If
If (y - 10) Mod 20 < 10 Then
inty = y - (y - 10) Mod 20
Else
inty = y + 20 - (y - 10) Mod 20
End If
'把坐标转换成数组中的相应元素
inti = (intx - 10) / 20
intj = (inty - 10) / 20
'如果该数组元素不为零,即表示棋盘中相应点已有棋子,则跳出If qipan(inti, intj) <> 0 Then
Exit Sub
End If
'画子(圆)
If blackturn = True Then
'黑色
Me.FillColor = RGB(0, 0, 0)
qipan(inti, intj) = 1 '黑子赋1
Label1.Caption = "白方"
Else
'白色
Me.FillColor = RGB(255, 255, 255)
qipan(inti, intj) = 2 '白子赋2
Label1.Caption = "黑方"
End If
Me.FillStyle = 0 '不可缺
Me.Circle (intx, inty), 8
'判断是否有五子连线
Call IfFiveLine
'轮流
blackturn = Not blackturn '取反
End Sub
Private Sub IfFiveLine() '判断是否有五子连线
Dim strwho As String '下子方名称
If qipan(inti, intj) = 1 Then '表示黑方下的子
strwho = "黑方"
Else
strwho = "白方"
End If
'分别判断横竖,对角线是否有五子,此段代码比较复杂,可能那以理解,但其执行效率极高
'非常适合与棋盘格子很多的情况
If samelinenums(1, 0) >= 5 Or samelinenums(0, 1) >= 5 Or samelinenums(1, 1) >= 5 Or samelinenums(-1, 1) >= 5 Then
MsgBox strwho & "胜!"
boolF = False '棋局结束
End If
End Sub
Function samelinenums(changei As Integer, changej As Integer) '判断同一直线上的棋子数
Dim i As Integer
Dim j As Integer
Dim num As Integer '同一线上相同颜色棋子数
'计算落子一边同颜色的棋子数
i = inti: j = intj
Do
If qipan(i, j) <> qipan(inti, intj) Then
num = max(Abs(inti - i), Abs(intj - j))
Exit Do
End If
i = i + changei: j = j + changej
Loop Until i < 0 Or i > 15 Or j < 0 Or j > 15
'计算落子另一边同颜色的棋子数
i = inti: j = intj
Do
If qipan(i, j) <> qipan(inti, intj) Then
num = num - 1 + max(Abs(inti - i), Abs(intj - j))
Exit Do
End If
i = i - changei: j = j - changej
Loop Until i < 0 Or i > 15 Or j < 0 Or j > 15
'MsgBox num
samelinenums = num
End Function
'求较大值
Function max(inta As Integer, intb As Integer)
max = inta
If max < intb Then max = intb
End Function
Private Sub Form_Paint() '以(10,10)为左上角坐标画一个16*16,每格边长为20象素的棋盘
Cls '清除
Dim i As Integer
ScaleMode = 3 '设定窗体画布的单位为象素
For i = 10 To 330 Step 20
Me.Line (10, i)-(330, i)
Me.Line (i, 10)-(i, 330)
Next
End Sub
- j))
Exit Do
End If
i = i - changei: j = j - changej
Loop Until i < 0 Or i > 15 Or j < 0 Or j > 15
'MsgBox num
samelinenums = num
End Function。

相关文档
最新文档