java初学编程之小球碰撞

合集下载

javascript实现10个球随机运动、碰撞实例详解

javascript实现10个球随机运动、碰撞实例详解

javascript实现10个球随机运动、碰撞实例详解本⽂实例讲述了javascript实现10个球随机运动、碰撞的⽅法。

分享给⼤家供⼤家参考。

具体如下:学了⼀段时间的javascript了,做过⼀些⼩案例,⽬前最有难度的就是10个⼩球随机碰撞效果,这不,把它上上来与⼤家分享⼀下,相信不少和我⼀样的菜鸟在开始上⼿编程时都会有不少的困惑,希望它能给⼀些⼈带来帮助。

效果要求:10个⼩球在页⾯随机移动,碰到窗⼝边界或其他⼩球都会反弹思路:1、10个⼩球是10个div;2、碰窗⼝反弹,定义vx vy为⼩球的移动变量,以及⼀个弹⼒变量bounce(负值),⼩球碰窗⼝边界时,vx vy分别乘以bounce,则改变了⼩球移动⽅向3、⼩球相碰反弹,说简单点,当两个⼩球的圆⼼距变量dist⼩于其最⼩值(半径之和)则改变球的移动⽅向,实现反弹好了,代码如下:html和js是分开的⽂件哟test.html⽂件如下:<html><head><title></title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><style type="text/css">body {margin:0;padding:0;text-align: center;}#screen { width: 800px; height: 640px; position: relative; background: #ccccff;margin: 0 auto;vertical-align: bottom}#inner { position: absolute; left:0px; top:0px; width:100%; height:100%; }#screen p {color:white;font:bold 14px;}.one { background-image:url('bubble.png'); background-position: -66px -58px; }.two { background-image:url('bubble.png'); background-position: -66px -126px;}.three { background-image:url('bubble.png'); background-position: -66px -194px; }.four { background-image:url('bubble.png'); background-position: -66px -263px; }.five { background-image:url('bubble.png'); background-position: -66px -331px; }.six { background-image:url('bubble.png'); background-position: -66px -399px; }.seven { background-image:url('bubble.png'); background-position: -66px -194px; }.eight { background-image:url('bubble.png'); background-position: -66px -263px; }.nine { background-image:url('bubble.png'); background-position: -66px -331px; }.ten{ background-image:url('bubble.png'); background-position: -66px -399px; }</style></head><body><div id="screen" ><p>hi test it!</p><div id="inner"></div></div><input type="button" id="start" value="start" ><input type="button" id="stop" value="stop"><br><br><br><script type="text/javascript" src="test.js"></script></body></html>test.js⽂件如下:var getFlag=function (id) {return document.getElementByIdx_x(id); //获取元素引⽤}var extend=function(des, src) {for (p in src) {des[p]=src[p];}return des;}var clss=['one','two','three','four','five','six','seven','eight','nine','ten'];var Ball=function (diameter,classn) {var ball=document.createElement_x("div");ball.className=classn;with(ball.style) {width=height=diameter+'px';position='absolute';}return ball;}var Screen=function (cid,config) {//先创建类的属性var self=this;if (!(self instanceof Screen)) {return new Screen(cid,config)}config=extend(Screen.Config, config) //configj是extend类的实例self.container=getFlag(cid); //窗⼝对象self.ballsnum=config.ballsnum;self.diameter=56; //球的直径self.radius=self.diameter/2;self.spring=config.spring; //球相碰后的反弹⼒self.bounce=config.bounce; //球碰到窗⼝边界后的反弹⼒self.gravity=config.gravity; //球的重⼒self.balls=[]; //把创建的球置于该数组变量self.timer=null; //调⽤函数产⽣的时间idself.L_bound=0; //container的边界self.R_bound=self.container.clientWidth;self.T_bound=0;self.B_bound=self.container.clientHeight;};Screen.Config={ //为属性赋初值ballsnum:10,spring:0.8,bounce:-0.9,gravity:0.05};Screen.prototype={initialize:function () {var self=this;self.createBalls();self.timer=setInterval(function (){self.hitBalls()}, 30)},createBalls:function () {var self=this, num=self.ballsnum;var frag=document.createDocumentFragment(); //创建⽂档碎⽚,避免多次刷新 for (i=0;i<num;i++) {var ball=new Ball(self.diameter,clss[ Math.floor(Math.random()* num )]);ball.diameter=self.diameter;ball.radius=self.radius;ball.style.left=(Math.random()*self.R_bound)+'px'; //球的初始位置,ball.style.top=(Math.random()*self.B_bound)+'px';ball.vx=Math.random() * 6 -3;ball.vy=Math.random() * 6 -3;frag.appendChild(ball);self.balls[i]=ball;}self.container.appendChild(frag);},hitBalls:function () {var self=this, num=self.ballsnum,balls=self.balls;for (i=0;i<num-1;i++) {var ball1=self.balls[i];ball1.x=ball1.offsetLeft+ball1.radius; //⼩球圆⼼坐标ball1.y=ball1.offsetTop+ball1.radius;for (j=i+1;j<num;j++) {var ball2=self.balls[j];ball2.x=ball2.offsetLeft+ball2.radius;ball2.y=ball2.offsetTop+ball2.radius;dx=ball2.x-ball1.x; //两⼩球圆⼼距对应的两条直⾓边dy=ball2.y-ball1.y;var dist=Math.sqrt(dx*dx + dy*dy); //两直⾓边求圆⼼距var misDist=ball1.radius+ball2.radius; //圆⼼距最⼩值if(dist < misDist) {//假设碰撞后球会按原⽅向继续做⼀定的运动,将其定义为运动Avar angle=Math.atan2(dy,dx);//当刚好相碰,即dist=misDist时,tx=ballb.x, ty=ballb.ytx=balla.x+Math.cos(angle) * misDist;ty=balla.y+Math.sin(angle) * misDist;//产⽣运动A后,tx > ballb.x, ty > ballb.y,所以⽤ax、ay记录的是运动A的值ax=(tx-ballb.x) * self.spring;ay=(ty-ballb.y) * self.spring;//⼀个球减去ax、ay,另⼀个加上它,则实现反弹balla.vx-=ax;balla.vy-=ay;ballb.vx+=ax;ballb.vy+=ay;}}}for (i=0;i<num;i++) {self.moveBalls(balls[i]);}},moveBalls:function (ball) {var self=this;ball.vy+=self.gravity;ball.style.left=(ball.offsetLeft+ball.vx)+'px';ball.style.top=(ball.offsetTop+ball.vy)+'px';//判断球与窗⼝边界相碰,把变量名简化⼀下var L=self.L_bound, R=self.R_bound, T=self.T_bound, B=self.B_bound, BC=self.bounce;if (ball.offsetLeft < L) {ball.style.left=L;ball.vx*=BC;}else if (ball.offsetLeft + ball.diameter > R) {ball.style.left=(R-ball.diameter)+'px';ball.vx*=BC;}else if (ball.offsetTop < T) {ball.style.top=T;ball.vy*=BC;}if (ball.offsetTop + ball.diameter > B) {ball.style.top=(B-ball.diameter)+'px';ball.vy*=BC;}}}window.onload=function() {var sc=null;getFlag('start').onclick=function () {document.getElementByIdx_x("inner").innerHTML='';sc=new Screen('inner',{ballsnum:10, spring:0.8, bounce:-0.9, gravity:0.05});sc.initialize();}getFlag('stop').onclick=function() {clearInterval(sc.timer);}}测试后的效果还是很不错的,各位也许会觉得代码挺长,但是其思路还是蛮清晰的:⾸先创建Screen类,并在Screen的构造函数中给出了球移动、碰撞所需的各种属性变量,如ballsnum、spring、bounce、gravity等等然后⽤原型prototype给出相应的函数,如创建球,createBalls,球碰撞hitBalls,球移动moveBalls,给每个函数添加相应的功能、最后⽤按钮点击事件调⽤函数,仅此⽽已。

