包含java棋牌游戏源码教程的词条

求java小游戏源代码

表1. CheckerDrag.java

// CheckerDrag.javaimport java.awt.*;import java.awt.event.*;public class CheckerDrag extends java.applet.Applet{ // Dimension of checkerboard square. // 棋盘上每个小方格的尺寸 final static int SQUAREDIM = 40; // Dimension of checkerboard — includes black outline. // 棋盘的尺寸 – 包括黑色的轮廓线 final static int BOARDDIM = 8 * SQUAREDIM + 2; // Dimension of checker — 3/4 the dimension of a square. // 棋子的尺寸 – 方格尺寸的3/4 final static int CHECKERDIM = 3 * SQUAREDIM / 4; // Square colors are dark green or white. // 方格的颜色为深绿色或者白色 final static Color darkGreen = new Color (0, 128, 0); // Dragging flag — set to true when user presses mouse button over checker // and cleared to false when user releases mouse button. // 拖动标记 –当用户在棋子上按下鼠标按键时设为true, // 释放鼠标按键时设为false boolean inDrag = false; // Left coordinate of checkerboard’s upper-left corner. // 棋盘左上角的左方向坐标 int boardx; // Top coordinate of checkerboard’s upper-left corner. //棋盘左上角的上方向坐标 int boardy; // Left coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原点(左上角)的左方向坐标 int ox; // Top coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原点(左上角)的上方向坐标 int oy; // Left displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按键时的鼠标坐标与棋子矩形原点之间的左方向位移 int relx; // Top displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按键时的鼠标坐标与棋子矩形原点之间的上方向位移 int rely; // Width of applet drawing area. // applet绘图区域的宽度 int width; // Height of applet drawing area. // applet绘图区域的高度 int height; // Image buffer. // 图像缓冲 Image imBuffer; // Graphics context associated with image buffer. // 图像缓冲相关联的图形背景 Graphics imG; public void init () { // Obtain the size of the applet’s drawing area. // 获取applet绘图区域的尺寸 width = getSize ().width; height = getSize ().height; // Create image buffer. // 创建图像缓冲 imBuffer = createImage (width, height); // Retrieve graphics context associated with image buffer. // 取出图像缓冲相关联的图形背景 imG = imBuffer.getGraphics (); // Initialize checkerboard’s origin, so that board is centered. // 初始化棋盘的原点,使棋盘在屏幕上居中 boardx = (width – BOARDDIM) / 2 + 1; boardy = (height – BOARDDIM) / 2 + 1; // Initialize checker’s rectangle’s starting origin so that checker is // centered in the square located in the top row and second column from // the left. // 初始化棋子矩形的起始原点,使得棋子在第一行左数第二列的方格里居中 ox = boardx + SQUAREDIM + (SQUAREDIM – CHECKERDIM) / 2 + 1; oy = boardy + (SQUAREDIM – CHECKERDIM) / 2 + 1; // Attach a mouse listener to the applet. That listener listens for // mouse-button press and mouse-button release events. // 向applet添加一个用来监听鼠标按键的按下和释放事件的鼠标监听器 addMouseListener (new MouseAdapter () { public void mousePressed (MouseEvent e) { // Obtain mouse coordinates at time of press. // 获取按键时的鼠标坐标 int x = e.getX (); int y = e.getY (); // If mouse is over draggable checker at time // of press (i.e., contains (x, y) returns // true), save distance between current mouse // coordinates and draggable checker origin // (which will always be positive) and set drag // flag to true (to indicate drag in progress). // 在按键时如果鼠标位于可拖动的棋子上方 // (也就是contains (x, y)返回true),则保存当前 // 鼠标坐标与棋子的原点之间的距离(始终为正值)并且 // 将拖动标志设为true(用来表明正处在拖动过程中) if (contains (x, y)) { relx = x – ox; rely = y – oy; inDrag = true; } } boolean contains (int x, int y) { // Calculate center of draggable checker. // 计算棋子的中心位置 int cox = ox + CHECKERDIM / 2; int coy = oy + CHECKERDIM / 2; // Return true if (x, y) locates with bounds // of draggable checker. CHECKERDIM / 2 is the // radius. // 如果(x, y)仍处于棋子范围内则返回true // CHECKERDIM / 2为半径 return (cox – x) * (cox – x) + (coy – y) * (coy – y) CHECKERDIM / 2 * CHECKERDIM / 2; } public void mouseReleased (MouseEvent e) { // When mouse is released, clear inDrag (to // indicate no drag in progress) if inDrag is // already set. // 当鼠标按键被释放时,如果inDrag已经为true, // 则将其置为false(用来表明不在拖动过程中) if (inDrag) inDrag = false; } }); // Attach a mouse motion listener to the applet. That listener listens // for mouse drag events. //向applet添加一个用来监听鼠标拖动事件的鼠标运动监听器 addMouseMotionListener (new MouseMotionAdapter () { public void mouseDragged (MouseEvent e) { if (inDrag) { // Calculate draggable checker’s new // origin (the upper-left corner of // the checker rectangle). // 计算棋子新的原点(棋子矩形的左上角) int tmpox = e.getX () – relx; int tmpoy = e.getY () – rely; // If the checker is not being moved // (at least partly) off board, // assign the previously calculated // origin (tmpox, tmpoy) as the // permanent origin (ox, oy), and // redraw the display area (with the // draggable checker at the new // coordinates). // 如果棋子(至少是棋子的一部分)没有被 // 移出棋盘,则将之前计算的原点 // (tmpox, tmpoy)赋值给永久性的原点(ox, oy), // 并且刷新显示区域(此时的棋子已经位于新坐标上) if (tmpox boardx tmpoy boardy tmpox + CHECKERDIM boardx + BOARDDIM tmpoy + CHECKERDIM boardy + BOARDDIM) { ox = tmpox; oy = tmpoy; repaint (); } } } }); } public void paint (Graphics g) { // Paint the checkerboard over which the checker will be dragged. // 在棋子将要被拖动的位置上绘制棋盘 paintCheckerBoard (imG, boardx, boardy); // Paint the checker that will be dragged. // 绘制即将被拖动的棋子 paintChecker (imG, ox, oy); // Draw contents of image buffer. // 绘制图像缓冲的内容 g.drawImage (imBuffer, 0, 0, this); } void paintChecker (Graphics g, int x, int y) { // Set checker shadow color. // 设置棋子阴影的颜色 g.setColor (Color.black); // Paint checker shadow. // 绘制棋子的阴影 g.fillOval (x, y, CHECKERDIM, CHECKERDIM); // Set checker color. // 设置棋子颜色 g.setColor (Color.red); // Paint checker. // 绘制棋子 g.fillOval (x, y, CHECKERDIM – CHECKERDIM / 13, CHECKERDIM – CHECKERDIM / 13); } void paintCheckerBoard (Graphics g, int x, int y) { // Paint checkerboard outline. // 绘制棋盘轮廓线 g.setColor (Color.black); g.drawRect (x, y, 8 * SQUAREDIM + 1, 8 * SQUAREDIM + 1); // Paint checkerboard. // 绘制棋盘 for (int row = 0; row 8; row++) { g.setColor (((row 1) != 0) ? darkGreen : Color.white); for (int col = 0; col 8; col++) { g.fillRect (x + 1 + col * SQUAREDIM, y + 1 + row * SQUAREDIM, SQUAREDIM, SQUAREDIM); g.setColor ((g.getColor () == darkGreen) ? Color.white : darkGreen); } } } // The AWT invokes the update() method in response to the repaint() method // calls that are made as a checker is dragged. The default implementation // of this method, which is inherited from the Container class, clears the // applet’s drawing area to the background color prior to calling paint(). // This clearing followed by drawing causes flicker. CheckerDrag overrides // update() to prevent the background from being cleared, which eliminates // the flicker. // AWT调用了update()方法来响应拖动棋子时所调用的repaint()方法。该方法从 // Container类继承的默认实现会在调用paint()之前,将applet的绘图区域清除 // 为背景色,这种绘制之后的清除就导致了闪烁。CheckerDrag重写了update()来 // 防止背景被清除,从而消除了闪烁。 public void update (Graphics g) { paint (g); }}

