×

java小游戏源代码大全

求用JAVA编写俄罗斯方块游戏的源代码?java小游戏源代码

admin admin 发表于2022-07-08 21:54:47 浏览123 评论0

抢沙发发表评论

求用JAVA编写俄罗斯方块游戏的源代码


俄罗斯方块——java源代码提供 import java.awt.*; import java.awt.event.*; //俄罗斯方块类 public class ERS_Block extends Frame{ public static boolean isPlay=false; public static int level=1,score=0; public static TextField scoreField,levelField; public static MyTimer timer; GameCanvas gameScr; public static void main(String argus){ ERS_Block ers = new ERS_Block(“俄罗斯方块游戏 V1.0 Author:Vincent“); WindowListener win_listener = new WinListener(); ers.addWindowListener(win_listener); } //俄罗斯方块类的构造方法 ERS_Block(String title){ super(title); setSize(600,480); setLayout(new GridLayout(1,2)); gameScr = new GameCanvas(); gameScr.addKeyListener(gameScr); timer = new MyTimer(gameScr); timer.setDaemon(true); timer.start(); timer.suspend(); add(gameScr); Panel rightScr = new Panel(); rightScr.setLayout(new GridLayout(2,1,0,30)); rightScr.setSize(120,500); add(rightScr); //右边信息窗体的布局 MyPanel infoScr = new MyPanel(); infoScr.setLayout(new GridLayout(4,1,0,5)); infoScr.setSize(120,300); rightScr.add(infoScr); //定义标签和初始值 Label scorep = new Label(“分数:“,Label.LEFT); Label levelp = new Label(“级数:“,Label.LEFT); scoreField = new TextField(8); levelField = new TextField(8); scoreField.setEditable(false); levelField.setEditable(false); infoScr.add(scorep); infoScr.add(scoreField); infoScr.add(levelp); infoScr.add(levelField); scorep.setSize(new Dimension(20,60)); scoreField.setSize(new Dimension(20,60)); levelp.setSize(new Dimension(20,60)); levelField.setSize(new Dimension(20,60)); scoreField.setText(“0“); levelField.setText(“1“); //右边控制按钮窗体的布局 MyPanel controlScr = new MyPanel(); controlScr.setLayout(new GridLayout(5,1,0,5)); rightScr.add(controlScr); //定义按钮play Button play_b = new Button(“开始游戏“); play_b.setSize(new Dimension(50,200)); play_b.addActionListener(new Command(Command.button_play,gameScr)); //定义按钮Level UP Button level_up_b = new Button(“提高级数“); level_up_b.setSize(new Dimension(50,200)); level_up_b.addActionListener(new Command(Command.button_levelup,gameScr)); //定义按钮Level Down Button level_down_b =new Button(“降低级数“); level_down_b.setSize(new Dimension(50,200)); level_down_b.addActionListener(new Command(Command.button_leveldown,gameScr)); //定义按钮Level Pause Button pause_b =new Button(“游戏暂停“); pause_b.setSize(new Dimension(50,200)); pause_b.addActionListener(new Command(Command.button_pause,gameScr)); //定义按钮Quit Button quit_b = new Button(“退出游戏“); quit_b.setSize(new Dimension(50,200)); quit_b.addActionListener(new Command(Command.button_quit,gameScr)); controlScr.add(play_b); controlScr.add(level_up_b); controlScr.add(level_down_b); controlScr.add(pause_b); controlScr.add(quit_b); setVisible(true); gameScr.requestFocus(); } } //重写MyPanel类,使Panel的四周留空间 class MyPanel extends Panel{ public Insets getInsets(){ return new Insets(30,50,30,50); } } //游戏画布类 class GameCanvas extends Canvas implements KeyListener{ final int unitSize = 30; //小方块边长 int rowNum; //正方格的行数 int columnNum; //正方格的列数 int maxAllowRowNum; //允许有多少行未削 int blockInitRow; //新出现块的起始行坐标 int blockInitCol; //新出现块的起始列坐标 int scrArr; //屏幕数组 Block b; //对方快的引用 //画布类的构造方法 GameCanvas(){ rowNum = 15; columnNum = 10; maxAllowRowNum = rowNum - 2; b = new Block(this); blockInitRow = rowNum - 1; blockInitCol = columnNum/2 - 2; scrArr = new int ; } //初始化屏幕,并将屏幕数组清零的方法 void initScr(){ for(int i=0;i《rowNum;i++) for (int j=0; j《columnNum;j++) scrArr[j]=0; b.reset(); repaint(); } //重新刷新画布方法 public void paint(Graphics g){ for(int i = 0; i 《 rowNum; i++) for(int j = 0; j 《 columnNum; j++) drawUnit(i,j,scrArr[j]); } //画方块的方法 public void drawUnit(int row,int col,int type){ scrArr[row][col] = type; Graphics g = getGraphics(); tch(type){ //表示画方快的方法 case 0: g.setColor(Color.black);break; //以背景为颜色画 case 1: g.setColor(Color.blue);break; //画正在下落的方块 case 2: g.setColor(Color.magenta);break; //画已经落下的方法 } g.fill3DRect(col*unitSize,getSize().height-(row+1)*unitSize,unitSize,unitSize,true); g.dispose(); } public Block getBlock(){ return b; //返回block实例的引用 } //返回屏幕数组中(row,col)位置的属性值 public int getScrArrXY(int row,int col){ if (row 《 0 || row 》= rowNum || col 《 0 || col 》= columnNum) return(-1); else return(scrArr[row][col]); } //返回新块的初始行坐标方法 public int getInitRow(){ return(blockInitRow); //返回新块的初始行坐标 } //返回新块的初始列坐标方法 public int getInitCol(){ return(blockInitCol); //返回新块的初始列坐标 } //满行删除方法 void deleteFullLine(){ int full_line_num = 0; int k = 0; for (int i=0;i《rowNum;i++){ boolean isfull = true; L1:for(int j=0;j《columnNum;j++) if(scrArr[j] == 0){ k++; isfull = false; break L1; } if(isfull) full_line_num++; if(k!=0 && k-1!=i && !isfull) for(int j = 0; j 《 columnNum; j++){ if (scrArr[j] == 0) drawUnit(k-1,j,0); else drawUnit(k-1,j,2); scrArr[k-1][j] = scrArr[j]; } } for(int i = k-1 ;i 《 rowNum; i++){ for(int j = 0; j 《 columnNum; j++){ drawUnit(i,j,0); scrArr[j]=0; } } ERS_Block.score += full_line_num; ERS_Block.scoreField.setText(““+ERS_Block.score); } //判断游戏是否结束方法 boolean isGameEnd(){ for (int col = 0 ; col 《columnNum; col ++){ if(scrArr[maxAllowRowNum][col] !=0) return true; } return false; } public void keyTyped(KeyEvent e){ } public void keyReleased(KeyEvent e){ } //处理键盘输入的方法 public void keyPressed(KeyEvent e){ if(!ERS_Block.isPlay) return; tch(e.getKeyCode()){ case KeyEvent.VK_DOWN:b.fallDown();break; case KeyEvent.VK_LEFT:b.leftMove();break; case KeyEvent.VK_RIGHT:b.rightMove();break; case KeyEvent.VK_SPACE:b.leftTurn();break; } } } //处理控制类 class Command implements ActionListener{ static final int button_play = 1; //给按钮分配编号 static final int button_levelup = 2; static final int button_leveldown = 3; static final int button_quit = 4; static final int button_pause = 5; static boolean pause_resume = true; int curButton; //当前按钮 GameCanvas scr; //控制按钮类的构造方法 Command(int button,GameCanvas scr){ curButton = button; this.scr=scr; } //按钮执行方法 public void actionPerformed (ActionEvent e){ tch(curButton){ case button_play:if(!ERS_Block.isPlay){ scr.initScr(); ERS_Block.isPlay = true; ERS_Block.score = 0; ERS_Block.scoreField.setText(“0“); ERS_Block.timer.resume(); } scr.requestFocus(); break; case button_levelup:if(ERS_Block.level 《 10){ ERS_Block.level++; ERS_Block.levelField.setText(““+ERS_Block.level); ERS_Block.score = 0; ERS_Block.scoreField.setText(““+ERS_Block.score); } scr.requestFocus(); break; case button_leveldown:if(ERS_Block.level 》 1){ ERS_Block.level--; ERS_Block.levelField.setText(““+ERS_Block.level); ERS_Block.score = 0; ERS_Block.scoreField.setText(““+ERS_Block.score); } scr.requestFocus(); break; case button_pause:if(pause_resume){ ERS_Block.timer.suspend(); pause_resume = false; }else{ ERS_Block.timer.resume(); pause_resume = true; } scr.requestFocus(); break; case button_quit:System.exit(0); } } } //方块类 class Block { static int pattern = { {0x0f00,0x4444,0x0f00,0x4444},//用十六进至表示,本行表示长条四种状态 {0x04e0,0x0464,0x00e4,0x04c4}, {0x4620,0x6c00,0x4620,0x6c00}, {0x2640,0xc600,0x2640,0xc600}, {0x6220,0x1700,0x2230,0x0740}, {0x6440,0x0e20,0x44c0,0x8e00}, {0x0660,0x0660,0x0660,0x0660} }; int blockType; //块的模式号(0-6) int turnState; //块的翻转状态(0-3) int blockState; //快的下落状态 int row,col; //块在画布上的坐标 GameCanvas scr; //块类的构造方法 Block(GameCanvas scr){ this.scr = scr; blockType = (int)(Math.random() * 1000)%7; turnState = (int)(Math.random() * 1000)%4; blockState = 1; row = scr.getInitRow(); col = scr.getInitCol(); } //重新初始化块,并显示新块 public void reset(){ blockType = (int)(Math.random() * 1000)%7; turnState = (int)(Math.random() * 1000)%4; blockState = 1; row = scr.getInitRow(); col = scr.getInitCol(); dispBlock(1); } //实现“块”翻转的方法 public void leftTurn(){ if(assertValid(blockType,(turnState + 1)%4,row,col)){ dispBlock(0); turnState = (turnState + 1)%4; dispBlock(1); } } //实现“块”的左移的方法 public void leftMove(){ if(assertValid(blockType,turnState,row,col-1)){ dispBlock(0); col--; dispBlock(1); } } //实现块的右移 public void rightMove(){ if(assertValid(blockType,turnState,row,col+1)){ dispBlock(0); col++; dispBlock(1); } } //实现块落下的操作的方法 public boolean fallDown(){ if(blockState == 2) return(false); if(assertValid(blockType,turnState,row-1,col)){ dispBlock(0); row--; dispBlock(1); return(true); }else{ blockState = 2; dispBlock(2); return(false); } } //判断是否正确的方法 boolean assertValid(int t,int s,int row,int col){ int k = 0x8000; for(int i = 0; i 《 4; i++){ for(int j = 0; j 《 4; j++){ if((int)(pattern[t][s]&k) != 0){ int temp = scr.getScrArrXY(row-i,col+j); if (temp《0||temp==2) return false; } k = k 》》 1; } } return true; } //同步显示的方法 public synchronized void dispBlock(int s){ int k = 0x8000; for (int i = 0; i 《 4; i++){ for(int j = 0; j 《 4; j++){ if(((int)pattern[blockType][turnState]&k) != 0){ scr.drawUnit(row-i,col+j,s); } k=k》》1; } } } } //定时线程 class MyTimer extends Thread{ GameCanvas scr; public MyTimer(GameCanvas scr){ this.scr = scr; } public void run(){ while(true){ try{ sleep((10-ERS_Block.level + 1)*100); } catch(InterruptedException e){} if(!scr.getBlock().fallDown()){ scr.deleteFullLine(); if(scr.isGameEnd()){ ERS_Block.isPlay = false; suspend(); }else scr.getBlock().reset(); } } } } class WinListener extends WindowAdapter{ public void windowClosing (WindowEvent l){ System.exit(0); } } 22

