当前位置:首页 » 编程语言 » java弹球

java弹球

发布时间: 2023-02-11 07:58:16

❶ 急求一个java的躲避弹球小游戏的代码

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.Timer;
public class PinBall
{
private final int TABLE_WIDTH = 300;//桌面宽度
private final int TABLE_HEIGHT = 400;//桌面高度
private final int RACKET_Y = 340;//球拍的垂直位置
private final int RACKET_HEIGHT = 20;//球拍高度
private final int RACKET_WIDTH = 60;//球拍宽度
private final int BALL_SIZE = 16;//球的大小
private Frame f = new Frame("弹球游戏");//实例化一个窗口
Random rand = new Random();//实例化一个随机数生成器
private int ySpeed = 10;//小球的纵向运动数度、
private double xyRate = rand.nextDouble() - 0.5;//返回一个-0.5到0.5之间的比率用控制小球运动方向
private int xSpeed = (int)(ySpeed*xyRate*2);//这个横向速度在-10到10之间,产生左右摆动运动效果
private int ballX = rand.nextInt(200)+20;//小球开始的横坐标位置,200表示产生0到100之间的随机数
private int ballY = rand.nextInt(10)+20;//小球开始的纵坐标位置
private int racketX = rand.nextInt(200);//球拍开始时的横坐标位置
private MyCanvas tableArea = new MyCanvas();//实力化一个画布工具,集成Canvas类
private String shape = "";//保存需要绘制图形的字符串属性
Timer timer;//声明一个时间变量
private boolean isLose = false;//表示游戏是否结束

public void init()
{
tableArea.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT));//定义画布大小
f.add(tableArea);//添加画布到窗口
KeyAdapter keyProcessor = new KeyAdapter()//实例化一个键盘监听事件适配器
{
public void keyPressed(KeyEvent ke)//重写适配器里面的按下某键盘方法
{
if(ke.getKeyCode()==KeyEvent.VK_LEFT)//按下键盘左键时
{
if(racketX > 0)//球拍左边框不能出画布的左边框
racketX -=10;//按一左键次向左移动10个像素
}
if(ke.getKeyCode()==KeyEvent.VK_RIGHT)//按下键盘右键时
{
if(racketX < TABLE_WIDTH - RACKET_WIDTH)//球拍右边框不能出画布的右边框
racketX +=10;//按一次右键移动向右移动10个像素
}
}
};
f.addKeyListener(keyProcessor);//给窗口添加键盘监听器
tableArea.addKeyListener(keyProcessor);//给画布添加键盘监听器
ActionListener taskPerformer = new ActionListener()//这里是实例化了一个监听接口,这个接口里面只有一个方法
{
public void actionPerformed(ActionEvent evt)//重写这个接口里面的方法,判断小球的位置
{
if(ballX<=0 || ballX>=TABLE_WIDTH-BALL_SIZE)//保证小球横向上在画布之内运动
{
xSpeed = -xSpeed;//触发反方向运动
}
if(ballY>=RACKET_Y-BALL_SIZE&&(ballX<racketX||ballX>racketX+RACKET_WIDTH))//出了球拍的可击打范围
{
timer.stop();//停止对监听器的触发
isLose=true;//将标志isLose变量置为true
tableArea.repaint();//调用画布的重绘方法
}
else if(ballY<=0||(ballY>=RACKET_Y-BALL_SIZE&&ballY>racketX&&ballX<=racketX+RACKET_WIDTH))//小球在球拍之内,而其到达球拍的高度
{
ySpeed=-ySpeed;//上下方向改变,小球反弹
}
ballY+=ySpeed;//小球的坐标在纵向上增加
ballX+=xSpeed;//小球的坐标在横向上的增加
tableArea.repaint();//调用画布的重绘方法3
}
};
timer = new Timer(100,taskPerformer);//每隔0.1秒运行一次监听器
timer.start();//计时器开始运行
f.addWindowListener(new MyListener());//关闭窗口事件
f.pack();//设置窗口最佳大小
f.setVisible(true);//显示窗口
}
class MyListener extends WindowAdapter//关闭窗口的类
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)//程序入口
{
new PinBall().init();//调用PinBall类里面的init()方法
}
class MyCanvas extends Canvas//建一个集成Canvas类的类
{
public void paint(Graphics g)//重写父类的绘图方法
{
if(isLose)//如果isLose为真,则在画布里打印“游戏已结束”
{
g.setColor(new Color(255,0,0));//当前颜色
g.setFont(new Font("黑体",Font.BOLD,30));//字体名称,样式,大小
g.drawString("游戏已结束!",50,200);//按坐标绘制文字图形
}
else//负责
{
g.setColor(new Color(240,240,80));//当前颜色
g.fillOval(ballX,ballY,BALL_SIZE,BALL_SIZE);//填充颜色,根据坐标和长宽填充圆形
g.setColor(new Color(80,80,200));//当前颜色
g.fillRect(racketX,RACKET_Y,RACKET_WIDTH,RACKET_HEIGHT);//填充颜色,根据坐标和长宽填充矩形
}
}
}
}

