<< 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 is variations in raman spectra for nanomaterials
Jyoti Reply
I only see partial conversation and what's the question here!
Crow Reply
what about nanotechnology for water purification
RAW Reply
please someone correct me if I'm wrong but I think one can use nanoparticles, specially silver nanoparticles for water treatment.
Damian
yes that's correct
Professor
I think
Professor
what is the stm
Brian Reply
is there industrial application of fullrenes. What is the method to prepare fullrene on large scale.?
Rafiq
industrial application...? mmm I think on the medical side as drug carrier, but you should go deeper on your research, I may be wrong
Damian
How we are making nano material?
LITNING Reply
what is a peer
LITNING Reply
What is meant by 'nano scale'?
LITNING Reply
What is STMs full form?
LITNING
scanning tunneling microscope
Sahil
how nano science is used for hydrophobicity
Santosh
Do u think that Graphene and Fullrene fiber can be used to make Air Plane body structure the lightest and strongest. Rafiq
Rafiq
what is differents between GO and RGO?
Mahi
what is simplest way to understand the applications of nano robots used to detect the cancer affected cell of human body.? How this robot is carried to required site of body cell.? what will be the carrier material and how can be detected that correct delivery of drug is done Rafiq
Rafiq
what is Nano technology ?
Bob Reply
write examples of Nano molecule?
Bob
The nanotechnology is as new science, to scale nanometric
brayan
nanotechnology is the study, desing, synthesis, manipulation and application of materials and functional systems through control of matter at nanoscale
Damian
Is there any normative that regulates the use of silver nanoparticles?
Damian Reply
what king of growth are you checking .?
Renato
What fields keep nano created devices from performing or assimulating ? Magnetic fields ? Are do they assimilate ?
Stoney Reply
why we need to study biomolecules, molecular biology in nanotechnology?
Adin Reply
?
Kyle
yes I'm doing my masters in nanotechnology, we are being studying all these domains as well..
Adin
why?
Adin
what school?
Kyle
biomolecules are e building blocks of every organics and inorganic materials.
Joe
anyone know any internet site where one can find nanotechnology papers?
Damian Reply
research.net
kanaga
sciencedirect big data base
Ernesto
Introduction about quantum dots in nanotechnology
Praveena Reply
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 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!
Jobilize.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