java小游戏源代码


介绍这个给你把...我空间还有很多..

http://hi.baidu.com/282919088

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();

JButton jButton2 = new JButton();

JLabel jLabel2 = new JLabel();

int count = 1, rapidity = 80; // count 当前进行的个数, rapidity 游标的位置

int zhengque = 0, cuowu = 0;

int rush = { 10 ,20 ,30 };     //游戏每关的个数 可以自由添加.列 { 10 ,20 ,30 ,40,50}

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’,

    ’Z’, ’1’, ’2’, ’3’, ’4’, ’5’, ’6’, ’7’, ’8’, ’9’ };           //随机出现的数字 可以自由添加

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“)

      .toURL());

    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);

   setSize(new Dimension(588, 530));

   setTitle(“Frame Title“);

   jPanel1.setBorder(BorderFactory.createEtchedBorder());

   jPanel1.setBounds(new Rectangle(4, 4, 573, 419));

   jPanel1.setLayout(null);

   jButton1.setBounds(new Rectangle(277, 442, 89, 31));

   jButton1.setText(“开始“);

   jButton1.addActionListener(new Frame1_jButton1_actionAdapter(this));

   jSlider1.setBounds(new Rectangle(83, 448, 164, 21));

   jSlider1.setMaximum(100);

   jSlider1.setMinimum(1);

   jSlider1.setValue(50);

   jLabel1.setText(“速度“);

   jLabel1.setBounds(new Rectangle(35, 451, 39, 18));

   jButton2.setBounds(new Rectangle(408, 442, 89, 31));

   jButton2.setText(“结束“);

   jButton2.addActionListener(new Frame1_jButton2_actionAdapter(this));

   jLabel2.setText(“第一关:100个“);

   jLabel2.setBounds(new Rectangle(414, 473, 171, 21));

   contentPane.add(jPanel1);

   contentPane.add(jButton2);

   contentPane.add(jButton1);

   contentPane.add(jSlider1);

   contentPane.add(jLabel1);

   contentPane.add(jLabel2);

   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]) { 

    try {

     Thread t = new Thread(new Tthread());

     t.start();

     count += 1;

     Thread.sleep(1000 + (int) (Math.random() * 2000)); // 生产下组停顿时间

     // 最快1快.最慢2秒

    } 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“)) { // 判断是否是自然结束

    if (zhengque / cuowu 》= 2) {

     JOptionPane.showMessageDialog(null, “恭喜你过关了“);

     rush_count += 1; // 自动加1关

     if (rush_count 《 rush.length) {

      if (rapidity 》 10) { // 当速度大于10的时候在-5提加速度.怕速度太快

       rapidity -= 5; // 速度自动减10毫秒

       jSlider1.setValue(rapidity); // 选择位置

      }

      Thread t = new Thread(this);

      t.start();

     } else {

      JOptionPane.showMessageDialog(null, “牛B...你通关了..“);

      rush_count = 0;

      count = 0;

     }

    } else {

     JOptionPane.showMessageDialog(null, “请再接再励“);

     rush_count = 0;

     count = 0;

    }

   } else {

    rush_count = 0;

    count = 0;

   }

}