❷ JAVA如何实现小球的弹性碰撞

我没用java写过代码,所以我只说算法,代码你自己翻译下
按C的语法来:
void xiaoqiu
{
int UB=10,DB=200,LB=10,RB=200; //定义弹球范围的边界
int sh=1; //定义横向步长
int sz=1; //定义纵向步长(两步长之比决定了反弹的角度)
int x=LB,y=UB; //定义坐标
int i=10000; //循环次数(自己选择跳出手段)

while(i>0)
{
i--;
x=x+sh;
if(x>=RB||x<=LB) sh=-sh; //碰壁后步长变反
y=y+sz;
if(y>=DB||y<=UB) sz=-sz; //碰壁后步长变反
(显示代码)

}
return;

}

总得来说,就是相当于横向和纵向分别处理移动、反弹的问题,碰壁后步长变为相反数

不懂请追问

❸ eclupse多线程,发射弹球遇边界弹回java编程

一,设置一个二维数组,数组的每一行代表一个球
二,小球移动的速度设置一个衰减因子,这样一定次数后会停止
三,小球的碰撞,小球速度改变

❹ java弹球游戏

import java.awt.Color;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import java.awt.event.MouseEvent;

import java.awt.event.MouseMotionListener;

import java.awt.image.BufferedImage;


import javax.swing.JFrame;

import javax.swing.JPanel;


public class CopyOfBallCrash implements Runnable {

public static void main(final String[] args) {

new Thread(new CopyOfBallCrash()).start();

}


private final int width = 400;

private final int height = 700;

private int mouse_X, mouse_Y;

private final BufferedImage offscreen = new BufferedImage(width, height,

BufferedImage.TYPE_4BYTE_ABGR);

private final JPanel panel = new JPanel();

private final Shape ball = new Shape(100, 100, 1, 1, 20);

private final Shape rect = new Shape(0, 100, 20);


public CopyOfBallCrash() {

final JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel.setPreferredSize(new Dimension(width, height));

ball.setBounds(width, height);

rect.setBounds(width, height);

frame.setContentPane(panel);

panel.addMouseMotionListener(new MouseMotionListener() {

@Override

public void mouseDragged(final MouseEvent e) {}


@Override

public void mouseMoved(final MouseEvent e) {

mouse_X = e.getX();

mouse_Y = e.getY();

}

});

frame.pack();

frame.setVisible(true);

}


public void paint(final Graphics g) {

final Graphics2D g2d = offscreen.createGraphics();

g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2d.fillRect(0, 0, width, height);

g2d.setColor(Color.blue);

rect.drawRect(g2d, mouse_X);

g2d.setColor(Color.red);

ball.drawOval(g2d, rect);

if (Shape.isLose) g2d.drawString("你输了!!!", 100, 300);

g2d.dispose();

g.drawImage(offscreen, 0, 0, null);

}


@Override

public void run() {

while (true)

paint(panel.getGraphics());

}

}