谁有Java 游戏编程开发教程这本书二人麻将游戏源代码或这本书的电子版

String []mapimg={“source/font.png”,”source/ks.jpg”,”source/1.jpg”,”source/2.png”,

“source/3.jpg”,”source/youknow.jpg”,”fight/js.jpg”,”fight/js1.jpg”};

//获得工具包

Toolkit tool=Toolkit.getDefaultToolkit()

//开始图片

Image startimg;

//背景图片

Image bjimg,fontimg;

//画开始界面

public void drawstart(Graphics g){

startimg=tool.getImage(mapimg[1]);

g.drawImage(startimg, 0, 0, frame.getWidth(), frame.getHeight(), frame);

fontimg=tool.getImage(mapimg[0]);

g.drawImage(fontimg, 20, 30, frame);

};

这是我以前做的一个很简单的游戏中的几行代码,对你的问题,你要手动选择图片,那做个文件选择器,把图片路径作为方法参数传进去就ok了

大神们 急求基于eclipse的java小游戏程序的源码,程序不要多复杂啊。像坦克大战,五子棋,扫雷之类的谢谢

import java.util.Scanner;

public class Wuziqi {

/**

* 棋盘

*/

private final int[][] qipan;

/**

* 步数

*/

private int bushu;

/**

* 构造方法,设置棋盘规格

* @param x

* @param y

*/

public Wuziqi(int x, int y) {

if (x 1 || y 1) {

System.out.println(“棋盘规格应不小于1,使用默认规格”);

qipan = new int[9][9];

} else {

qipan = new int[y][x];

}

}

/**

* 游戏开始

*/

public void play() {

int[] zuobiao = null;

//如果游戏没有结束

while (!end(zuobiao)) {

//落子,并取得坐标

zuobiao = luozi();

//输出棋盘

out();

}

}

/**

* 输出棋盘和棋子

*/

private void out() {

for (int i = 0; i qipan.length; i++) {

for (int j = 0; j qipan[i].length; j++) {

if (qipan[i][j] == 0) {

System.out.print(”  +”);

}else if (qipan[i][j] == -1) {

System.out.print(”  白”);

}else if (qipan[i][j] == 1) {

System.out.print(”  黑”);

}

}

System.out.println(” “);

}

}

/**

* 落子

*/

private int[] luozi() {

int[] zuobiao;

bushu++;

if (bushu % 2 == 1) {

System.out.println(“请黑方落子”);

zuobiao = input();

qipan[zuobiao[1]][zuobiao[0]] = 1;

}else {

System.out.println(“请白方落子”);

zuobiao = input();

qipan[zuobiao[1]][zuobiao[0]] = -1;

}

return zuobiao;

}

/**

* 输入坐标

* @return

*/

private int[] input() {

Scanner sc = new Scanner(System.in);

System.out.println(“请输入x轴坐标”);

String x = sc.next();

System.out.println(“请输入y轴坐标”);

String y = sc.next();

//如果没有通过验证,则再次执行input(),递归算法

if (!validate(x, y)) {

return input();

}

int int_x = Integer.valueOf(x);

int int_y = Integer.valueOf(y);

return new int[] {int_x, int_y};

}

/**

* 校验数据

* @param x

* @param y

* @return

*/

private boolean validate(String x, String y) {

Integer int_x = null;

Integer int_y = null;

//异常处理的方式判断字符串是否是一个整数

try {

int_x = Integer.valueOf(x);

int_y = Integer.valueOf(y);

} catch (NumberFormatException e) {

System.out.println(“坐标格式错误,坐标应为整数”);

return false;

}

if (int_x 0 || int_y 0 || int_x = qipan[0].length || int_y = qipan.length) {

System.out.println(“坐标越界”);

return false;

}

if (qipan[int_y][int_x] == 0) {

return true;

} else {

System.out.println(“坐标上已有棋子”);

}

return false;

};

/**

* 结束条件

* @return

*/

private boolean end(int[] zuobiao) {

if (zuobiao == null) {

return false;

}

//计数器

//表示棋盘上经过最近落子坐标的4条线上的连续(和最近落子颜色相同的)棋子的个数

//如果某条线上连续的棋子大于等于4(加上最近落子本身,大于等于5),则游戏结束,符合五子棋规则

int[] jieguo = new int[4];

int x = zuobiao[0];

int y = zuobiao[1];

//定义八个方向

final int[][] fangxiang = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}};