被多个小球同时碰撞 代码

被多个小球同时碰撞 代码

被多个小球同时碰撞代码当多个小球同时碰撞时,你可以使用编程语言来模拟这个过程。

以下是一个简单的示例代码,使用Python语言来实现多个小球的碰撞:python.import random.class Ball:def __init__(self, x, y, radius, speed):self.x = x.self.y = y.self.radius = radius.self.speed = speed.self.direction = random.uniform(0, 2 math.pi) # 随机初始化小球的运动方向。

def move(self):self.x += self.speed math.cos(self.direction)。

self.y += self.speed math.sin(self.direction)。

def check_collision(self, other_ball):distance = math.sqrt((self.x other_ball.x) 2 + (self.y other_ball.y) 2)。

if distance <= self.radius + other_ball.radius:# 碰撞后,更新小球的运动方向。

self.direction = math.atan2(other_ball.y self.y, other_ball.x self.x)。

other_ball.direction = math.atan2(self.y other_ball.y, self.x other_ball.x)。

# 创建多个小球。

balls = []for i in range(5):x = random.randint(0, 100)。

y = random.randint(0, 100)。

radius = random.randint(5, 10)。

Java中小球碰撞并使用按钮控制数量实例代码

Java中小球碰撞并使用按钮控制数量实例代码