class Shape {

public int width, height;

public int x, y, vx, vy, r, w, h;

public static boolean isLose;


public Shape(final int x, final int y, final int vx, final int vy, final int r) {

super();

this.x = x;

this.y = y;

this.vx = vx;

this.vy = vy;

this.r = r;

}


public Shape(final int x, final int w, final int h) {

super();

this.x = x;

this.w = w;

this.h = h;

}


public final void setBounds(final int width, final int height) {

this.width = width;

this.height = height;

}


public final void drawOval(final Graphics2D g2d, final Shape shape) {

if (y + h >= height) {

isLose = true;

return;

}

if (x + vx <= 0 || x + vx + w >= width) vx = -vx;

if (y + vy <= 0) vy = -vy;

if (isCrashOutside(shape.x, shape.y, shape.w, shape.h) && y + w >= shape.y)

vy = -vy;

x += vx;

y += vy;

g2d.fillOval(x, y, r, r);

}


public final void drawRect(final Graphics2D g2d, final int mouseX) {

y = height - h;

if (x + w < width && x < mouseX) x++;

if (x > 0 && x > mouseX) x--;

g2d.fillRect(x, y, w, h);

}


public final boolean isCrashOutside(final int x, final int y, final int w,

final int h) {

return (this.x > x ? this.x <= w + x : x <= r + this.x)

&& (this.y > y ? this.y <= h + y : y <= r + this.y);

}

}


❺ Java程序解惑,希望大家帮帮忙,打砖块游戏不能用键盘控制。开始和移动都不能。运行是用application吗