//最近落子的坐标上的棋子颜色

int number = qipan[y][x];

//搜索最近落子坐标为中心最远4的距离

for (int i = 1; i = 4; i++) {

//每次搜索不同的距离都搜索八个方向

for (int j = 0; j fangxiang.length; j++) {

//约定如果某个方向为null时,不再搜索这个方向。关键字continue是跳过本次(一次)循环的意思

if (fangxiang[j] == null) {

continue;

}

int mubiao_x = x + i * fangxiang[j][0];

int mubiao_y = y + i * fangxiang[j][1];

//如果搜索坐标相对于棋盘越界,则不再搜索这个方向

if (mubiao_y = qipan.length || mubiao_y 0 || mubiao_x = qipan[0].length || mubiao_x 0) {

fangxiang[j] = null;

continue;

}

//如果最近落子坐标上的值等于目标坐标上的值(颜色相同),则计数器上某条线加1

//否则认为这个方向没有棋子或有别的颜色的棋子,不再搜索这个方向

if (number == qipan[mubiao_y][mubiao_x]) {

jieguo[j % 4]++;

}else {

fangxiang[j] = null;

}

}

}

//查看计数器上是否有比3更大的数(查看是否有一方胜出)

for (int i : jieguo) {

if (i 3) {

System.out.println(“游戏结束”);

if (bushu % 2 == 1) {

System.out.println(“黑方胜”);

} else {

System.out.println(“白方胜”);

}

return true;

}

}

//没有胜出者的情况下,查看棋盘上是否还有空位置,如果有,则游戏可以继续

for (int[] arr : qipan) {

for (int i : arr) {

if (i == 0) {

return false;

}

}

}

//如果没有空位置,则平局

System.out.println(“游戏结束,平局”);

return true;

}

}

包含java棋牌游戏源码教程的词条

用JAVA做五子棋源代码

java网络五子棋

下面的源代码分为4个文件;

chessClient.java:客户端主程序。

chessInterface.java:客户端的界面。

chessPad.java:棋盘的绘制。

chessServer.java:服务器端。

可同时容纳50个人同时在线下棋,聊天。

没有加上详细注释,不过绝对可以运行,j2sdk1.4下通过。

/*********************************************************************************************

1.chessClient.java

**********************************************************************************************/

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

import java.util.*;

class clientThread extends Thread

{

chessClient chessclient;

clientThread(chessClient chessclient)

{

this.chessclient=chessclient;

}

public void acceptMessage(String recMessage)

{

if(recMessage.startsWith(“/userlist “))

{

StringTokenizer userToken=new StringTokenizer(recMessage,” “);

int userNumber=0;

chessclient.userpad.userList.removeAll();

chessclient.inputpad.userChoice.removeAll();

chessclient.inputpad.userChoice.addItem(“所有人”);

while(userToken.hasMoreTokens())

{

String user=(String)userToken.nextToken(” “);

if(userNumber0 !user.startsWith(“[inchess]”))

{

chessclient.userpad.userList.add(user);

chessclient.inputpad.userChoice.addItem(user);

}

userNumber++;

}

chessclient.inputpad.userChoice.select(“所有人”);

}

else if(recMessage.startsWith(“/yourname “))

{

chessclient.chessClientName=recMessage.substring(10);

chessclient.setTitle(“Java五子棋客户端 “+”用户名:”+chessclient.chessClientName);

}

else if(recMessage.equals(“/reject”))

{

try

{

chessclient.chesspad.statusText.setText(“不能加入游戏”);

chessclient.controlpad.cancelGameButton.setEnabled(false);

chessclient.controlpad.joinGameButton.setEnabled(true);

chessclient.controlpad.creatGameButton.setEnabled(true);

}

catch(Exception ef)

{

chessclient.chatpad.chatLineArea.setText(“chessclient.chesspad.chessSocket.close无法关闭”);

}

chessclient.controlpad.joinGameButton.setEnabled(true);

}

else if(recMessage.startsWith(“/peer “))

{

chessclient.chesspad.chessPeerName=recMessage.substring(6);

if(chessclient.isServer)

{

chessclient.chesspad.chessColor=1;

chessclient.chesspad.isMouseEnabled=true;

chessclient.chesspad.statusText.setText(“请黑棋下子”);

}

else if(chessclient.isClient)

{

chessclient.chesspad.chessColor=-1;

chessclient.chesspad.statusText.setText(“已加入游戏,等待对方下子…”);

}

}

else if(recMessage.equals(“/youwin”))

{

chessclient.isOnChess=false;

chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);

chessclient.chesspad.statusText.setText(“对方退出,请点放弃游戏退出连接”);

chessclient.chesspad.isMouseEnabled=false;

}

else if(recMessage.equals(“/OK”))

{

chessclient.chesspad.statusText.setText(“创建游戏成功,等待别人加入…”);

}

else if(recMessage.equals(“/error”))

{

chessclient.chatpad.chatLineArea.append(“传输错误:请退出程序,重新加入 \n”);

}

else

{

chessclient.chatpad.chatLineArea.append(recMessage+”\n”);

chessclient.chatpad.chatLineArea.setCaretPosition(

chessclient.chatpad.chatLineArea.getText().length());

}

}