public void jButton1_actionPerformed(ActionEvent e) {

   Thread t = new Thread(this);

   t.start();

}

public void jButton2_actionPerformed(ActionEvent e) {

   count = rush[rush_count] + 1;

   paiduan = “flase“;

}

class Tthread implements Runnable {

   public void run() {

    boolean fo = true;

    int Y = 0, X = 0;

    JLabel show = new JLabel();

    show.setFont(new java.awt.Font(“宋体“, Font.PLAIN, 33));

    jPanel1.add(show);

    X = 10 + (int) (Math.random() * 400);

    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) {

     // ---------------------数字下移--------------------

     show.setBounds(new Rectangle(X, Y += 2, 33, 33));

     try {

      Thread.sleep(rapidity);

     } catch (InterruptedException e) {

      e.printStackTrace();

     }

     if (Y 》= 419) {

      fo = false;

      for (int i = number.size() - 1; i 》= 0; i--) {

       Bean bn = ((Bean) number.get(i));

       if (parameter.equalsIgnoreCase(bn.getParameter())) {

        cuowu += 1;

        jLabel2.setText(“正确:“ + zhengque + “个,错误:“ + cuowu

          + “个“);

        number.removeElementAt(i);

        Music_shibai.play();

        break;

       }

      }

     }

    }

   }

}

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;

      number.removeElementAt(i);

      bean.getShow().setVisible(false);

      jLabel2.setText(“正确:“ + zhengque + “个,错误:“ + cuowu + “个“);

      Music_chenggong.play();

      break;

     }

    }

    Musci_anjian.play();

   }

}

public static void main(String args) {

   try {

    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

   } catch (Exception exception) {

    exception.printStackTrace();

   }

   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.setLocation((screenSize.width - frameSize.width) / 2,

     (screenSize.height - frameSize.height) / 2);

   frame.setVisible(true);

}

}

class Frame1_jButton2_actionAdapter implements ActionListener {

private Frame adaptee;

Frame1_jButton2_actionAdapter(Frame adaptee) {

   this.adaptee = adaptee;

}

public void actionPerformed(ActionEvent e) {

   adaptee.jButton2_actionPerformed(e);

}

}

class Frame1_jButton1_actionAdapter implements ActionListener {

private Frame adaptee;

Frame1_jButton1_actionAdapter(Frame adaptee) {

   this.adaptee = adaptee;

}

public void actionPerformed(ActionEvent e) {

   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;

}

}


求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小游戏源代码大全