import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ballApplet extends Applet implements Runnable {
Dimension d;
Font bFont = new Font("Helvetica", Font.BOLD, 24);
Font sFont = new Font("Helvetica", Font.BOLD, 14);
FontMetrics fmSmall, fmBig;
Graphics goff;
Image img;
Thread mThread;
boolean ingame = false;
int ballx, bally, batpos;
int batdpos = 0;
int balldx = 0, balldy = 0, dxval;
int iScroe, ballNum;
boolean[] showbrick;
int brickNumOfLine;
final int bWidth = 5;
final int batW = 20;
final int ballsize = 5;
final int batH = 5;
final int scoreH = 25;
final int brickW = 15;
final int brickH = 8;
final int space = 1;
final int backcol = 0x102040;
final int line = 4;
final int startline = 32;

public void init() {
Graphics g;
d=size();
setBackground(new Color(backcol));
brickNumOfLine = (d.width-2*bWidth)/(brickW +space);
d.width = brickNumOfLine*(brickW+space)+(2*bWidth);
g = getGraphics();
g.setFont(sFont);
fmSmall= g.getFontMetrics();
g.setFont(bFont);
fmBig = g.getFontMetrics();
showbrick = new boolean[brickNumOfLine*line];
this.addKeyListener(new BallGameKeyListener());
GameInit();

}

public void GameInit() {
batpos = (d.width - batW) / 2;
ballx = (d.width - ballsize) / 2;
bally = (d.height - ballsize - scoreH - 2 * bWidth);
iScroe = 0;
ballNum = 3;
dxval = 2;
if (Math.random() < 0.5)
balldx = dxval;
else
balldx = -dxval;
balldy = -dxval;
batdpos = 0;
InitBricks();
}

public void InitBricks() {
int i;
for (i = 0; i < line * brickNumOfLine; i++)
showbrick[i] = true;
}

// public boolean keyDown(Event e, int key) {
// if (ingame) {
// if (key == Event.LEFT)
// batdpos = -4;
// if (key == Event.RIGHT)
// batdpos = 4;
// if (key == Event.ESCAPE)
// ingame = false;
// } else {
// if (key == 's' || key == 'S') {
// ingame = true;
// GameInit();
// }
// }
// return true;
// }
//
// public boolean keyUp(Event e, int key) {
// if (key == Event.LEFT || key == Event.RIGHT)
// batdpos = 0;
// return true;
// }

public void paint(Graphics g) {
if (goff == null && d.width > 0 && d.height > 0) {
img = createImage(d.width, d.height);
goff = img.getGraphics();
}
if (goff == null || img == null)
return;
goff.setColor(new Color(backcol));
goff.fillRect(0, 0, d.width, d.height);
if (ingame)
PlayGame();
else
ShowIntroScreen();
g.drawImage(img, 0, 0, this);
}

public void PlayGame() {
MoveBall();
CheckBat();
CheckBricks();
DrawPlayField();
DrawBricks();
ShowScore();
}

public void ShowIntroScreen() {
MoveBall();
CheckBat();
CheckBricks();
BatDummyMove();
DrawPlayField();
DrawBricks();
ShowScore();
goff.setFont(bFont);
goff.setColor(new Color(96, 128, 255));
String s = "弹球游戏";
goff.drawString(s, (d.width - fmBig.stringWidth(s)) / 2, (d.height
- scoreH - bWidth) / 2 - 20);
goff.setFont(sFont);
goff.setColor(new Color(128, 255, 32));
s = "请按下'S'键开始游戏";
goff.drawString(s, (d.width - fmSmall.stringWidth(s)) / 2, (d.height
- scoreH - bWidth) / 2 + 30);
goff.setColor(new Color(255, 160, 64));
s = "使用方向键控制球拍移动";
goff.drawString(s, (d.width - fmSmall.stringWidth(s)) / 2, (d.height
- scoreH - bWidth) / 2 + 50);
}

public void DrawBricks() {
int i, j;
boolean nobricks = true;
int colorDelta = 255 / (line - 1);
for (j = 0; j < line; j++) {
for (i = 0; i < brickNumOfLine; i++) {
if (showbrick[j * brickNumOfLine + i]) {
nobricks = false;
goff.setColor(new Color(255, j * colorDelta, 255 - j
* colorDelta));
goff.fillRect(bWidth + i * (brickW + space), startline + j
* (brickH + space), brickW, brickH);
}
}
}
if (nobricks) {
InitBricks();
if (ingame)
iScroe += 100;
}
}

public void DrawPlayField() {
goff.setColor(Color.white);
goff.fillRect(0, 0, d.width, bWidth);
goff.fillRect(0, 0, bWidth, d.height);
goff.fillRect(d.width - bWidth, 0, bWidth, d.height);
goff.fillRect(0, d.height - bWidth, d.width, bWidth);
goff.fillRect(batpos, d.height - 2 * bWidth - scoreH, batW, batH);
goff.fillRect(ballx, bally, ballsize, ballsize);
}

public void ShowScore() {
goff.setFont(sFont);
goff.setColor(Color.white);
goff.drawString("得分:" + iScroe, 40, d.height - 10);
String s = "生命:" + ballNum;
goff
.drawString(s, d.width - 40 - fmSmall.stringWidth(s),
d.height - 10);
}

public void MoveBall() {
ballx += balldx;
bally += balldy;
if (bally <= bWidth) {
balldy = -balldy;
bally = bWidth;
}
if (bally >= (d.height - ballsize - scoreH)) {
if (ingame) {
ballNum--;
if (ballNum <= 0)
ingame = false;
}
ballx = batpos + (batW - ballsize) / 2;
bally = startline + line * (brickH + space);
balldy = dxval;
balldx = 0;
}
if (ballx >= (d.width - bWidth - ballsize)) {
balldx = -balldx;
ballx = d.width - bWidth - ballsize;
}
if (ballx <= bWidth) {
balldx = -balldx;
ballx = bWidth;
}
}

public void BatDummyMove() {
if (ballx < (batpos + 2))
batpos -= 3;
else if (ballx > (batpos + batW - 3))
batpos += 3;
}

public void CheckBat() {
batpos += batpos;
if (batpos < bWidth)
batpos = bWidth;
else if (batpos > (d.width - bWidth - batW))
batpos = (d.width - bWidth - batW);
if (bally >= (d.height - scoreH - 2 * bWidth - ballsize)
&& bally < (d.height - scoreH - 2 * bWidth)
&& (ballx + ballsize) >= batpos && ballx <= (batpos + batW)) {
bally = d.height - scoreH - ballsize - bWidth * 2;
balldy = -dxval;
balldx = CheckBatBounce(balldx, ballx - batpos);
}
}

public int CheckBatBounce(int dy, int delta) {
int sign;
int stepsize, i = -ballsize, j = 0;
stepsize = (ballsize + batW) / 8;
if (dy > 0)
sign = 1;
else
sign = -1;
while (i < batW && delta > i) {
i += stepsize;
j++;
}
switch (j) {
case 0:
case 1:
return -4;
case 2:
return -3;
case 7:
return 3;
case 3:
case 6:
return sign * 2;
case 4:
case 5:
return sign * 1;
default:
return 4;
}
}

public void CheckBricks() {
int i, j, x, y;
int xspeed = balldx;
if (xspeed < 0)
xspeed = -xspeed;
int ydir = balldy;
if (bally < (startline - ballsize)
|| bally > (startline + line * (space + brickH)))
return;
for (j = 0; j < line; j++) {
for (i = 0; i < brickNumOfLine; i++) {
if (showbrick[j * brickNumOfLine + i]) {
y = startline + j * (space + brickH);
x = bWidth + i * (space + brickW);
if (bally >= (y - ballsize) && bally < (y + brickH)
&& ballx >= (x - ballsize) && ballx < (x + brickW)) {
showbrick[j * brickNumOfLine + i] = false;
if (ingame)
iScroe += (line - j);
if (ballx >= (x - ballsize)
&& ballx <= (x - ballsize + 3)) {
balldx = -xspeed;
} else if (ballx <= (x + brickW - 1)
&& ballx >= (x + brickW - 4)) {
balldx = xspeed;
}
balldy = -ydir;
}
}
}
}
}

public void run() {
long starttime;
Graphics g = getGraphics();
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
while (true) {
starttime = System.currentTimeMillis();
try {
paint(g);
starttime += 20;
Thread.sleep(Math
.max(0, starttime - System.currentTimeMillis()));
} catch (InterruptedException e) {
break;
}
}
}

public void start() {
if (mThread == null) {
mThread = new Thread(this);
mThread.start();
}
}

public void stop() {
if (mThread != null) {
mThread.stop();
mThread = null;
}
}

public static void main(String[] args) {
Frame frame = new Frame("弹球游戏");
ballApplet app = new ballApplet();
frame.add("Center", app);
frame.setSize(270, 350);
frame.validate();
frame.setVisible(true);
frame.addWindowListener(new WindowControl(app));
app.init();
app.start();
}

class BallGameKeyListener implements KeyListener{

@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
// TODO Auto-generated method stub
if (ingame) {

switch(key){
case KeyEvent.VK_ESCAPE:
ingame = false;
break;
case KeyEvent.VK_RIGHT:
batdpos = 4;
break;
case KeyEvent.VK_LEFT:
batdpos = -4;
break;
}

} else {
if (key == KeyEvent.VK_S) {
ingame = true;
GameInit();
}
}
}

@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT)
batdpos = 0;
}

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}

}
}

