您的位置:首页 > 移动开发 > 微信开发

Java小程序之桌球动起来!

2016-08-03 23:02 183 查看
亲爱的小伙伴们,最近好久都没有更新博客了!因为我在忙着学MySQL数据库去了!

经过一段时间的钻研,终于学完了MySQL数据库的基础知识,现在回归到Java,会慢慢结合数据库写一些小东西,敬请期待!

今天学到一招,给大家分享一下。

开发小游戏的基本步骤:

1.搭建窗体

2.加载图片

3.增加动态效果

4.通过所学的数学函数来控制物体的运动

下面给大家带来一个小小的桌球游戏,桌球碰到边界会弹回去,球会一直在我们的窗体中不断的运动

源代码:

package com.bluesky;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.*;

public class SimpleBallGame extends JFrame{

private static final long serialVersionUID = 1L;
//获得我们保存好的图片,在项目下新建一个Floder文件夹,名字问Images,往里面复制一张图片
Image ball = Toolkit.getDefaultToolkit().getImage("Images/Ball.gif");
//缓冲背景图片
Image offScreeImage = null;
//通过改变变量x,y的值实现物体的运动
double x=100;
double y=100;
//角度
double degree=3.14/3;

//窗体的基本设置
public void lanchFrame(){
this.setSize(500, 400);
this.setLocationRelativeTo(null);
this.setBackground(Color.black);
this.setTitle("简单桌球游戏");
this.setVisible(true);
//控制物体运动的线程
new Thread(new BallGameThread()).start();
}

//解决闪烁现象的方法
public void update(Graphics g){
if(offScreeImage==null) this.createImage(500,400);
Graphics offg = offScreeImage.getGraphics();
paint(offg);
g.drawImage(offScreeImage, 0, 0, null);
}

//画球的方法
public void paint(Graphics g){
g.fillRect(0, 0, 500, 400);
Color c = g.getColor();
g.setColor(Color.red);
g.drawImage(ball,(int)x,(int)y,50, 50, null);
x=x+50*Math.cos(degree);
y=y+50*Math.sin(degree);
if(x>450 || x<0)  degree=3.14-degree;
if(y>350|| y<40)   degree=-degree;
g.setColor(c);
}

public static void main(String[] args) {
new SimpleBallGame().lanchFrame();
}

//线程的具体实现
private class BallGameThread implements Runnable{

public void run() {
try {
while(true){
repaint();
Thread.sleep(200);}
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}


运行结果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: