java弹球游戏代码_Java实现简单的弹球游戏本⽂实例为⼤家分享了Java实现简单的弹球游戏的具体代码,供⼤家参考,具体内容如下
该程序主要是⽤于对java图形化界⾯编程进⾏联系,程序实现全部采⽤的是AWT包下的类。
程序仅做参考,供学习使⽤。
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.Timer;
public class PinBallGame {
//创建窗⼝对象
private Frame frame = new Frame("弹球游戏");
//桌⾯宽度
private final int TABLE_WTDTH = 300;
/
/桌⾯⾼度
private final int TABLE_HEIGHT = 400;
//球拍的⾼度和宽度
private final int RACKET_WIDTH = 60;
private final int RACKET_HETGHT = 20;
//⼩球的⼤⼩
private final int BALL_SIZE = 16;
//定义变量,记录⼩球的坐标
private int ballX = 120;
private int ballY = 20;
//定义变量,记录⼩球在x和y⽅向上分别移动的速度
private int speedY = 10;
private int speedX = 5;
//定义变量,记录球拍的坐标
private int racketX = 120;
private final int racketY = 340;
java爱心代码编程简单//定义变量,标识当前游戏是否已结束
private boolean isOver = false;
//声明⼀个定时器
private Timer timer;
//⾃定义⼀个类,继承Canvas,充当画布
@SuppressWarnings("serial")
private class MyCanvas extends Canvas{
@Override
public void paint(Graphics g) {
//TODO 在这⾥绘制内容
if (isOver) {
//游戏结束
g.setColor(Color.BLUE);
g.setFont(new Font("Times",Font.BOLD,30));
g.drawString("游戏结束!", 50, 200);
}else{
//游戏中
/
/绘制⼩球
g.setColor(Color.RED);
g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
//绘制球拍
g.setColor(Color.PINK);
g.fillRect(racketX, racketY, RACKET_WIDTH, RACKET_HETGHT); }
}
}
//创建绘画区域
MyCanvas drawArea = new MyCanvas();
public void init() {
/
/组装视图,游戏逻辑的控制
//完成球拍坐标的变化
KeyListener listener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
//获取当前按下的键
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
//0) {
racketX -= 10;
}
}
if (keyCode == KeyEvent.VK_RIGHT) {
//-> 应该向右移动
if (racketX =(TABLE_WTDTH-BALL_SIZE)) {
speedX = -speedX;
}
if (ballY <= 0 || (ballY > racketY-BALL_SIZE && ballX>racketX && ballX < racketX+RACKET_WIDTH)) { speedY = -speedY;
}
if (ballY > racketY-BALL_SIZE && (ballX < racketX || ballX > racketX+RACKET_WIDTH)) {
//当前⼩球超出了球拍的范围,游戏结束
//停⽌定时器
timer.stop();
//修改游戏是否结束的标记
isOver = true;
//重绘界⾯
}
//更新⼩球的坐标,重绘界⾯
ballX += speedX;
ballY += speedY;
//重绘界⾯
}
};
timer = new Timer(100, task);
timer.start();
drawArea.setPreferredSize(new Dimension(TABLE_WTDTH,TABLE_HEIGHT)); frame.add(drawArea);
//设置frame最佳⼤⼩,并可视
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
}
});
}
public static void main(String[] args) {
new PinBallGame().init();
}
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持脚本之家。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论