class WindowControl extends WindowAdapter {
Applet app;

public WindowControl(Applet app) {
this.app = app;
}

public void WindowClosing(WindowEvent e) {
app.stop();
app.destroy();
System.exit(0);
}

}

给你+了个keyListener 然后按你的理念给你加入了按键判定。按S按键可以开始游戏但方向键不能移动应该是你的方法错误了你自己修改去把懒得看了。。太长了 一般画可以移动的物体是直接按坐标来画然后移动的时候+= 好哦这-= 控制坐标 我发现你的错误是你用batdpos这个变量去控制移动。。但你根本没用这个变量去画图。。所以不能移动。。你自己去改把。。

热点内容
java返回this 发布:2025-10-20 08:28:16 浏览:585
制作脚本网站 发布:2025-10-20 08:17:34 浏览:880
python中的init方法 发布:2025-10-20 08:17:33 浏览:574
图案密码什么意思 发布:2025-10-20 08:16:56 浏览:761
怎么清理微信视频缓存 发布:2025-10-20 08:12:37 浏览:676
c语言编译器怎么看执行过程 发布:2025-10-20 08:00:32 浏览:1004
邮箱如何填写发信服务器 发布:2025-10-20 07:45:27 浏览:248
shell脚本入门案例 发布:2025-10-20 07:44:45 浏览:108
怎么上传照片浏览上传 发布:2025-10-20 07:44:03 浏览:798
python股票数据获取 发布:2025-10-20 07:39:44 浏览:705