java动作游戏代码 java 游戏 代码

java 小游戏import java.util.Random;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.*;
public class SmallGame extends JFrame {
private Random r;
private String[] box = { "剪刀", "石头", "布" };
private JComboBox choice;
private JTextArea ta;
private JLabel lb;
private int win = 0;
private int loss = 0;
private int equal = 0;
public SmallGame() {
initial();//调用initial方法,就是下面定义的那个.该方法主要是初始界面.
pack();
setTitle("游戏主界面");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(400, 300);
setVisible(true);
}
public static void main(String[] args) {
new SmallGame();
}
public void initial() {
r = new Random(); // 生成随机数
choice = new JComboBox();//初始化choice这个下拉框.也就是你选择出剪子还是石头什么的那个下拉框..
for (int i = 0; ibox.length; i) {//为那个下拉框赋值.用前面定义的private String[] box = { "剪刀", "石头", "布" };附值.这样下拉框就有三个选项了..
choice.addItem(box[i]);
}
ta = new JTextArea(3, 15);//初始化那个文本域3行15列
ta.setEditable(false);//让用户不能编辑那个文本域即不能在里面写东西
JButton okBut = new JButton("出招");//新建一个出招的按钮
okBut.addActionListener(new ActionListener() {//给出招按钮加个监听.意思就是监听着这个按钮看用户有没有点击它..如果点击就执行下面这个方法
public void actionPerformed(ActionEvent e) {//就是这个方法
ta.setText(getResult());//给那个文本域赋值..就是显示结果赋值的是通过getResult()这个方法得到的返回值 getResult()这个方法下面会讲
lb.setText(getTotal());//给分数那个LABEL赋值..就是显示分数..赋值的是通过getTotal()这个方法得到的返回值
}
});
JButton clearBut = new JButton("清除分数");//新建一个清楚分数的按钮
clearBut.addActionListener(new ActionListener() {//同上给他加个监听
public void actionPerformed(ActionEvent e) {//如果用户点击了就执行这个方法
ta.setText("");//给文本域赋值为""..其实就是清楚他的内容
win = 0;//win赋值为0
loss = 0;//同上
equal = 0;//同上
lb.setText(getTotal());//给显示分数那个赋值..因为前面已经都赋值为0了..所以这句就是让显示分数那都为0
}
});
lb = new JLabel(getTotal());//初始化那个显示分数的东西
JPanel choicePanel = new JPanel();//定义一个面板..面板就相当于一个画图用的东西..可以在上面加按钮啊文本域什么的..
choicePanel.add(choice);//把下拉框加到面板里
choicePanel.add(okBut);//把出招按钮加到面板里
choicePanel.add(clearBut);//把清楚分数按钮加到面板里
JScrollPane resultPanel = new JScrollPane(ta);//把文本域加到一个可滚动的面板里面..JScrollPane就是可滚动的面板..这样如果那个文本域内容太多就会出现滚动条..而不是变大
JPanel totalPanel = new JPanel();//再定义个面板..用来显示分数的..
totalPanel.add(lb);//把那个显示分数的label加到里面去
Container contentPane = getContentPane();//下面就是布局了..
contentPane.setLayout(new BorderLayout());
contentPane.add(choicePanel, BorderLayout.NORTH);
contentPane.add(resultPanel, BorderLayout.CENTER);
contentPane.add(totalPanel, BorderLayout.SOUTH);
}
public String getResult() {//获得结果的方法 返回值是一个String..这个返回值会用来显示在文本域里面
String tmp = "";
int boxPeop = choice.getSelectedIndex();//获得你选择的那个的索引..从0开始的..
int boxComp = getBoxComp();//获得电脑出的索引..就是随机的0-2的数
tmp= "你出:\t"box[boxPeop];//下面你应该明白了..
tmp= "\n电脑出:\t"box[boxComp];
tmp= "\n结果:\t"check(boxPeop, boxComp);
return tmp;
}
public int getBoxComp() {//就是产生一个0-2的随机数..
return r.nextInt(3);//Random的nextInt(int i)方法就是产生一个[0-i)的随机整数 所以nextInt(3)就是[0-2]的随机数
}
public String check(int boxPeop, int boxComp) {//这个就是判断你选择的和电脑选择的比较结果..是输是赢还是平..boxPeop就是你选择的..boxComp就是电脑选择的..
String result = "";
if (boxPeop == (boxComp1) % 3) {//(boxComp1) % 3电脑选择的加上1加除以3取余..也就是如果电脑选0这个就为1..这个判断的意思就是如果电脑选0并且你选1..那么就是电脑选了
//private String[] box = { "剪刀", "石头", "布" };这里面下标为0的..你选了下标为1的..就是电脑选剪刀你选石头..所以你赢了..如果电脑选1..(boxComp1) % 3就为2..意思就是
//电脑选了石头你选了布..所以你赢了..另外一种情况你明白了撒..只有三种情况你赢..所以这里都包含了..也只包含了那三种..
result = "你赢了!";
win;//赢了就让记你赢的次数的那个变量加1
} else if (boxPeop == boxComp) {//相等当然平手了
result = "平";
equal;//同上了
} else {//除了赢和平当然就是输了..
result = "你输了!";
loss;//同上
}
return result;
}
public int getPoint() {
return (win - loss) * 10;
}
public String getTotal() {
return "赢:"win"平:"equal"输:"loss"得分:"
getPoint();
}
}
希望你能明白哈 。。
求一个简单又有趣的JAVA小游戏代码具体如下:
连连看的小源码
package Lianliankan;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class lianliankan implements ActionListener
{
JFrame mainFrame; //主面板
Container thisContainer;
JPanel centerPanel,southPanel,northPanel; //子面板
JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组
JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮
JLabel fractionLable=new JLabel("0"); //分数标签
JButton firstButton,secondButton; //
分别记录两次62616964757a686964616fe59b9ee7ad9431333335326239被选中的按钮
int grid[][] = new int[8][7];//储存游戏按钮位置
static boolean pressInformation=false; //判断是否有按钮被选中
int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戏按钮的位置坐标
int i,j,k,n;//消除方法控制
代码(code)是程序员用开发工具所支持的语言写出来的源文件,是一组由字符、符号或信号码元以离散形式表示信息的明确的规则体系 。
对于字符和Unicode数据的位模式的定义,此模式代表特定字母、数字或符号(例如 0x20 代表一个空格 , 而 0x74 代表字符“t”) 。一些数据类型每个字符使用一个字节;每个字节可以具有 256 个不同的位模式中的一个模式 。
在计算机中 , 字符由不同的位模式(ON 或 OFF)表示 。每个字节有 8 位,这 8 位可以有 256 种不同的 ON 和 OFF 组合模式 。对于使用 1 个字节存储每个字符的程序,通过给每个位模式指派字符可表示最多 256 个不同的字符 。2 个字节有 16 位,这 16 位可以有 65,536 种唯一的 ON 和 OFF 组合模式 。使用 2 个字节表示每个字符的程序可表示最多 65,536 个字符 。
单字节代码页是字符定义,这些字符映射到每个字节可能有的 256 种位模式中的每一种 。代码页定义大小写字符、数字、符号以及 !、@、#、% 等特殊字符的位模式 。每种欧洲语言(如德语和西班牙语)都有各自的单字节代码页 。
虽然用于表示 A 到 Z 拉丁字母表字符的位模式在所有的代码页中都相同 , 但用于表示重音字符(如"é"和"á")的位模式在不同的代码页中却不同 。如果在运行不同代码页的计算机间交换数据,必须将所有字符数据由发送计算机的代码页转换为接收计算机的代码页 。如果源数据中的扩展字符在接收计算机的代码页中未定义,那么数据将丢失 。
如果某个数据库为来自许多不同国家的客户端提供服务 , 则很难为该数据库选择这样一种代码页,使其包括所有客户端计算机所需的全部扩展字符 。而且,在代码页间不停地转换需要花费大量的处理时间 。
求一个简单的JAVA游戏代码,100行左右,谢谢!import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Painter extends JFrame{
/**
*
*/
private static final long serialVersionUID = 8160427604782702376L;
CanvasPanel canvas = new CanvasPanel();;
public Painter() {
super("Star");
this.add(canvas);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new Painter();
}
}
class CanvasPanel extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -4642528854538741028L;
private JButton[] btn = new JButton[4];
private String[] btn_name = {" ", "-", "R", "L"};
private int center_x = 200, center_y = 200, radius = 100, degree = 0;
public CanvasPanel() {
this.setPreferredSize(new Dimension(400, 500));
this.setLayout(null);
for(int i = 0; i4; i) {
btn[i] = new JButton(btn_name[i]);
btn[i].setBounds(160i * 60, 425, 50, 50);
btn[i].addActionListener(this);
this.add(btn[i]);
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i = 0; i5; i) {
g.drawLine( (int) (center_xradius * Math.sin(Math.toRadians(degree72 * i))),
(int) (center_y - radius * Math.cos(Math.toRadians(degree72 * i))),
(int) (center_xradius * Math.sin(Math.toRadians(degree72 * i144))),
(int) (center_y - radius * Math.cos(Math.toRadians(degree72 * i144))));
}
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand() == " ") {
if(radius200)
radius= 2;
repaint();
} else if(e.getActionCommand() == "-") {
if(radius0)
radius -= 2;
repaint();
} else if(e.getActionCommand() == "R") {
degree = (degree2) % 360;
repaint();
} else if(e.getActionCommand() == "L") {
degree = (degree - 2) % 360;
repaint();
}
}
}
几个Java小游戏代码package reduce;
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 当前进行java动作游戏代码的个数, 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, "恭喜java动作游戏代码你过关了");
rush_count= 1; // 自动加1关
if (rush_countrush.length) {
if (rapidity10) { // 当速度大于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; inumber.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.heightscreenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.widthscreenSize.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动作游戏代码 java 游戏 代码】}
}
java动作游戏代码我只有一个打字母小游戏
求java小游戏源代码表1. CheckerDrag.java
// CheckerDrag.javaimport java.awt.*;import java.awt.event.*;public class CheckerDrag extends java.applet.Applet{// Dimension of checkerboard square.// 棋盘上每个小方格java动作游戏代码的尺寸final static int SQUAREDIM = 40;// Dimension of checkerboard -- includes black outline.// 棋盘的尺寸 – 包括黑色的轮廓线final static int BOARDDIM = 8 * SQUAREDIM2;// Dimension of checker -- 3/4 the dimension of a square.// 棋子的尺寸 – 方格尺寸的3/4final 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.// 拖动标记 --当用户在棋子上按下鼠标按键时设为truejava动作游戏代码,// 释放鼠标按键时设为falseboolean 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.// 初始化棋盘的原点java动作游戏代码,使棋盘在屏幕上居中boardx = (width - BOARDDIM) / 21;boardy = (height - BOARDDIM) / 21;// 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.// 初始化棋子矩形的起始原点java动作游戏代码,使得棋子在第一行左数第二列的方格里居中ox = boardxSQUAREDIM(SQUAREDIM - CHECKERDIM) / 21;oy = boardy(SQUAREDIM - CHECKERDIM) / 21;// 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 = oxCHECKERDIM / 2;int coy = oyCHECKERDIM / 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 (tmpoxboardxtmpoyboardytmpoxCHECKERDIMboardxBOARDDIMtmpoyCHECKERDIMboardyBOARDDIM){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 * SQUAREDIM1, 8 * SQUAREDIM1);// Paint checkerboard.// 绘制棋盘for (int row = 0; row8; row){g.setColor (((row1) != 0) ? darkGreen : Color.white);for (int col = 0; col8; col){g.fillRect (x1col * SQUAREDIM, y1row * 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游戏中让一个人物走动的代码是什么?代码主要为以下:
package com.lovo.game.frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import javax.swing.JFrame;
import com.lovo.game.role.Fire;
import com.lovo.game.role.GameMap;
import com.lovo.game.role.ZhaoYun;
import com.lovo.game.util.TrackerInit;
public class GameStartFrame extends JFrame implements Runnable{
private Image memoryImage;
private Graphics memoryGraphics;
public static boolean isRun = true;
private static GameMap gameMap = new GameMap();
private ZhaoYun zy = new ZhaoYun();
private Fire fire = new Fire();
public GameStartFrame(){
this.setSize(900,700);
this.setVisible(true);
this.setDefaultCloseOperation(3);
//设置居中
this.setLocationRelativeTo(null);
//初始化双缓冲画布、画笔
this.memoryImage = this.createImage(900,700);
this.memoryGraphics = this.memoryImage.getGraphics();
//媒体追踪器
MediaTracker tracker = new MediaTracker(this);
TrackerInit.initImage(tracker);
//启动线程
Thread th = new Thread(this);
th.start();
}
public static void main(String[] args) {
GameStartFrame game = new GameStartFrame();
}
public void run() {
while(isRun){
this.flushFrame();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void flushFrame(){
gameMap.drawMap(memoryGraphics);
zy.drawImage(memoryGraphics);
fire.drawImage(memoryGraphics);
//将双缓冲画布中的图片显示在窗体
this.getGraphics().drawImage(this.memoryImage,0,0,this);
}
}
package com.lovo.game.role;
import java.awt.Graphics;
import java.awt.Image;
public class GameMap {
public static Image mapImg;
public static int mapx;
public void drawMap(Graphics memoryGraphics){
mapx -=5;
if(mapx =-17100){
mapx = -17100;
}
memoryGraphics.drawImage(mapImg,mapx,0,null);
}
}
package com.lovo.game.role;
import java.awt.Graphics;
import java.awt.Image;
import com.lovo.game.util.MoveImageChange;
public class Fire {
public static Image[]fireImage;
private int x =100;
private int y =300;
private int width = 200;
private int height = 130;
private MoveImageChange moveChange = new MoveImageChange(3);
public void drawImage(Graphics memoryGraphics){
Image img = moveChange.imageChange(fireImage);
memoryGraphics.drawImage(img,this.x,this.y,this.width,this.height,null);
}
}
package com.lovo.game.util;
import java.awt.MediaTracker;
import com.lovo.game.role.Fire;
import com.lovo.game.role.GameMap;
import com.lovo.game.role.ZhaoYun;
public class TrackerInit {
public static void initImage(MediaTracker tracker){
//初始化地图图片
GameMap.mapImg = CutImage.getSingleImage("image/map.jpg", tracker);
//赵云
ZhaoYun.zyImage = CutImage.cutOneImage("image/boss/playSpear.png",18, 236, 134,tracker);
//火
Fire.fireImage = CutImage.cutOneImage("image/fireImg.png", 6, 283, 161,tracker);
try {
//0组的图片全部等待加载完毕后,在显示
tracker.waitForID(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.lovo.game.util;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageProducer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class CutImage {
public staticImage[][] cutManyImage(String filePath, int row, int col,
int imageWidth, int imageHight,MediaTracker tracker) {
Image[][] img = new Image[row][col];
ImageIcon imIcon = new ImageIcon(filePath);// 创建图像数组对象
Image imgTemp = imIcon.getImage();// 创建源图像
// 为源 图象获取ImageProducer源
ImageProducer sourceProducer = imgTemp.getSource();
for (int i = 0; irow; i) {
for (int j = 0; jcol; j) {
// 创建图片分割图像对象,第一、二个参数为分割图像起始坐标 。后两个参数为图像大小
CropImageFilter cropImg = new CropImageFilter(j * imageWidth, i * imageHight,imageWidth, imageHight);
ImageProducer imgProducer = new FilteredImageSource(sourceProducer, cropImg);
img[i][j] = new JFrame().createImage(imgProducer);
tracker.addImage(img[i][j], 0);
}
}
return img;
}
public staticImage[] cutOneImage(String filePath,int col,
int imageWidth, int imageHight,MediaTracker tracker) {
Image[] img = new Image[col];
ImageIcon imIcon = new ImageIcon(filePath);// 创建图像数组对象
Image imgTemp = imIcon.getImage();// 创建源图像
// 为源 图象获取ImageProducer源
ImageProducer sourceProducer = imgTemp.getSource();
for (int j = 0; jcol; j) {
// 创建图片分割图像对象,第一、二个参数为分割图像起始坐标 。后两个参数为图像大小
CropImageFilter cropImg = new CropImageFilter(j * imageWidth, 0,imageWidth, imageHight);
ImageProducer imgProducer = new FilteredImageSource(sourceProducer, cropImg);
img[j] = new JFrame().createImage(imgProducer);
tracker.addImage(img[j], 0);
}
return img;
}
public static Image getSingleImage(String imgPath,MediaTracker tracker){
Image img = new ImageIcon(imgPath).getImage();
tracker.addImage(img, 0);
return img;
}
}
package com.lovo.game.util;
import java.awt.Image;
public class MoveImageChange {
private int count;
private Image img;
private int frequency;
private int loopCount;
public MoveImageChange(int frequency){
this.frequency=frequency;
}
public MoveImageChange(int frequency,int count){
this.frequency=frequency;
this.count = count;
}
publicImage imageChange(Image[] images){
if(img==null){//初始图片为第一张图片
img=images[0];
}
count;
if(countfrequency){//当记数器大于频率时
count=0;
loopCount;
if(loopCount = images.length){//图片下标越界时
loopCount=0;
}
img=images[loopCount];
}
return img;
}
public void setLoopCount(int loopCount){
this.loopCount = loopCount;
}
}
package com.lovo.game.role;
import java.awt.Graphics;
import java.awt.Image;
import com.lovo.game.util.MoveImageChange;
public class ZhaoYun {
public static Image[] zyImage;
private int x =600;
private int y =300;
private int width =200;
private int height =130;
private MoveImageChange moveChange = new MoveImageChange(3);
public void drawImage(Graphics memoryGraphics){
Image img = moveChange.imageChange(zyImage);
memoryGraphics.drawImage(img,this.x,this.y,this.width,this.height,null);
java动作游戏代码的介绍就聊到这里吧,感谢你花时间阅读本站内容 , 更多关于java 游戏 代码、java动作游戏代码的信息别忘了在本站进行查找喔 。

    推荐阅读