<< Chapter < Page Chapter >> Page >

Listing 10 also signals the end of the Slick0210 class and the end of the program.

Run the program

I encourage you to copy the code from Listing 11 and Listing 12 . Compile the code and execute it,making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.

Summary

In this module, you learned how to use the Sprite01 class from an earlier module to write a predator/prey simulation program involvingthousands of sprites, collision detection, and sound effects.

What's next?

In the next module, you will learn how to write a program that simulates the spread of a fatal communicable disease within a population.

Miscellaneous

This section contains a variety of miscellaneous information.

Housekeeping material
  • Module name: Slick0210: Collision detection and sound
  • File: Slick0210.htm
  • Published: 02/06/13
  • Revised: 10/03/15
Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for thismodule at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should beaware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. Ineither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please beaware that it is a copy of a module that is freely available on cnx.org and that it was made and published withoutmy prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.

Complete program listings

Complete listings of the code discussed in this module are provided in Listing 11 and Listing 12 .

Listing 11 . Source code for the program named Slick0210.
/*Slick0210.java Copyright 2013, R.G.BaldwinA baseball coach is attacked by a swarm of fierce green flying insects. Fortunately, a red predator insect comesalong and attacks the green insects just in time to save the coach.There are two scenarios that can be exercised by setting dieOnCollision to true or false. In one scenario,the green insects become harmless blue insects when they collide with the red insect. In the other case, they areconsumed by the red insect upon contact and removed from the population.In both scenarios, contact between a green insect and the red insect causes the red insect to increase in size.If you allow the program to run long enough, the probability is high that all of the green insects willhave collided with the red insect and will either have turned blue or have been consumed.Tested using JDK 1.7 under WinXP *********************************************************/import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame;import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics;import org.newdawn.slick.Image; import org.newdawn.slick.SlickException;import org.newdawn.slick.Color; import org.newdawn.slick.Sound;import java.util.Random; import java.util.ArrayList;import java.util.Iterator; public class Slick0210 extends BasicGame{//Set the value of this variable to true to cause the// sprites to die on collision and to be removed from // the population.boolean dieOnCollision = true;//Store references to Sprite01 objects here. ArrayList<Sprite01>sprites = new ArrayList<Sprite01>();//Change this value and recompile to change the number // of sprites.int numberSprites = 1000; //Populate these variables with references to Image// objects later. Image redBallImage;Image greenBallImage; Image blueBallImage;//Populate this variable with a reference to a Sound// object later. Sound blaster;//Populate these variables with information about the// background image later. Image background = null;float backgroundWidth; float backgroundHeight;//This object is used to produce values for a variety// of purposes. Random random = new Random();//Frame rate we would like to see and maximum frame// rate we will allow. int targetFPS = 60;//----------------------------------------------------// public Slick0210(){//constructor//Set the title super("Slick0210, baldwin");}//end constructor //----------------------------------------------------//public static void main(String[] args)throws SlickException{ AppGameContainer app = new AppGameContainer(new Slick0210(),414,307,false); app.start();}//end main //----------------------------------------------------//@Override public void init(GameContainer gc)throws SlickException { //Create Image objects that will be used to visually// represent the sprites. redBallImage = new Image("redball.png");greenBallImage = new Image("greenball.png"); blueBallImage = new Image("blueball.png");//Create a Sound object.blaster = new Sound("blaster.wav"); //Create a background image and save information// about it. background = new Image("background.jpg");backgroundWidth = background.getWidth(); backgroundHeight = background.getHeight();//Add a sprite dressed with redBallImage to the// beginning of the ArrayList object. Put it in the // center of the game window. Make the direction of// motion random. Make the speed of motion // (step size)random. Make the size random. Specify// a white (do nothing)color filter. sprites.add(new Sprite01(redBallImage,//image backgroundWidth/2.0f,//initial positionbackgroundHeight/2.0f,//initial position (random.nextFloat()>0.5) ? 1f : -1f,//direction (random.nextFloat()>0.5) ? 1f : -1f,//direction 0.1f+random.nextFloat()*2.0f,//step size0.1f+random.nextFloat()*2.0f,//step size 0.5f+random.nextFloat()*1.5f,//scalenew Color(1.0f,1.0f,1.0f)));//color filter //Populate the ArrayList object with sprites. Dress// them with a greenBallImage. Make the initial // position random. Make the initial direction of// motion random. Make the speed (step size) random. // Make the size (scale) random. Make the color filter// white (do nothing). for(int cnt = 0;cnt<numberSprites;cnt++){ sprites.add(new Sprite01(greenBallImage,//image backgroundWidth*random.nextFloat(),//positionbackgroundHeight*random.nextFloat(),//position (random.nextFloat()>0.5) ? 1f : -1f,//direction (random.nextFloat()>0.5) ? 1f : -1f,//direction 0.1f+random.nextFloat()*2.0f,//step size0.1f+random.nextFloat()*2.0f,//step size random.nextFloat()*1.0f,//scalenew Color(1.0f,1.0f,1.0f)));//color filter }//end for loopgc.setTargetFrameRate(targetFPS);//set frame rate }//end init//----------------------------------------------------// @Overridepublic void update(GameContainer gc, int delta) throws SlickException{//Access to the first sprite in the ArrayList object. Sprite01 redBallSprite = sprites.get(0);//Do the following for every sprite in the ArrayList // objectfor(int cnt = 0;cnt<sprites.size();cnt++){ //Get a reference to the Sprite01 object.Sprite01 thisSprite = sprites.get(cnt);//Ask the sprite to move according to its properties thisSprite.move();//Ask the sprite to bounce off the edge if it is at // an edge.thisSprite.edgeBounce( backgroundWidth,backgroundHeight);//Test for a collision between this sprite and the// sprite that is dressed in the redBallImage. boolean collision =thisSprite.isCollision(redBallSprite); //Process a collision if it has occurred. Exclude// collisions between the redBallSprite and itself. // Also exclude collisions between sprites dressed// in a blueBallImage and the redBallSprite. if((collision == true)&&(! thisSprite.getImage().equals(redBallImage))&&(! thisSprite.getImage().equals(blueBallImage))){ //A collision has occurred, change the color of// this sprite to blue and maybe cause it to // die and be removed from the population.thisSprite.setImage(blueBallImage); if(dieOnCollision){thisSprite.setLife(0); }//end if//Cause the redBallSprite to change direction on// a random basis. redBallSprite.setXDirection((random.nextFloat()>0.5) ? 1f : -1f); redBallSprite.setYDirection((random.nextFloat()>0.5) ? 1f : -1f);//Cause the redBallSprite to change stepsize on a // random basis.redBallSprite.xStep = 0.1f+random.nextFloat()*2.0f;redBallSprite.yStep = 0.1f+random.nextFloat()*2.0f;//Cause the redBallSprite to grow largerredBallSprite.setScale(redBallSprite.getScale() +(redBallSprite.getScale()) * 0.001f); //Play a sound to indicate that a collision has// occurred. blaster.play();}//end if }//end for loop//Remove dead objects from the ArrayList objectIterator<Sprite01>iter = sprites.iterator(); while(iter.hasNext()){Sprite01 theSprite = iter.next(); if(theSprite.getLife()<= 0){ iter.remove();}//end if }//end while loop}//end update //----------------------------------------------------//public void render(GameContainer gc, Graphics g) throws SlickException{//set the drawing mode to honor transparent pixels g.setDrawMode(g.MODE_NORMAL);//Draw the background to erase the previous picture. background.draw(0,0);//Draw every sprite in the ArrayList object. for(int cnt = 0;cnt<sprites.size();cnt++){ sprites.get(cnt).draw();}//end for loop//Display the remaining number of sprites. g.drawString("Sprites remaining: " + (sprites.size()),100f,10f); //Signal when all sprites have been eaten.if(sprites.size() == 1){ g.drawString("Burp!",100f,25f);}//end if }//end render}//end class Slick0210 //======================================================//

Questions & Answers

what does nano mean?
Anassong Reply
nano basically means 10^(-9). nanometer is a unit to measure length.
Bharti
do you think it's worthwhile in the long term to study the effects and possibilities of nanotechnology on viral treatment?
Damian Reply
absolutely yes
Daniel
how to know photocatalytic properties of tio2 nanoparticles...what to do now
Akash Reply
it is a goid question and i want to know the answer as well
Maciej
characteristics of micro business
Abigail
for teaching engĺish at school how nano technology help us
Anassong
Do somebody tell me a best nano engineering book for beginners?
s. Reply
what is fullerene does it is used to make bukky balls
Devang Reply
are you nano engineer ?
s.
fullerene is a bucky ball aka Carbon 60 molecule. It was name by the architect Fuller. He design the geodesic dome. it resembles a soccer ball.
Tarell
what is the actual application of fullerenes nowadays?
Damian
That is a great question Damian. best way to answer that question is to Google it. there are hundreds of applications for buck minister fullerenes, from medical to aerospace. you can also find plenty of research papers that will give you great detail on the potential applications of fullerenes.
Tarell
what is the Synthesis, properties,and applications of carbon nano chemistry
Abhijith Reply
Mostly, they use nano carbon for electronics and for materials to be strengthened.
Virgil
is Bucky paper clear?
CYNTHIA
so some one know about replacing silicon atom with phosphorous in semiconductors device?
s. Reply
Yeah, it is a pain to say the least. You basically have to heat the substarte up to around 1000 degrees celcius then pass phosphene gas over top of it, which is explosive and toxic by the way, under very low pressure.
Harper
Do you know which machine is used to that process?
s.
how to fabricate graphene ink ?
SUYASH Reply
for screen printed electrodes ?
SUYASH
What is lattice structure?
s. Reply
of graphene you mean?
Ebrahim
or in general
Ebrahim
in general
s.
Graphene has a hexagonal structure
tahir
On having this app for quite a bit time, Haven't realised there's a chat room in it.
Cied
what is biological synthesis of nanoparticles
Sanket Reply
what's the easiest and fastest way to the synthesize AgNP?
Damian Reply
China
Cied
types of nano material
abeetha Reply
I start with an easy one. carbon nanotubes woven into a long filament like a string
Porter
many many of nanotubes
Porter
what is the k.e before it land
Yasmin
what is the function of carbon nanotubes?
Cesar
I'm interested in nanotube
Uday
what is nanomaterials​ and their applications of sensors.
Ramkumar Reply
what is nano technology
Sravani Reply
what is system testing?
AMJAD
preparation of nanomaterial
Victor Reply
how did you get the value of 2000N.What calculations are needed to arrive at it
Smarajit Reply
Privacy Information Security Software Version 1.1a
Good
Got questions? Join the online conversation and get instant answers!
QuizOver.com Reply

Get the best Algebra and trigonometry course in your pocket!





Source:  OpenStax, Anatomy of a game engine. OpenStax CNX. Feb 07, 2013 Download for free at https://legacy.cnx.org/content/col11489/1.13
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Anatomy of a game engine' conversation and receive update notifications?

Ask