Java中⼩球碰撞并使⽤按钮控制数量实例代码刚开始实训第三天,要求java做⼀个⼩球碰撞的⼩游戏,啥也不会的我,决定写写啥。

先根据程序要求写了⼀个窗⼝package three.day;import java.awt.event.*;import javax.swing.*;public class Windows extends JFrame{DrowJPs jp=new DrowJPs();public void init() {this.setSize(800,500);this.setLocationRelativeTo(rootPane);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setTitle("天沫⼂寒枫");this.add(jp);this.setVisible(true);}public static void main(String[] args) {Windows win=new Windows();win.init();}}然后写⼀个画图package three.day;import java.awt.Color;import java.awt.Graphics;import javax.swing.JPanel;public class DrowJPs extends JPanel implements Runnable{int[] x=new int[1000],y=new int[1000],s=new int[1000],xt=new int[1000],yt=new int[1000];int[] r=new int[1000],g=new int[1000],b=new int[1000];int num=5;public DrowJPs() {for (int i = 0; i < 1000; i++) {x[i]=(int)(Math.random()*450);y[i]=(int)(Math.random()*230);r[i]=(int)(Math.random()*256);g[i]=(int)(Math.random()*256);b[i]=(int)(Math.random()*256);xt[i]=(int)(Math.random()*4+1);yt[i]=(int)(Math.random()*4+1);s[i]=(int)(Math.random()*200+20);}Thread t=new Thread(this);Thread t1=new Thread(this);t.start();t1.start();}public void paint(Graphics gr) {super.paint(gr);setBackground(Color.pink);for (int i = 0; i < num; i++) {gr.setColor(new Color(r[i],g[i],b[i]));gr.fillOval(x[i], y[i], s[i], s[i]);}}public void run() {while(true) {for (int i = 0; i < num; i++) {if(x[i]<=0|x[i]>=(790-s[i]))xt[i]*=-1;if(y[i]<=0|y[i]>=(465-s[i]))yt[i]*=-1;x[i]+=xt[i];y[i]+=yt[i];try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}repaint();}}}}开了俩个线程,⼀个数量⼤了有点卡这样运⾏就ok啦另外有个拓展要求使⽤⿏标控制增加球的数量光增加怎么⾏呢,当然也得来⼀个减少那就再init函数⾥加⼊JButton btn = new JButton("增加⼀个⼩球");JButton btn1 = new JButton("减少⼀个⼩球");btn.setBounds(0, 0, 400, 600);btn1.setBounds(400, 0, 400, 600);this.add(btn);this.add(btn1);btn.addActionListener(new MyListener());btn1.addActionListener(new MyListener1());注意画布jp⼀定要加在按钮的后⾯不然是看不见画布的再写俩个监听就⾏了class MyListener implements ActionListener{public void actionPerformed(ActionEvent e) {jp.addnum(0);}}class MyListener1 implements ActionListener{public void actionPerformed(ActionEvent e) {jp.addnum(1);}}传01⽅便画布那边检测增减画布那边简简单单加个设置num的函数就⾏public void addnum(int i) {if(i==0)num++;else num--;}呼,完成了,就是按钮不时地会闪现出来有点烦,还有球减到0画布可就没了总结到此这篇关于Java中⼩球碰撞并使⽤按钮控制数量的⽂章就介绍到这了,更多相关Java⼩球碰撞并控制数量内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

java编写弹跳的小球

java编写弹跳的小球