public void run()

{

String message=””;

try

{

while(true)

{

message=chessclient.in.readUTF();

acceptMessage(message);

}

}

catch(IOException es)

{

}

}

}

public class chessClient extends Frame implements ActionListener,KeyListener

{

userPad userpad=new userPad();

chatPad chatpad=new chatPad();

controlPad controlpad=new controlPad();

chessPad chesspad=new chessPad();

inputPad inputpad=new inputPad();

Socket chatSocket;

DataInputStream in;

DataOutputStream out;

String chessClientName=null;

String host=null;

int port=4331;

boolean isOnChat=false; //在聊天?

boolean isOnChess=false; //在下棋?

boolean isGameConnected=false; //下棋的客户端连接?

boolean isServer=false; //如果是下棋的主机

boolean isClient=false; //如果是下棋的客户端

Panel southPanel=new Panel();

Panel northPanel=new Panel();

Panel centerPanel=new Panel();

Panel westPanel=new Panel();

Panel eastPanel=new Panel();

chessClient()

{

super(“Java五子棋客户端”);

setLayout(new BorderLayout());

host=controlpad.inputIP.getText();

westPanel.setLayout(new BorderLayout());

westPanel.add(userpad,BorderLayout.NORTH);

westPanel.add(chatpad,BorderLayout.CENTER);

westPanel.setBackground(Color.pink);

inputpad.inputWords.addKeyListener(this);

chesspad.host=controlpad.inputIP.getText();

centerPanel.add(chesspad,BorderLayout.CENTER);

centerPanel.add(inputpad,BorderLayout.SOUTH);

centerPanel.setBackground(Color.pink);

controlpad.connectButton.addActionListener(this);

controlpad.creatGameButton.addActionListener(this);

controlpad.joinGameButton.addActionListener(this);

controlpad.cancelGameButton.addActionListener(this);

controlpad.exitGameButton.addActionListener(this);

controlpad.creatGameButton.setEnabled(false);

controlpad.joinGameButton.setEnabled(false);

controlpad.cancelGameButton.setEnabled(false);

southPanel.add(controlpad,BorderLayout.CENTER);

southPanel.setBackground(Color.pink);

addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

if(isOnChat)

{

try

{

chatSocket.close();

}

catch(Exception ed)

{

}

}

if(isOnChess || isGameConnected)

{

try

{

chesspad.chessSocket.close();

}

catch(Exception ee)

{

}

}

System.exit(0);

}

public void windowActivated(WindowEvent ea)

{

}

});

add(westPanel,BorderLayout.WEST);

add(centerPanel,BorderLayout.CENTER);

add(southPanel,BorderLayout.SOUTH);

pack();

setSize(670,548);

setVisible(true);

setResizable(false);

validate();

}

public boolean connectServer(String serverIP,int serverPort) throws Exception

{

try

{

chatSocket=new Socket(serverIP,serverPort);

in=new DataInputStream(chatSocket.getInputStream());

out=new DataOutputStream(chatSocket.getOutputStream());

clientThread clientthread=new clientThread(this);

clientthread.start();

isOnChat=true;

return true;

}

catch(IOException ex)

{

chatpad.chatLineArea.setText(“chessClient:connectServer:无法连接,建议重新启动程序 \n”);

}

return false;

}

public void actionPerformed(ActionEvent e)

{

if(e.getSource()==controlpad.connectButton)

{

host=chesspad.host=controlpad.inputIP.getText();

try

{

if(connectServer(host,port))

{

chatpad.chatLineArea.setText(“”);

controlpad.connectButton.setEnabled(false);

controlpad.creatGameButton.setEnabled(true);

controlpad.joinGameButton.setEnabled(true);

chesspad.statusText.setText(“连接成功,请创建游戏或加入游戏”);

}

}

catch(Exception ei)

{

chatpad.chatLineArea.setText(“controlpad.connectButton:无法连接,建议重新启动程序 \n”);

}

}

if(e.getSource()==controlpad.exitGameButton)

{

if(isOnChat)

{

try

{

chatSocket.close();

}

catch(Exception ed)

{

}

}

if(isOnChess || isGameConnected)

{

try

{

chesspad.chessSocket.close();

}

catch(Exception ee)

{

}

}

System.exit(0);

}

if(e.getSource()==controlpad.joinGameButton)

{

String selectedUser=userpad.userList.getSelectedItem();

if(selectedUser==null || selectedUser.startsWith(“[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 “+userpad.userList.getSelectedItem()+” “+chessClientName);

}

}

else

{

isOnChess=true;

isClient=true;

controlpad.creatGameButton.setEnabled(false);

controlpad.joinGameButton.setEnabled(false);

controlpad.cancelGameButton.setEnabled(true);

chesspad.chessthread.sendMessage(“/joingame “+userpad.userList.getSelectedItem()+” “+chessClientName);

}

}

catch(Exception ee)

{

isGameConnected=false;

isOnChess=false;

isClient=false;

controlpad.creatGameButton.setEnabled(true);

controlpad.joinGameButton.setEnabled(true);

controlpad.cancelGameButton.setEnabled(false);

chatpad.chatLineArea.setText(“chesspad.connectServer无法连接 \n”+ee);

}

}

}

