表1. CheckerDrag.java
介绍这个给你把...我空间还有很多..
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Vector;
public class Frame extends JFrame implements Runnable {
JPanel contentPane;
JPanel jPanel1 = new JPanel();
JButton jButton1 = new JButton();
JSlider jSlider1 = new JSlider();
JLabel jLabel1 = new JLabel();
int zhengque = 0, cuowu = 0;
int rush[] = ; //游戏每关的个数 可以自由添加.列
int rush_count = 0; //记录关数
char list[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
Vector number = new Vector();
String paiduan = "true";
AudioClip Musci_anjian, Music_shibai, Music_chenggong;
public Frame() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
//-----------------声音文件---------------------
Musci_anjian = Applet.newAudioClip(new File("sounds//anjian.wav")
.toURL());
Music_shibai = Applet.newAudioClip(new File("sounds//shibai.wav")
Music_chenggong = Applet.newAudioClip(new File(
"sounds//chenggong.wav").toURL());
//---------------------------------------
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
/**
* Component initialization.
*
* @throws java.lang.Exception
*/
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(null);
setTitle("Frame Title");
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setLayout(null);
jButton1.setText("开始");
jButton1.addActionListener(new Frame1_jButton1_actionAdapter(this));
jSlider1.setMaximum(100);
jSlider1.setMinimum(1);
jLabel1.setText("速度");
contentPane.add(jPanel1);
contentPane.add(jButton1);
contentPane.add(jSlider1);
contentPane.add(jLabel1);
this.addKeyListener(new MyListener());
jButton1.addKeyListener(new MyListener());
jSlider1.addKeyListener(new MyListener());
jSlider1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
rapidity = jSlider1.getValue();
});
public void run() {
number.clear();
zhengque = 0;
cuowu = 0;
paiduan = "true";
while (count = rush[rush_count]) {
Thread t = new Thread(new Tthread());
t.start();
count += 1;
} catch (InterruptedException e) {
e.printStackTrace();
while (true) { // 等待最后一个字符消失
if (number.size() == 0) {
break;
if (zhengque == 0) { // 为了以后相除..如果全部正确或者错误就会出现错误. 所以..
zhengque = 1;
if (cuowu == 0) {
cuowu = 1;
if (paiduan.equals("true")) { // 判断是否是自然结束
JOptionPane.showMessageDialog(null, "恭喜你过关了");
rush_count += 1; // 自动加1关
if (rush_count rush.length) {
jSlider1.setValue(rapidity); // 选择位置
Thread t = new Thread(this);
} else {
JOptionPane.showMessageDialog(null, "牛B...你通关了..");
rush_count = 0;
count = 0;
JOptionPane.showMessageDialog(null, "请再接再励");
public void jButton1_actionPerformed(ActionEvent e) {
count = rush[rush_count] + 1;
paiduan = "flase";
class Tthread implements Runnable {
boolean fo = true;
int Y = 0, X = 0;
JLabel show = new JLabel();
jPanel1.add(show);
String parameter = list[(int) (Math.random() * list.length)] + "";
Bean bean = new Bean();
bean.setParameter(parameter);
bean.setShow(show);
number.add(bean);
show.setText(parameter);
while (fo) {
// ---------------------数字下移--------------------
Thread.sleep(rapidity);
fo = false;
for (int i = number.size() - 1; i = 0; i--) {
Bean bn = ((Bean) number.get(i));
if (parameter.equalsIgnoreCase(bn.getParameter())) {
cuowu += 1;
+ "个");
number.removeElementAt(i);
Music_shibai.play();
class MyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
String uu = e.getKeyChar() + "";
for (int i = 0; i number.size(); i++) {
Bean bean = ((Bean) number.get(i));
if (uu.equalsIgnoreCase(bean.getParameter())) {
zhengque += 1;
bean.getShow().setVisible(false);
Music_chenggong.play();
Musci_anjian.play();
public static void main(String[] args) {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Frame frame = new Frame();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height screenSize.height) {
frameSize.height = screenSize.height;
if (frameSize.width screenSize.width) {
frameSize.width = screenSize.width;
frame.setVisible(true);
private Frame adaptee;
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e) {
class Frame1_jButton1_actionAdapter implements ActionListener {
Frame1_jButton1_actionAdapter(Frame adaptee) {
adaptee.jButton1_actionPerformed(e);
class Bean {
String parameter = null;
JLabel show = null;
public JLabel getShow() {
return show;
public void setShow(JLabel show) {
this.show = show;
public String getParameter() {
return parameter;
public void setParameter(String parameter) {
this.parameter = parameter;
分情况看:
(1)如果你没用非官方集成的开发环境的话,首先在你电脑上装个JDK,然后设置下电脑环境变量,里面有PATH和CLASSPATH这两个参数,具体怎么设置呢?就是把安装目录的地址拷贝到里面就好了,略有不同这两个参数的设置.安装完成后,把源代码文件的目录记下,源代码拷贝到记事本上,把后缀名改成".java";打开CMD窗口,先执行"javac 文件名.java"命令,在目录下会生成一个".class"的文件,那是编译生成的文件,如果顺利通过编译,说明源代码没错误,OK,你再执行"java 文件名.class"就执行程序了.
都说到这里了大家应该明白,你只要把JDK装上,调试成功了,剩余的就小意思,如果实在搞不定,把你代码发过来,我给你生成".jar"文件好了,就像".exe"的可执行文件.呵呵,说了这么多,自己要多摸索下啊,我是学java的,欢迎交流,希望你能顺利解决,编程要自己多摸索
java网络五子棋
chessPad.java:棋盘的绘制.
chessServer.java:服务器端.
/*********************************************************************************************
①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);
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无法关闭");
else if(recMessage.startsWith("/peer "))
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="";
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;
boolean isOnChat=false; //在聊天?
boolean isOnChess=false; //在下棋?
boolean isServer=false; //如果是下棋的主机
Panel southPanel=new Panel();
Panel northPanel=new Panel();
Panel centerPanel=new Panel();
Panel westPanel=new Panel();
Panel eastPanel=new Panel();
chessClient()
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)
chatSocket.close();
catch(Exception ed)
if(isOnChess || isGameConnected)
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();
setVisible(true);
setResizable(false);
validate();
public boolean connectServer(String serverIP,int serverPort) throws Exception
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();
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(e.getSource()==controlpad.joinGameButton)
String selectedUser=userpad.userList.getSelectedItem();
if(selectedUser==null || selectedUser.startsWith("[inchess]") ||
selectedUser.equals(chessClientName))
chesspad.statusText.setText("必须先选定一个有效用户");
if(!isGameConnected)
if(chesspad.connectServer(chesspad.host,chesspad.port))
isGameConnected=true;
isOnChess=true;
isClient=true;
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);
isGameConnected=false;
isOnChess=false;
isClient=false;
chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ee);
if(e.getSource()==controlpad.creatGameButton)
isServer=true;
chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);
catch(Exception ec)
isServer=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);
chesspad.statusText.setText("请建立游戏或者加入游戏");
if(!isOnChess)
isClient=isServer=false;
public void keyPressed(KeyEvent e)
TextField inputWords=(TextField)e.getSource();
if(e.getKeyCode()==KeyEvent.VK_ENTER)
if(inputpad.userChoice.getSelectedItem().equals("所有人"))
out.writeUTF(inputWords.getText());
inputWords.setText("");
catch(Exception ea)
chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
controlpad.connectButton.setEnabled(true);
out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText());
public void keyTyped(KeyEvent e)
public void keyReleased(KeyEvent e)
public static void main(String args[])
chessClient chessClient=new chessClient();
/******************************************************************************************
下面是:chessInteface.java
******************************************************************************************/
class userPad extends Panel
List userList=new List(10);
userPad()
userList.add(i+"."+"没有用户");
add(userList,BorderLayout.CENTER);
class chatPad extends Panel
chatPad()
add(chatLineArea,BorderLayout.CENTER);
class controlPad extends Panel
Label IPlabel=new Label("IP",Label.LEFT);
TextField inputIP=new TextField("localhost",10);
Button connectButton=new Button("连接主机");
Button creatGameButton=new Button("建立游戏");
Button joinGameButton=new Button("加入游戏");
Button cancelGameButton=new Button("放弃游戏");
Button exitGameButton=new Button("关闭程序");
controlPad()
setLayout(new FlowLayout(FlowLayout.LEFT));
setBackground(Color.pink);
add(IPlabel);
add(inputIP);
add(connectButton);
add(creatGameButton);
add(joinGameButton);
add(cancelGameButton);
add(exitGameButton);
class inputPad extends Panel
Choice userChoice=new Choice();
inputPad()
userChoice.addItem(i+"."+"没有用户");
add(userChoice);
add(inputWords);
/**********************************************************************************************
下面是:chessPad.java
class chessThread extends Thread
chessPad chesspad;
chessThread(chessPad chesspad)
this.chesspad=chesspad;
public void sendMessage(String sndMessage)
chesspad.outData.writeUTF(sndMessage);
System.out.println("chessThread.sendMessage:"+ea);
if(recMessage.startsWith("/chess "))
String chessToken;
String[] chessOpt={"-1","-1","0"};
int chessOptNum=0;
chessToken=(String)userToken.nextToken(" ");
chessOpt[chessOptNum-1]=chessToken;
chessOptNum++;
chesspad.chessSelfName=recMessage.substring(10);
chesspad.statusText.setText("错误:没有这个用户,请退出程序,重新加入");
//System.out.println(recMessage);
message=chesspad.inData.readUTF();
class chessPad extends Panel implements MouseListener,ActionListener
int chessPoint_x=-1,chessPoint_y=-1,chessColor=1;
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;
chessThread chessthread=new chessThread(this);
chessPad()
setLayout(null);
addMouseListener(this);
add(statusText);
statusText.setEditable(false);
public boolean connectServer(String ServerIP,int ServerPort) throws Exception
chessSocket=new Socket(ServerIP,ServerPort);
inData=new DataInputStream(chessSocket.getInputStream());
outData=new DataOutputStream(chessSocket.getOutputStream());
chessthread.start();
statusText.setText("chessPad:connectServer:无法连接 \n");
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;
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)
chessBlackCount++;
else if(color==-1)
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(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)
chessLink=chessLink+1;
return(true);
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
chessLink++;
chessLinkTest=1;
import java.applet.*;
import java.awt.image.*;
import java.awt.geom.*;
class Car{
Image img;
int x, y;
Dimension dim;
Car(Image img){
this.img=img;
Car(Image img, int x, int y){
this.img=img; this.x=x; this.y=y;
Car(Image img, int x, int y, Dimension dim){
this(img, x, y);
this.dim=dim;
void draw(Graphics g, ImageObserver observer){
g.drawImage(img, x, y, observer);
int getX(){ return x;}
int getY(){ return y;}
void setX(int x){this.x=x;}
void setY(int y){this.y=y;}
void setLocation(int x, int y){
this.x=x; this.y=y;
int getWidth(){ return img.getWidth(null);}
int getHeight(){ return img.getHeight(null);}
void move(int dx, int dy){
x+=dx;
y+=dy;
if(dim!=null){
if(x0)x=0;
if(x+getWidth()dim.getWidth())
x=(int)dim.getWidth()-getWidth();
boolean intersects(Car car){
return getRectangle().intersects(car.getRectangle());
boolean intersects(int x, int y){
return getRectangle().intersects(x, y, getWidth(), getHeight());
public class CarRace extends Applet implements KeyListener, Runnable{
Image buff;
Canvas screen;
Car redCar;
Button bStart;
Thread game;
boolean loop=true;
int road;
Random rnd=new Random();
public void init(){
prepareResource();
setBackground(Color.blue);
initScreen();
add(screen);
bStart=new Button("霸烙 矫累");
add(bStart);
bStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
screen.requestFocus();
if(!game.isAlive())
game.start();
void prepareResource(){
Image imgRed=getImage(getCodeBase(),"images/red_car.gif");
Image imgBlue=getImage(getCodeBase(),"images/blue_car.gif");
Image imgGreen=getImage(getCodeBase(),"images/green_car.gif");
MediaTracker mt=new MediaTracker(this);
try{
mt.addImage(imgRed, 0);
mt.addImage(imgBlue, 1);
mt.waitForAll();
}catch(Exception e){}
buff=createImage((int)dim.getWidth(), (int)dim.getHeight());
for(int i=0;i10;i++){
enemy[i]=new Car(imgBlue, 0, 0);
for(int i=10;ienemy.length;i++){
enemy[i]=new Car(imgGreen, 0, 0);
for(int i=0;ienemy.length;i++){
setEnemy(i);
game=new Thread(this);
public void stop(){
loop=false;
public void run(){
while(loop){
drawScreen();
void initScreen(){
screen=new Canvas(){
public void paint(Graphics g){
if(gs==null){
};
screen.setSize(dim);
screen.addKeyListener(this);
void setEnemy(int en){
next:while(true){
x=rnd.nextInt((int)dim.getWidth()-enemy[en].getWidth());
for(int j=0;jenemy.length;j++){
if(j!=en enemy[j].intersects(x, y))continue next;
enemy[en].setLocation(x, y);
void check(Car en){
if(redCar.intersects(en)){
if(redCar.getX()en.getX()){
else{
synchronized void drawScreen(){
gb.clearRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight());
gb.setPaint(new Color(100, 100, 100));
gb.fillRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight());
drawRoad();
enemy[i].draw(gb, screen);
if(enemy[i].getY()dim.getHeight())
check(enemy[i]);
redCar.draw(gb, screen);
gs.drawImage(buff, 0,0, screen);
void drawRoad(){
gb.setPaint(Color.yellow);
public void keyPressed(KeyEvent ke){
if(ke.getKeyCode()==KeyEvent.VK_LEFT){
redCar.move(-10,0);
else if(ke.getKeyCode()==KeyEvent.VK_RIGHT){
redCar.move(10,0);
public void keyReleased(KeyEvent ke){}
public void keyTyped(KeyEvent ke){}
这个是一个典型的Applet,文件名应该是CarRace.java,需要图片作为车子等等,本人也是别人给的,但是还要个.html文件来运行它,代码为:
/Applet
请楼主采纳
以上就是土嘎嘎小编为大家整理的java游戏编程源代码相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!