java编写弹跳的小球import java.awt.*;import java.awt.event.*;import javax.swing.*;//可以不是public 类public class jxiaoqiu extends JFrame implements ActionListener,Runnable{Thread thread;JButton startButton,threadButton,stopButton;boolean flag=true;JPanel canvas;static final int WIDTH=15,HEIGHT=15;//居然是WIDTH写错了int x=0,y=0,dx=2,dy=2;public jxiaoqiu(){setTitle("线程对比实验,重画模式");addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});//Container contentPane=getContentPane();//完全没有必要啊canvas=new JPanel();canvas.setBackground(new Color(120,220,250));//contentPane.add(canvas,"Center");//不是BorderLayout.CENTER?add(canvas,BorderLayout.CENTER);//contentPane.add(can)JPanel p=new JPanel();startButton=new JButton("不使用线程");startButton.addActionListener(this);p.add(startButton);threadButton=new JButton("使用线程");threadButton.addActionListener(this);p.add(threadButton);stopButton=new JButton("停止");stopButton.addActionListener(this);p.add(stopButton);//contentPane.add(p,"South");add(p,"South");//add(p,BorderLayout.SOUTH);是正规的setSize(300,200);setVisible(true);}public void actionPerformed(ActionEvent e){if(e.getSource()==startButton){bounce();}else if(e.getSource()==threadButton){start();}else {stop();}}public void move(boolean yn){Graphics g=canvas.getGraphics();g.setColor(canvas.getBackground());//画图的组建使用的方法:设置背景色g.fillOval(x,y,WIDTH,HEIGHT);//擦出之前的小球,否则是画线了Dimension d=canvas.getSize();if(x<0){x=0;dx=-dx;}if(y<0){y=0;dy=-dy;}if(x+WIDTH>d.width){x=d.width-WIDTH;dx=-dx;}//去掉WIDTH,越界后不回来if(y+HEIGHT>d.height){y=d.height-HEIGHT;dy=-dy;}x+=dx;y+=dy;g.setColor(Color.red);//设背景色为红色g.fillOval(x,y,WIDTH,HEIGHT);//画小球if(yn=true){try{thread.sleep(20);}catch(InterruptedException e){} }else {double z=0.371;for(int k=0;k<99999;k++){z=4*z*(1-z);}}}public void start(){flag=true;thread=new Thread(this); thread.start();}public void run(){while(flag){move(true);}}public void stop(){flag=false;}public void bounce(){int i=0;while(flag &&i<1000){move(flag);i++;}}public static void main(String args[]){ new jxiaoqiu();}}。

绘制随机小球来回弹动java代码

绘制随机小球来回弹动java代码

Java小球碰撞代码绘制小球随机位置,随机颜色(自定义颜色)来回碰撞。

这个代码只有上下左右四个方向,所以反弹也是固定的45°角。