if(e.getSource()==controlpad.creatGameButton)

{

try

{

if(!isGameConnected)

{

if(chesspad.connectServer(chesspad.host,chesspad.port))

{

isGameConnected=true;

isOnChess=true;

isServer=true;

controlpad.creatGameButton.setEnabled(false);

controlpad.joinGameButton.setEnabled(false);

controlpad.cancelGameButton.setEnabled(true);

chesspad.chessthread.sendMessage(“/creatgame “+”[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(inputpad.userChoice.getSelectedItem().equals(“所有人”))

{

try

{

out.writeUTF(inputWords.getText());

inputWords.setText(“”);

}

catch(Exception ea)

{

chatpad.chatLineArea.setText(“chessClient:KeyPressed无法连接,建议重新连接 \n”);

userpad.userList.removeAll();

inputpad.userChoice.removeAll();

inputWords.setText(“”);

controlpad.connectButton.setEnabled(true);

}

}

else

{

try

{

out.writeUTF(“/”+inputpad.userChoice.getSelectedItem()+” “+inputWords.getText());

inputWords.setText(“”);

}

catch(Exception ea)

{

chatpad.chatLineArea.setText(“chessClient:KeyPressed无法连接,建议重新连接 \n”);

userpad.userList.removeAll();

inputpad.userChoice.removeAll();

inputWords.setText(“”);

controlpad.connectButton.setEnabled(true);

}

}

}

}

public void keyTyped(KeyEvent e)

{

}

public void keyReleased(KeyEvent e)

{

}

public static void main(String args[])

{

chessClient chessClient=new chessClient();

}

}

/******************************************************************************************

下面是:chessInteface.java

******************************************************************************************/

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

class userPad extends Panel

{

List userList=new List(10);

userPad()

{

setLayout(new BorderLayout());

for(int i=0;i50;i++)

{

userList.add(i+”.”+”没有用户”);

}

add(userList,BorderLayout.CENTER);

}

}

class chatPad extends Panel

{

TextArea chatLineArea=new TextArea(“”,18,30,TextArea.SCROLLBARS_VERTICAL_ONLY);

chatPad()

{

setLayout(new BorderLayout());

add(chatLineArea,BorderLayout.CENTER);

}

}

class controlPad extends Panel

{

Label IPlabel=new Label(“IP”,Label.LEFT);

TextField inputIP=new TextField(“www.easyaq.com”,10);

Button connectButton=new Button(“连接主机”);

Button creatGameButton=new Button(“建立游戏”);

Button joinGameButton=new Button(“加入游戏”);

Button cancelGameButton=new Button(“放弃游戏”);

Button exitGameButton=new Button(“关闭程序”);

controlPad()

{

setLayout(new FlowLayout(FlowLayout.LEFT));

setBackground(Color.pink);

add(IPlabel);

add(inputIP);

add(connectButton);

add(creatGameButton);

add(joinGameButton);

add(cancelGameButton);

add(exitGameButton);

}

}

class inputPad extends Panel

{

TextField inputWords=new TextField(“”,40);

Choice userChoice=new Choice();

inputPad()

{

setLayout(new FlowLayout(FlowLayout.LEFT));

for(int i=0;i50;i++)

{

userChoice.addItem(i+”.”+”没有用户”);

}

userChoice.setSize(60,24);

add(userChoice);

add(inputWords);

}

}

/**********************************************************************************************

下面是:chessPad.java

**********************************************************************************************/

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

import java.util.*;

class chessThread extends Thread

{

chessPad chesspad;

chessThread(chessPad chesspad)

{

this.chesspad=chesspad;

}

public void sendMessage(String sndMessage)

{

try

{

chesspad.outData.writeUTF(sndMessage);

}

catch(Exception ea)

{

System.out.println(“chessThread.sendMessage:”+ea);

}

}

public void acceptMessage(String recMessage)

{

if(recMessage.startsWith(“/chess “))

{

StringTokenizer userToken=new StringTokenizer(recMessage,” “);

String chessToken;

String[] chessOpt={“-1″,”-1″,”0″};

int chessOptNum=0;

while(userToken.hasMoreTokens())

{

chessToken=(String)userToken.nextToken(” “);

if(chessOptNum=1 chessOptNum=3)

{

chessOpt[chessOptNum-1]=chessToken;

}

chessOptNum++;

}

chesspad.netChessPaint(Integer.parseInt(chessOpt[0]),Integer.parseInt(chessOpt[1]),Integer.parseInt(chessOpt[2]));

}

else if(recMessage.startsWith(“/yourname “))

{

chesspad.chessSelfName=recMessage.substring(10);

}

else if(recMessage.equals(“/error”))

{

chesspad.statusText.setText(“错误:没有这个用户,请退出程序,重新加入”);

}

else

{

//System.out.println(recMessage);

}

}

public void run()

{

String message=””;

try

{

while(true)

{

message=chesspad.inData.readUTF();

acceptMessage(message);

}

}

catch(IOException es)

{

}

}

}

class chessPad extends Panel implements MouseListener,ActionListener

{

int chessPoint_x=-1,chessPoint_y=-1,chessColor=1;

int chessBlack_x[]=new int[200];

int chessBlack_y[]=new int[200];

int chessWhite_x[]=new int[200];

int chessWhite_y[]=new int[200];

int chessBlackCount=0,chessWhiteCount=0;

int chessBlackWin=0,chessWhiteWin=0;

boolean isMouseEnabled=false,isWin=false,isInGame=false;

TextField statusText=new TextField(“请先连接服务器”);

Socket chessSocket;

DataInputStream inData;

DataOutputStream outData;

String chessSelfName=null;

String chessPeerName=null;

String host=null;

int port=4331;

chessThread chessthread=new chessThread(this);

chessPad()

{

setSize(440,440);

setLayout(null);

setBackground(Color.pink);

addMouseListener(this);

add(statusText);

statusText.setBounds(40,5,360,24);

statusText.setEditable(false);

}

public boolean connectServer(String ServerIP,int ServerPort) throws Exception

{

try

{

chessSocket=new Socket(ServerIP,ServerPort);

inData=new DataInputStream(chessSocket.getInputStream());

outData=new DataOutputStream(chessSocket.getOutputStream());

chessthread.start();

return true;

}

catch(IOException ex)

{

statusText.setText(“chessPad:connectServer:无法连接 \n”);

}

return false;

}

public void chessVictory(int chessColorWin)

{

this.removeAll();

for(int i=0;i=chessBlackCount;i++)

{

chessBlack_x[i]=0;

chessBlack_y[i]=0;

}

for(int i=0;i=chessWhiteCount;i++)

{

chessWhite_x[i]=0;

chessWhite_y[i]=0;

}

chessBlackCount=0;

chessWhiteCount=0;

add(statusText);

statusText.setBounds(40,5,360,24);

if(chessColorWin==1)

{ chessBlackWin++;

statusText.setText(“黑棋胜,黑:白为”+chessBlackWin+”:”+chessWhiteWin+”,重新开局,等待白棋下子…”);

}

else if(chessColorWin==-1)

{

chessWhiteWin++;

statusText.setText(“白棋胜,黑:白为”+chessBlackWin+”:”+chessWhiteWin+”,重新开局,等待黑棋下子…”);

}

}

public void getLocation(int a,int b,int color)

{

if(color==1)

{

chessBlack_x[chessBlackCount]=a*20;

chessBlack_y[chessBlackCount]=b*20;

chessBlackCount++;

}

else if(color==-1)

{

chessWhite_x[chessWhiteCount]=a*20;

chessWhite_y[chessWhiteCount]=b*20;

chessWhiteCount++;

}

}

public boolean checkWin(int a,int b,int checkColor)

{

int step=1,chessLink=1,chessLinkTest=1,chessCompare=0;

if(checkColor==1)

{

chessLink=1;

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a+step)*20==chessBlack_x[chessCompare]) ((b*20)==chessBlack_y[chessCompare]))

{

chessLink=chessLink+1;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a-step)*20==chessBlack_x[chessCompare]) (b*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

chessLink=1;

chessLinkTest=1;

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if((a*20==chessBlack_x[chessCompare]) ((b+step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if((a*20==chessBlack_x[chessCompare]) ((b-step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

chessLink=1;

chessLinkTest=1;

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a-step)*20==chessBlack_x[chessCompare]) ((b+step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a+step)*20==chessBlack_x[chessCompare]) ((b-step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

chessLink=1;

chessLinkTest=1;

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a+step)*20==chessBlack_x[chessCompare]) ((b+step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

}

if(chessLink==(chessLinkTest+1))

chessLinkTest++;

else

break;

}

for(step=1;step=4;step++)

{

for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)

{

if(((a-step)*20==chessBlack_x[chessCompare]) ((b-step)*20==chessBlack_y[chessCompare]))

{

chessLink++;

if(chessLink==5)

{

return(true);

}

}

跪求JAVA五子棋源代码

很sb的电脑五子棋:

import java.io.*;

import java.util.*;

public class Gobang {

// 定义一个二维数组来充当棋盘

private String[][] board;

// 定义棋盘的大小

private static int BOARD_SIZE = 15;

public void initBoard() {

// 初始化棋盘数组

board = new String[BOARD_SIZE][BOARD_SIZE];

// 把每个元素赋为”╋”,用于在控制台画出棋盘

for (int i = 0; i BOARD_SIZE; i++) {

for (int j = 0; j BOARD_SIZE; j++) {

// windows是一行一行来打印的。坐标值为(行值, 列值)

board[i][j] = “╋”;

}

}

}

// 在控制台输出棋盘的方法

public void printBoard() {

// 打印每个数组元素

for (int i = 0; i BOARD_SIZE; i++) {

for (int j = 0; j BOARD_SIZE; j++) {

// 打印数组元素后不换行

System.out.print(board[i][j]);

}

// 每打印完一行数组元素后输出一个换行符

System.out.print(“\n”);

}

}

// 该方法处理电脑下棋:随机生成2个整数,作为电脑下棋的坐标,赋给board数组。

private void compPlay() {

// 构造一个随机数生成器

Random rnd = new Random();

// Random类的nextInt(int n))方法:随机地生成并返回指定范围中的一个 int 值,

// 即:在此随机数生成器序列中 0(包括)和 n(不包括)之间均匀分布的一个int值。

int compXPos = rnd.nextInt(15);

int compYPos = rnd.nextInt(15);

// 保证电脑下的棋的坐标上不能已经有棋子(通过判断对应数组元素只能是”╋”来确定)

while (board[compXPos][compYPos].equals(“╋”) == false) {

compXPos = rnd.nextInt(15);

compYPos = rnd.nextInt(15);

}

System.out.println(compXPos);

System.out.println(compYPos);

// 把对应的数组元素赋为”○”。

board[compXPos][compYPos] = “○”;

}

// 该方法用于判断胜负:进行四次循环扫描,判断横、竖、左斜、右斜是否有5个棋连在一起

private boolean judgeWin() {

// flag表示是否可以断定赢/输

boolean flag = false;

// joinEle:将每一个横/竖/左斜/右斜行中的元素连接起来得到的一个字符串

String joinEle;

// 进行横行扫描

for (int i = 0; i BOARD_SIZE; i++) {

// 每扫描一行前,将joinEle清空

joinEle = “”;

for (int j = 0; j BOARD_SIZE; j++) {

joinEle += board[i][j];

}

// String类的contains方法:当且仅当该字符串包含指定的字符序列时,返回true。

if (joinEle.contains(“●●●●●”)) {

System.out.println(“您赢啦!”);

flag = true;

// 停止往下继续执行,提前返回flag。

// 如果执行了这个return,就直接返回该方法的调用处;

// 不会再执行后面的任何语句,包括最后那个return语句。

// (而break仅仅是完全跳出这个for循环,还会继续执行下面的for循环。)

return flag;

} else if (joinEle.contains(“○○○○○”)) {

System.out.println(“您输啦!”);

flag = true;

// 提前返回flag

return flag;

}

}

// 进行竖行扫描

for (int i = 0; i BOARD_SIZE; i++) {

joinEle = “”;

for (int j = 0; j BOARD_SIZE; j++) {

// 竖行的元素是它们的列值相同

joinEle += board[j][i];

}

if (joinEle.contains(“●●●●●”)) {

System.out.println(“您赢啦!”);

flag = true;

return flag;

} else if (joinEle.contains(“○○○○○”)) {

System.out.println(“您输啦!”);

flag = true;

return flag;

}

}

// 进行左斜行扫描

for (int i = -(BOARD_SIZE – 2); i BOARD_SIZE – 1; i++) {

joinEle = “”;

for (int j = 0; j BOARD_SIZE; j++) {

int line = i + j;

// 只截取坐标值没有越界的点

if (line = 0 line 15) {

joinEle += board[j][line];

}

}

if (joinEle.contains(“●●●●●”)) {

System.out.println(“您赢啦!”);

flag = true;

return flag;

} else if (joinEle.contains(“○○○○○”)) {

System.out.println(“您输啦!”);

flag = true;

return flag;

}

}

// 进行右斜行扫描

for (int i = 1; i 2 * (BOARD_SIZE – 1); i++) {

joinEle = “”;

for (int j = 0; j BOARD_SIZE; j++) {

int line = i – j;

if (line = 0 line 15) {

joinEle += board[j][line];

}

}

if (joinEle.contains(“●●●●●”)) {

System.out.println(“您赢啦!”);

flag = true;

return flag;

} else if (joinEle.contains(“○○○○○”)) {

System.out.println(“您输啦!”);

flag = true;

// 最后这个return可省略

}

}

// 确保该方法有返回值(如果上面条件都不满足时)

return flag;

}

public static void main(String[] args) throws Exception, IOException {

Gobang gb = new Gobang();

gb.initBoard();

gb.printBoard();

// BufferedReader类:带缓存的读取器————从字符输入流中读取文本,并缓存字符。可用于高效读取字符、数组和行。

// 最好用它来包装所有其 read() 操作可能开销很高的 Reader(如 FileReader 和 InputStreamReader)。

// 下面构造一个读取器对象。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// 定义输入字符串

String inputStr = null;

// br.readLine():每当在键盘上输入一行内容按回车,刚输入的内容将被br(读取器对象)读取到。

// BufferedReader类的readLine方法:读取一个文本行。

// 初始状态由于无任何输入,br.readLine()会抛出异常。因而main方法要捕捉异常。

while ((inputStr = br.readLine()) != null) {

// 将用户输入的字符串以逗号(,)作为分隔符,分隔成2个字符串。

// String类的split方法,将会返回一个拆分后的字符串数组。

String[] posStrArr = inputStr.split(“,”);

// 将2个字符串转换成用户下棋的坐标

int xPos = Integer.parseInt(posStrArr[0]);

int yPos = Integer.parseInt(posStrArr[1]);

// 校验用户下棋坐标的有效性,只能是数字,不能超出棋盘范围

if (xPos 15 || xPos 1 || yPos 15 || yPos 1) {

System.out.println(“您下棋的坐标值应在1到15之间,请重新输入!”);

continue;

}

// 保证用户下的棋的坐标上不能已经有棋子(通过判断对应数组元素只能是”╋”来确定)

// String类的equals方法:比较字符串和指定对象是否相等。结果返回true或false。

if (gb.board[xPos – 1][yPos – 1].equals(“╋”)) {

// 把对应的数组元素赋为”●”。

gb.board[xPos – 1][yPos – 1] = “●”;

} else {

System.out.println(“您下棋的点已有棋子,请重新输入!”);

continue;

}

// 电脑下棋

gb.compPlay();

gb.printBoard();

// 每次下棋后,看是否可以断定赢/输了

if (gb.judgeWin() == false) {

System.out.println(“请输入您下棋的坐标,应以x,y的格式:”);

} else {

// 完全跳出这个while循环,结束下棋

break;

}

}

}

}

本文来自投稿,不代表【】观点,发布者:【

本文地址: ,如若转载,请注明出处!

举报投诉邮箱:253000106@qq.com

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2024年3月28日 12:30:14
下一篇 2024年3月28日 12:38:29

相关推荐

  • 包含linuxiisaccess的词条

    毕业论文:linux系统的web服务器架设 1、我们以RedHat Linux 0系统为例,想要linuxconf在Web浏览器环境工作,必须进行以下设置: * 在gnome-linuxconf对话框中,打开“Config/Networking/Misc/Linuxconf network access”分支,选中“Enable netwoork acces…

    2024年5月23日
    4300
  • 包含黑客技术学习网址的词条

    信息安全技术专业的相关学习网站有哪些? 1、关于学习类的网站有掌门1对多贝、网易云课堂、慕课、传课、CSDN、我要自学网等等。 2、网络安全主要集中在大型城市,如北京上海广州深圳等,那里安全公司特别多,如360,天融信,奇安信等,所以学习网络安全建议选择这些城市。 3、入侵检测系统技术(IDS);加密&VPN技术;产品安全;安全管理。基础课程的主要内…

    2024年5月23日
    5000
  • 包含c语言对txt文件命名的词条

    如何在C语言编程里面修改源文件名字 如果你是在WINDOWS的话,简单了,随便用个编辑器,比如记事本,然后写c源程序,保存到你想要保存的位置。如果你在DOS下,可以用edit,写好以后,按alt键,选择文件菜单,然后保存。 用open打开文件,注意操作模式使用“修改”或者“添加” 用write或者fprintf向文件中写入你的内容。 用close关闭文件。 …

    2024年5月23日
    4800
  • 包含linux启动xinetd的词条

    简述linux进程的启动.终止的方式以及如何查看进程 查看启动的进程:可以使用以面命令来查看:01ps -ef |grep tomcat复制代码tomcat它是一个Java进程,所以查找Java进程也可查找出来。 ps -ef|grep java复制代码可以看到用户和进程编号,可以用kill 进程编号结束进程。 (1)手工启动 用户在输入端发出命令,直接启动…

    2024年5月23日
    4900
  • 包含linux内核二进制在内存分布的词条

    内存管理:一文读懂Linux内存组织结构及页面布局 (1)Linux虚拟内存实现机制 Linux虚拟内存的实现需要六种机制的支持:地址映射机制、内存分配回收机制、缓存和刷新机制、请求页机制、交换机制、内存共享机制。 Linux 内存管理是操作系统内核对物理内存的分配和管理。Linux 内存管理有两个基本任务:一是把可用的内存给程序使用,二是在物理内存不足时,…

    2024年5月23日
    4300
  • 包含Simcityjava的词条

    问一下各种程序的后缀 ,应用程序通常被分为两部分:图形用户接口(GUI)和引擎(Engien)。2,应用程序后缀名:(1)在DOS或Windows系统下其扩展名为*.exe或*.com;(2)在macosx下扩展名一般为*.app。 在windows操作系统下,可执行程序扩展名通常为.exe。全名executablefile,译作可执行文件,可移植可执行(P…

    2024年5月23日
    4600
  • 包含linuxnode后台运行的词条

    怎样使linux后台运行node服务指令 1、nohup node your_app.js & forever可以让我们做得更好,并且可以跨平台的在windows和Linux下都能运行。 2、安装指定版本的node.js(服务器基本软件的安装)你可以到nodejs org官网上面找到相对的tar.gz文件包,下载然后进行源码安装。 3、nodejs一…

    2024年5月23日
    3900
  • 包含hypervlinux集成服务的词条

    如何在Linux发行版中安装并启用Hyper-V集成服务 1、方法/步骤 在网上下载好linux系统的集成服务,并插入hyper-v磁盘中。用root 用户登录linux系统。linux系统自动载入cd rom 中。选择 install.sh,选择运行。运行中,重启电脑。 2、在Hyper-V控制台新建虚机,注意虚机的网卡先选择“旧版网络适配器”,主要是方便…

    2024年5月23日
    3800
  • 团购网站源码java,方维社区团购源码

    请问有java的电商系统的完整源码文档吗(java商城系统源码) 1、Smilehouse Workspace 是一个采用 Java 开发的电子商务应用程序。用来做产品、定案和客户信息管理。 2、现在国内唯一做的正式商业化能用的免费开源电商系统只有ShopsN。注意是纯粹免费,允许商业运营的。至于那种打着免费开源商城的系统,多如牛毛,也就没什么介绍的必要了。…

    2024年5月23日
    3900
  • 包含javajbtok的词条

    java的语法 1、Java的基本语法如下:大小写敏感:Java是大小写敏感的,这就意味着标识符Hello与hello是不同的。类名:对于所有的类来说,类名的首字母应该大写。 2、Java中区分大小写。类和接口名首字母必须大写,采用驼峰命名法,每一个名单词的首字母大写,例如:MyFirstJavaProgram;类名和源文件名必须一致。 3、关键字是电脑语言…

    2024年5月23日
    4000

发表回复

登录后才能评论



关注微信