首先是定义小球(Ball类)package picture;import java.awt.Color;import java.awt.Graphics;public class Ball {private int x,y;//分清定义是左上角顶点坐标还是圆心点坐标(圆心坐标)private int rSize;//半径private Color color;private int speed;private int orientation;private BallPanel panel;//获得小球所属的面板public static final int RIGHT_DOWN=0;public static final int RIGHT_ON=1;public static final int LEFT_DOWN=2;public static final int LEFT_ON=3;public Ball(){}public Ball(int x, int y, int rSize, Color color, int speed, int orientation) {super();this.x = x;this.y = y;this.rSize = rSize;this.color = color;this.speed = speed;this.orientation = orientation;}public void draw(Graphics g){g.setColor(color);g.fillArc(x-rSize, y-rSize/*左上角定点坐标*/, 2*rSize, 2*rSize, 0, 360);}//定义小球绘画的逻辑public void move(){//小球处在不同方向时移动所改变的坐标值switch(orientation){case RIGHT_DOWN:x+=speed;y+=speed;if(x+rSize >=panel.getWidth()){this.orientation = LEFT_DOWN;}if(y+rSize >=panel.getHeight()){this.orientation = RIGHT_ON;}break;case RIGHT_ON:x+=speed;y-=speed;if(x+rSize >=panel.getWidth()){this.orientation = LEFT_ON;}if(y-rSize <= 0 ){this.orientation = RIGHT_DOWN;}break;case LEFT_DOWN:x-=speed;y+=speed;if(x-rSize <= 0 ){this.orientation = RIGHT_DOWN;}if(y+rSize <=panel.getHeight()){this.orientation = LEFT_ON;}break;case LEFT_ON:x-=speed;y-=speed;if(x-rSize <= 0 ){this.orientation = RIGHT_ON;}if(y-rSize <= 0){this.orientation = LEFT_DOWN;}break;}/*碰到边界事件处理*/}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public int getrSize() {return rSize;}public void setrSize(int rSize) { this.rSize = rSize;}public Color getColor() {return color;}public void setColor(Color color) {this.color = color;}public int getSpeed() {return speed;}public void setSpeed(int speed) {this.speed = speed;}public int getOrientation() {return orientation;}public void setOrientation(int orientation) {this.orientation = orientation;}public BallPanel getPanel() {return panel;}public void setPanel(BallPanel panel) { this.panel = panel;}}然后是小球的面板(BallPanel)package picture;import java.awt.Color;import java.awt.Graphics;import javax.swing.JPanel;public class BallPanel extends JPanel{private int x = 0,y = 0;//构造函数提前调用startRun不合适private Ball[]balls;private Color[]cs = {Color.red,Color.blue,Color.green,Color.cyan,Color.yellow,Color.gray,Co lor.orange};public BallPanel(){this.setBackground(Color.WHITE);balls = new Ball[10];for(int i = 0 ;i<balls.length;i++){balls[i] = new Ball((int)(Math.random()*800),(int)(Math.random()*600),(int)(Math.random()*20)+10,cs[(int)(Math.random()*cs.length)],(int)(Math.random()*10)+1,(int)(Math.random()*4));balls[i].setPanel(this);}}public void paint(Graphics g){super.paint(g);for(int i=0;i<balls.length;i++){balls[i].draw(g);}}public void startRun(){new Thread(){public void run(){while(true){for(int i = 0;i<balls.length;i++){balls[i].move();}repaint();//重新画屏幕try {Thread.sleep(2);//画完之后睡一会再循环} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}.start();}}这里我需要提醒一下,ball类里面对于小球方向的控制判定,我是可以按照不同的定义。

弹球小游戏编程教程

弹球小游戏编程教程

弹球小游戏编程教程弹球小游戏是一种经典的游戏类型,很受玩家的喜爱。

本篇文章将为大家介绍如何使用编程语言来设计和实现一个简单的弹球小游戏。

本教程适用于初学者,通过学习本文,您可以了解到游戏的基本原理和编程技巧。

1. 游戏设计思路在介绍编程过程之前,我们先来讨论一下游戏设计的思路。

弹球小游戏主要包含以下几个主要元素:- 球:游戏主角,需要设置其初始位置、大小、颜色等属性。

- 挡板:用于控制球的运动,通常由玩家控制。

- 砖块:球需要与之碰撞,以此来消除砖块并得分。

- 分数系统:记录玩家的得分情况。

基于以上元素,我们可以将游戏流程分解为以下几个步骤:- 初始化画布和游戏元素。

- 处理玩家的输入以移动挡板。

- 让球运动并检测碰撞。

- 根据碰撞结果更新游戏状态。

- 循环执行以上步骤,直到游戏结束。

2. 编程环境设置在开始编写代码之前,我们需要准备一个编程环境。

我们可以使用各种编程语言来实现弹球小游戏,如Python、JavaScript等。

下面以Python为例,介绍如何进行环境设置:- 安装Python编程语言的解释器,你可以从Python官方网站上下载并安装最新版本的Python。

- 安装一个代码编辑器,比如Visual Studio Code、PyCharm等,用于编写和调试代码。

你也可以使用自己熟悉的文本编辑器。

安装完成后,就可以开始编写代码了。

3. 代码实现接下来,我们将使用Python语言来实现弹球小游戏。

首先,我们需要导入游戏所需要的库和模块:```pythonimport pygamefrom pygame.locals import *```然后,设置一些基本的游戏参数:```python# 游戏窗口大小screen_width = 800screen_height = 600# 球的初始位置和速度ball_x = 200ball_y = 200ball_dx = 2ball_dy = 2# 挡板的位置和速度paddle_x = 300paddle_y = 550paddle_dx = 0# 砖块的位置和状态bricks = []brick_width = 75brick_height = 20brick_count = 10# 初始化游戏pygame.init()screen = pygame.display.set_mode((screen_width, screen_height))pygame.display.set_caption("弹球小游戏")```然后,我们定义一些函数来处理游戏的逻辑:```pythondef draw_ball(x, y):pygame.draw.circle(screen, (255, 0, 0), (x, y), 10) def draw_paddle(x, y):pygame.draw.rect(screen, (0, 255, 0), (x, y, 100, 10)) def draw_bricks():for brick in bricks:pygame.draw.rect(screen, (0, 0, 255), brick)def check_collision():global ball_dx, ball_dy, brick_countif ball_x < 0 or ball_x > screen_width:ball_dx = -ball_dxif ball_y < 0 or ball_y > paddle_y:ball_dy = -ball_dyfor brick in bricks:if brick.collidepoint(ball_x, ball_y):bricks.remove(brick)ball_dy = -ball_dybrick_count -= 1def update_game():global ball_x, ball_y, paddle_x, paddle_y, paddle_dx, brick_count ball_x += ball_dxball_y += ball_dypaddle_x += paddle_dxif paddle_x < 0:paddle_x = 0if paddle_x > screen_width - 100:paddle_x = screen_width - 100if brick_count == 0:pygame.quit()exit()def render_game():screen.fill((0, 0, 0))draw_ball(ball_x, ball_y)draw_paddle(paddle_x, paddle_y)draw_bricks()pygame.display.flip()```最后,我们编写一个游戏主循环来处理用户的输入和更新游戏状态:```pythonwhile True:for event in pygame.event.get():if event.type == QUIT:pygame.quit()exit()if event.type == KEYDOWN:if event.key == K_LEFT:paddle_dx = -2elif event.key == K_RIGHT:paddle_dx = 2if event.type == KEYUP:if event.key == K_LEFT or event.key == K_RIGHT:paddle_dx = 0update_game()check_collision()render_game()```4. 运行游戏编写完成后,保存文件并执行代码,就可以开始游戏了。

Java程序设计实验报告2(弹球游戏)参考模板

Java程序设计实验报告2(弹球游戏)参考模板

《Java语言程序设计》课程设计实习报告题目:班级:学号:姓名:同组人员:指导老师:张彬一、实验目的1、掌握Swing图形用户界面编程以及事件处理等,掌握java绘图技术。

2、掌握多线程编程的基本原理,能使用Runnable、ExecutorService等接口进行线程的创建、启动等工作。

3、培养独立查找资料,并解决问题的能力。

二、实验任务1、设计并编程实现弹球游戏:用户能通过GUI组件指定生成小球的数量,每个小球将从随机的位置出现,并具有随机颜色,随机速度以及随机的运动方向,小球沿初始方向匀速运动,当碰到窗口边缘时,小球将依据受力原理改变运动方向(可简化考虑,受力只改变小球的运动方向,小球仍按照初始速度匀速运动,且不考虑小球之间的碰撞)。

鼠标在界面中显示为方块状,玩家需按住鼠标来回移动以避开运动的小球及屏幕四周,如果鼠标碰到任一小球或者窗口四周,则游戏结束。

程序需提供计时功能,并最终显示玩家能坚持多少秒。

2、程序要求:(1)具备相应界面,并通过事件编程,实现相应的GUI组件功能。

(2)使用多线程技术,在程序窗口区域绘制小球,并以线程控制小球的移动,实现动画效果。

(3)实现鼠标与屏幕四周,以及与小球的碰撞检测。

三、开发工具与平台1.开发工具:Eclipse默认是一个和Jbuilder类似的Java开发工具,但它不仅仅只是Java开发工具,只要装上相应的插件,eclipse也可作为其它语言的开发工具。

如C/C++插件(CDT)。

2.开发平台:JDK1.5四、设计思路1.界面设计(1)制作一个简单的面板JFrame,文件保存为bollFrame.java其中为一public的类bollFrame,其构造方法为:bollFrame(int n){super();setTitle("我的弹球小游戏");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();//得到电脑屏幕大小setSize(450,450);setLocation((dimension.width-game.getWidth())/2-250,(dimension.height-game.getHeight())/2-250);//设置面板显示基中;this.n = n;myBollPanel = new bollPanel(n);//构造一个画板;add(myBollPanel);//将画板放入JFramecreateMenu();//创建菜单;setJMenuBar(bar);}(2)构造画板类,文件保存为bollPanel.java其构造函数如下:bollPanel(int n){this.n = n;// executorThread = Executors.newCachedThreadPool();//创建线程池;mouse = new mouseThread(mxNow,myNow,groupThread,this);//启动鼠标线程;this.setIsOver(false);//游戏开始线程条件的判断;for(int i =0 ;i<n;++i){myBollThread =new bollThread(this);groupThread.add(myBollThread);//executorThread.execute(myBollThread);//小球线程加入线程池;}addMouseListener(this);addMouseMotionListener(this);}Paint()方法如下构造:public void paint(Graphics g){if(!this.getIsOver()) //如果游戏还没结束;{super.paint(g);//清除原先的图像g.setColor(Color.RED);g.setFont(new Font("宋体",Font.BOLD+Font.ITALIC,15));g.drawString("你已坚持:"+getT()+"S", 15, 15);//计时器的显示;for(int i = 0;i<n;++i){//画出每个线程球int xNow =groupThread.get(i).getxNow();int yNow = groupThread.get(i).getyNow();g.setColor(groupThread.get(i).getColor());g.fillOval(xNow,yNow,30,30);if(xNow>(getWidth()-23)||xNow<0){//碰到左右边界;groupThread.get(i).dx = -groupThread.get(i).dx;}if(yNow>(getHeight()-23)||yNow<0){//碰到上下边界;groupThread.get(i).dy = -groupThread.get(i).dy;}groupThread.get(i).setxNow(xNow+groupThread.get(i).getdx());// 设置下一个位置;groupThread.get(i).setyNow(yNow+groupThread.get(i).getdy());}}if(isMouse){g.drawImage(new ImageIcon("boll.gif").getImage(), mxNow, myNow, 40,40, this);//鼠标的图像;}}//end paint();总体界面如下:2.逻辑设计(1).首先,我们考虑到多个小球的运动,实质上是多线程的使用,n个小球我们就同时启动n个线程去控制每个小球的运动。

小球碰撞实验

小球碰撞实验

撞检测实验在屏幕上的随机位置上出现小球,完成弹球的功能,与四周进行碰撞检测,代码如下:1.import javax.microedition.lcdui.Canvas;import mand;import mandListener;import javax.microedition.lcdui.Displayable;import javax.microedition.lcdui.Graphics;public class LuckyBollCanvas extends Canvas{private int x;//球的x坐标private int y;//球的y坐标private int offx, offy;//球跳跃的步长public boolean pause;//控制是否结束public LuckyBollCanvas(){offx = offy = 10;x = (this.getWidth() + offx) / 2;y = (this.getHeight() + offy) / 2;pause = false;this.addCommand(new Command("Start ", Command.OK, 1));this.addCommand(new Command("Stop ", Command.BACK, 1));this.setCommandListener(new CanvasCommand());}protected void paint(Graphics arg0) { //刷新画板arg0.setColor(255, 255, 255);arg0.fillRect(0, 0, this.getWidth(), this.getHeight());//画球arg0.setColor(0, 0, 0);arg0.fillArc(x, y, 10, 10, 0, 360);}//线程内部类class LuckyBollThread implements Runnable{public LuckyBollThread() {super();new Thread(this).start()}public void run(){while (pause){x += offx;y += offy;if (x < 0){offx = 10;x = 0;} else if (x > getWidth() - offx) {x = getWidth() - offx;offx = -10;}if (y < 0) {offy = 10;y = 0;} else if (y > getHeight() - offy) {y = getHeight() - offy;offy = -10;}repaint();serviceRepaints();try{Thread.sleep(1000);} catch (InterruptedException e){e.printStackTrace();}}}}//Command内部类class CanvasCommand implements CommandListener{public void commandAction(Command arg0, Displayable arg1 { switch (arg0.getCommandType()){case Command.OK:System.out.println("oo");//测试pause = true;LuckyBollThread t = new LuckyBollThread();break;case Command.BACK:pause = false;System.out.println("ll");//测试break;}}}}2.import javax.microedition.lcdui.*;import javax.microedition.lcdui.Display;import javax.microedition.midlet.MIDlet;public class Midlet extends MIDlet{Display display;LuckyBollCanvas lbc;public void startApp(){this.display = Display.getDisplay(this);this.lbc = new LuckyBollCanvas();this.display.setCurrent(lbc);}public void pauseApp(){}public void destroyApp(boolean unconditional) {}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Java窗口程序小球碰撞准备工作:首先确定自身机器应装有jdk,如果没有请到这个官方网站/technetwork/indexes/downloads/index.html#java上下载。

小球程序的基本架构组成:1、对象小球2、窗口主程序3、小球运动程序注意:你看到的小球运动其实就是视觉的欺骗,因为屏幕的刷新速度和重绘速度造成的错觉让人觉得是在运动。

因此程序的运动其实就是图像的重新绘制和生成。

以下是编制的小球程序:首先是小球这个对象的java程序Ball.javaimport java.awt.Color;import java.awt.Graphics;public class Ball {/*** 球的八个方向*/public final static int LEFT_UP=0;public final static int LEFT_DOWN=1;public final static int RIGHT_UP=2;public final static int RIGHT_DOWN=3;public final static int UP=4;public final static int DOWN=5;public final static int RIGHT=6;public final static int LEFT=7;/*** 球的5个属性*/private int x,y;private int r;private Color color;private int oraintation;//小球的方向public Ball(int r,int x,int y,Color color,int oraintation){this.r=r;this.x=x;this.y=y;this.color=color;this.oraintation=oraintation;}public void draw(Graphics g){g.setColor(color);g.fillArc(x-r, y-r, r/2, r/2, 0,360);}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public int getR() {return r;}public void setR(int r) {this.r = r;}public Color getColor() {return color;}public void setColor(Color color) {this.color = color;}public int getOraintation() {return oraintation;}public void setOraintation(int oraintation) {this.oraintation = oraintation;}}然后是主程序BallMovingFrame.javaimport javax.swing.JFrame;public class BallMovingFrame extends JFrame{public static void main(String args[]){BallMovingPanel panel= new BallMovingPanel();BallMovingFrame b =new BallMovingFrame();b.setSize(640, 480);b.setVisible(true);b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);b.setTitle("ball");b.add(panel);panel.startRun();}}最后是绘制小球的程序BallMovingPanel.javaimport java.awt.Color;import java.awt.Graphics;import java.util.Random;import javax.swing.JPanel;public class BallMovingPanel extends JPanel{private Ball[] allBall;private Color[] color;private Ball ball;public BallMovingPanel(){allBall=new Ball[10];color=new Color[10];color[0]=Color.BLACK;color[1]=Color.BLUE;color[2]=Color.CYAN;color[3]=Color.GRAY;color[4]=Color.RED;color[5]=Color.green;color[6]=Color.YELLOW;color[7]=Color.magenta;color[8]=Color.ORANGE;color[9]=Color.LIGHT_GRAY;Random ran=new Random();for(int i=0;i<allBall.length;i++){ball=new Ball(40+2*i,ran.nextInt(600),ran.nextInt(424),color[ran.nextInt(100)%10],ran.nextInt(100)%8);allBall[i]=ball;}}public void paint(Graphics g){super.paint(g);for(int i=0;i<allBall.length;i++){allBall[i].draw(g);//调用小球类里的绘画方法}}public void startRun(){new Thread(){public void run(){while(true){for(int j=0;j<10;j++){for(int i=0;i<10;i++){//int r = allBall[i].getR();int f = allBall[i].getOraintation();int m = allBall[i].getX();int n = allBall[i].getY();if(f==ball.LEFT_UP){m--;n--;if(m<35){f = ball.RIGHT_UP;}if(n<35){f = ball.LEFT_DOWN;}}else if(f==ball.LEFT_DOWN){m--;n++;f = ball.RIGHT_DOWN;}if(n>450){f = ball.LEFT_UP;}}else if(f==ball.RIGHT_UP){m++;n--;if(m>640-35){f = ball.LEFT_UP;}if(n<35){f = ball.RIGHT_DOWN;}}else if(f==ball.RIGHT_DOWN){ m++;n++;if(m>640-60){f = ball.LEFT_DOWN;}if(n>480-60){f = ball.RIGHT_UP;}}else if(f==ball.UP){n--;if(n<35){f = ball.DOWN;}}else if(f==ball.DOWN){n++;if(n>480-40){f = ball.UP;}}else if(f==ball.LEFT){m--;if(m<35){f = ball.RIGHT;}}else if(f==ball.RIGHT){m++;if(m>640-40){f = ball.LEFT;}}allBall[i].setOraintation(f);allBall[i].setY(n);}}try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}repaint();}}}.start();}}上面程序编制完后,我们可以更加一层楼的去提升一步,只需点击一个批处理文件就可以让其运行了。

首先确定你是windows系统,然后创建小球.txt 文件然后在文件中输入javac Ball.javajavac BallMovingPanel.javajavac BallMovingFrame.javajava BallMovingFrame完成后报文文件。

最后将小球.txt 文件修改成小球.bat 文件。

完成后,就可以点击此文件进行运行了。

注意:这4个文件必须在同一文件夹下,否则会报错。

相关文档
最新文档