SlideShare uma empresa Scribd logo
1 de 43
A Group Project Report on

                            ROAD ATTACK

                                   Submitted to
           The Department of Electronics and Computer Engineering
             In partial fulfillment of the academic requirements of
                                      SNIST
                                        For
                            The award of the degree of

                            Bachelor of Technology
                                      In
                     Electronic and Computer Engineering
                                 (2010 – 2014)


                                    By
                      T samba siva rao 11315A1919
                      B sandeep kumar 11315A1921
                      P rakesh kumar 11315A1922
                           Under the Guidance of
                               Shayam babu




               Sreenidhi Institute of Science and Technology
                            (AUTONOMOUS)
           Yamnampet, Ghatkesar, R.R. District, Hyderabad - 501301
Department of ElectronicsAnd Computer Engineering
               Sreenidhi Institute of Science and Technology




                               CERTIFICATE


      This     is     to     certify    that     this    project     report     on
“EXTREME RACING”, submitted by T.sambasiva(11315A1919), B.sandeep
(11315A1921),P.rakesh(11315A1922) in the year 2012 in partial fulfillment of the
academic requirements of Sreenidhi Institute of Science and Technology for the
award of the degree of Bachelor of Technology inElectronics and Computer
Engineering, is a bonafide work that has been carried out by them as part of their
Group Project during Third Year First Semester, under our guidance. This
report has not been submitted to any other institute or university for the award of
any degree.




M.Shyam babu           K.SASIDHAR
Assistant Professor
Department of ECMHOD
 Internal Guide     Department of ECM
ACKNOWLEDGEMENT

       This project report is the outcome of the efforts of many people, who have driven my
passion to explore into Java. We have received great guidance, encouragement and support from
them and have learned a lot because of their willingness to share their knowledge and
experience.
       Primarily, we should express our deepest sense of gratitude to our internal guide
Mr.M.shyam babu, Assistant Professor, Department of ECM. His guidance has been of immense
help in surmounting various hurdles along the path of our goal.
       We are deeply indebted to Mrs. Sasidhar .K, Head, and Department of ECM, who spared
her most valuable time without any hesitation whenever we wanted.
       We record with a great feeling of gratitude, the contributions of all the faculty members,
who encouraged us during this project by rendering their help when needed.
       Finally we thank our parents and adore Almighty God who has made us come in contact
with such worthy people at the right time, provided us with all the necessary resources and made
us accomplish this task.




                                                                   T. samba siva
                                                                  P.rakesh kumar
B. sandeep kumar
INDEX



Abstract                                 i

List of Figures                          ii

1.INTRODUCTION                       1

 1.1 Project Specification                   2


2.SYSTEM DESIGN                      4

 2.1 Modules                              4


3.SYSTEM IMPLEMENTATION                  07

4.TEST                                   20

5. CONCLUSION                            37

6.REFERENCE                                  38
ABSTRACT




       The main objective of this project is to develop a Java based personal computer game.
Basically it‟s a car racing game in which user‟s car has to reach the destination in the given time
by avoiding the obstacles. If user completes one level successfully, he will be forwarded to next
level with increased complexity.


       User can change his car, save his score and enable or disable back ground sounds. User
can use special features like Health, Time and Speed booster in reaching the destination.




                                                1
1. INTRODUCTION
About Game:

Extreme Racing is a JAVA based PC game where the user‟s car has to reach the destination
within a given time avoiding the Obstacles.There will be maximum ten levels. User has to cross
ten levels to win the game. User will be provided with 4 lives to complete the game. In addition,
he can use additional features like weapons to fire the enemies and special features like boosters
to reach the destination.




JAVA:


Java is a Programming Language and computing platform first released by Sun Microsystems in
1995.It is the underlying technology that powers state-of-art technology including utilities,games
and applications.




It was started in 1991 as a project named “Green”, to develop a platform-independent language
that can be used to create software to be embedded in various consumer electronic devices, such
as microwave ovens and remote controls etc.


    Java runs inside a piece of software known as a Java Virtual Machine.
    In many languages, such as C and C++, the source code (.c and .cpp files) is portable.
       What makes Java unique is that Java‟s executable code is also portable (.class files).
    This means that the same application can be run without modification on any system that
       has a Java Virtual Machine without being recompiled.

                                                2
1.1 Project Specifications:


Software Requirements:


   1. Java SE 1.6
   2. Any OS that supports java


Hardware Requirements:



A personal computer with
   1. Processor – PIV or above
   2. RAM – Minimum of 512




                                  3
2. System Design

2.1 Modules


There are 5 Panels in this project. They are


1. Start Screen
2. Game Panel
3. Options
4.High Scores
5.Help Panel




                                               4
2.2.1 Use case Diagram:




                          Figure 2.1 : Use case Diagram




                                       5
2.2.2 Class Diagram:




                       Figure 2.2 : Class Diagram




                                   6
2.2.3 Sequence Diagram:




                          Figure 2.3:Sequence Diagram

                                      7
2.2.4 Collaboration Diagram:




                       Figure 2.4: Collaboration diagram




                                      8
2.1.1 START SCREEN:


Start Screen is the interface between the user and the game. It allows the user to select the
options of his own.It is the first screen that appears when a user opens the game.It provides user
interface components to start the game, to view the high scores, to exit from the application,
game options etc.Depending on the user input in this screen, user will be taken further in to the
game.


Start screen includes features like
        Start game:Takes user in to the Game
        Options     :Gives Options like Select Car and background music
        High Score : Displays the High Scores of the previous users
        Help        : Shows the game controls and special features.
        Exit        : Exit the game.




2.1.2 Game Panel

When the user clicks on start game button in start screen, he will be brought to this screen. This
is the Panel where the user plays the game. This panel contains some components on either sides
to display information about the game.


Components that appear on Game Panel:


        Score – displays the score of the user
        Level – Shows the current level.
        Lives – Shows number of lives left
        Time – Shows time left to reach the destination.




                                                 9
2.1.3Options Panel


This is the panel where the user can select options of his choice. This panel allows the user to
select car and change the sounds on/off.


Components that appear on Option Panel:


       Select Car-Allows user to select the car.
       Sound-Allows the users to set sounds on/off.




2.1.4 High Scores


This panel displays the High Scores to the User. When the user finishes the game he will
prompted to enter user‟s name to stores his score.




This window can be focused in two ways:
       When the User click on High Scores button on Start Screen.
       When the user finished the game, he will be directed to High Scores Panel.
2.1.5 Help Panel


This panel displays help information for user.


Help Screen include:


       Direction Keys-It tells the keys to be used in directing the car
       Special Features-It tells about special features in the game like Bullets, Pause,
       MainMenu, Boosters.

                                                 10
3. System Implementation

3.1 Game Window:

This class extends JFrame. JFrame creates a window. This is the only window in the project. All
the panels in the game are added to this window and switched according to the user input.
Creation of multiple objects is avoided by using the concept „singleton object‟. Card layout is
used to set the layout of the main frame. Panels are switched based upon the user input.


Sample code for creating singleton object:

publicstaticGamePanelgetGamePanel()
       {
             if(gamepanel == null)
                    gamepanel = newGamePanel();
             returngamepanel;
       }



3.2 Start Screen:
This class extends a Jpanel. Jpanel is a plain surface that can be added to frames. An object for
this screen is created and added to the main frame (Game window). This panel contains 5 buttons
start game, options, high score, help, exit. When user clicks on a specific button we switch the
panel in the cardlayout (maincardlayout). Several images will be displayed in this screen.
Following is the sample code for loading images into the project.

Sample code for creating image:
       ImageIconstarticon =
newImageIcon(this.getClass().getResource("startgame.jpg"));
              startimage = starticon.getImage();

                                                11
getContentPane() method returns the object of the default panel on game window. By using this
method, an object of default panel is created and other panels are added to it.

sample code for adding panel to cardlayout

        startScreen = newStartScreen();
        getContentPane().add(startScreen,"start screen");



Sample code for switching panels

                GameWindow.getGameWindowInstance().changePanel(GameWindow.getContentP
        ane(),”game panel”);




3.3 Game Panel

3.3.1 Timer Class
Creates a Timer and initializes both the initial delay and between-event delay to
delaymilliseconds.   If delay is less than or equal to zero, the timer fires as soon as it is started. If
listener   is not null, it's registered as an action listener on the timer.

Fires one or more action events after a specified delay. For example, an animation object can use
a Timer as the trigger for drawing its frames.

Setting up a timer involves creating a Timer object, registering one or more action listeners on it,
and starting the timer using the start method. For example, the following code creates and
starts a timer that fires an action event once per second (as specified by the first argument to the
Timer   constructor). The second argument to the Timer constructor specifies a listener to receive
the timer's action events.

Sample code

int delay = 10; //milliseconds
Timer timer = new Timer(delay,this);
timer.start();

                                                  12
3.3.2 Paint Method

Invoked by Swing to draw components. This method actually paints all the images in our game.
Applications should not invoke paint directly, but should instead use the repaint method to
schedule the component for redrawing.

Sample code

       publicvoid paint(Graphics g)
       {
              super.paint(g);
              g.drawImage(roadimage, road_x, road_y[0], this);
              g.drawImage(roadimage, road_x, road_y[1], this);
       }

3.3.3 ActionPerformed method

This method many actions in our game such as calculating the score, levels, lives, distance,
changing the position of the road, changing position of the enemy cars, changing positions of the
bullets etc. All these are maintained in different methods. This method gets called every time the
timer object raises the event.

Sample code

public void actionPerformed(ActionEvent e)

{

               accelerate();
               moveRoad();
               moveBullets();
               moveEnemies();
               checkCollision();
}

3.3.4 Moving road
Timer object fires the event for every 10 milli seconds i.e paint method, actionPerformed method
gets called 100 times for every second. The position of the images is changed in actionPerformed
method. Beacause of changing positions of the images and repainting, user gets illusion that the
car is moving. The position of the road is changed in actionperformed method.

                                                13
Sample code for changing position of the road.

road_y[1]+=acceleration;
             if(road_y[1]>=(810-acceleration))
                    road_y[1] = 0;

               road_y[0] = road_y[1]-810;


When the road crosses the position of 810, it‟s position has been changed to 0. An another road
image in road[0] position will always follow the road in road[1] position. So the road images will
be moved in a continuous loop.




3.3.5 Acceleration of user’s car
Acceleration of the user car is maintained by using a variable called acceleration. As long as the
user presses the up arrow key, this variable gets incremented. Acceleration decrement is
constantly maintained by decrementing the acceleration variable when the user does nor presses
the up arrow key.

Sample code of maintaining acceleration
if(upkeypressed){
             if(acceleration<max_acceleration)
             {
                          acceleration++;
             }}




                                                 14
3.3.6 Moving bullets

Two arrays are created to maintain the x and y positions of the bullets. When the user presses the
button „x‟ the positions(x,y) of one bullet is initialized. As long as user presses the x button, the
x,y positions of bullets are initialized. These positions are moved by changing these positions in
actionperformed method. When a bullet crosses the border, it will be initialized to zero. Bullets
are painted in paint method when their positions are not zero.

Sample code

PrivatevoidmoveBullets() {

               for(int i = 0;i<bullet_y.length;i++)
               {
                      if(bullet_y[i] != 0)
                             bullet_y[i]-=10;
                      if(bullet_y[i] < 0)
                             bullet_y[i] = 0;
               }      }


3.3.7 Moving enemies

Enemy car‟s y position is changed every time action performed method gets called. When the
enemy car crosses the border, it‟sy position is initialized to a value less than zero so that it comes
from the starting position again. It‟s x position is relocated by using locateEnemyPosition
method. Enemy car is moved with a value greater than user car‟s acceleration so that if the user
car moves fast, enemy car also moves fast.

Sample code

PublicvoidmoveEnemies()
       {
             enemy_y+=(acceleration+4);
             if(enemy_y>810){
                    enemy_y = -200;locateEnemyPosition();}
       }




                                                  15
3.3.8 Checking collision

Enemy car‟s collision with user car is maintained in the checkcollision method. This method is
called in actionperformed method. Each time enemy car‟s position is changed, it‟s collision with
the user‟s car is checked. If enemy car hits the user car 4 times, a variable called lives is
decremented. When this variable comes to zero, the game is ended and user is prompted to save
his score.

Sample code
publicvoidcheckCollision(){

if((enemy_y+85)>=car_y&&enemy_x>=(car_x-45) &&enemy_x<=(car_x+45)){
                          enemy_y = -200;
                          locateEnemyPosition();
                          energy-=100;
                          if(energy == 0)
                          {
                                 energy = 400;lives--;
                                        lifeover = true;
                                        if(lives == 0)
                                               gameover = true;
                          }
             }
}
3.3.9 Playing Audio

User can enable or disable sounds from the options screen. Audio is played by using the classes
AudioSystem, Clip. Audio files are loaded and played in GamePanel class.

Sample code for loading audio files into the project

publicvoid initAudioFiles()
       {
              try{
                    File file = new File("sound.wav");
       audioIn = AudioSystem.getAudioInputStream(file);

       // Get a sound clip resource.
       mainaudioclip = AudioSystem.getClip();
       audioIn2 = AudioSystem.getAudioInputStream(file2);
       bulletclip = AudioSystem.getClip();
       audioIn3 = AudioSystem.getAudioInputStream(file3);
       explosionclip = AudioSystem.getClip();

       // Open audio clip and load samples from the audio input stream.

                                                  16
mainaudioclip.open(audioIn);
                    // Open an audio input stream.
                    }catch(Exception e){}

       }

Sample code for starting an audio clip

mainaudioclip.start();
mainaudioclip.loop(mainaudioclip.LOOP_CONTINUOUSLY);




3.3.10 Reading User Settings

User settings saved in highscores.txt are read by using the method getUserSettings().

Sample code for reading user settings

publicvoid getUserSettings()
       {
             try{
                    File f;
                      f=new File("settings.txt");
                    if(!f.exists()){
                      f.createNewFile();
                    usercar = "usercar2.jpg";
                    sounds = false;
                    return;
                      }
                    else{
                      FileInputStream fstream = new FileInputStream(f);
                      DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
                      String line;
                      String[] all = new String[3];
                    while((line=br.readLine())!=null)
                      {
                             all = line.split(",");
                      }
                    if(all[0]!=null)
                    usercar = all[0];
                    else
                           usercar = "usercar2.jpg";
                    if(all[1].equals("on"))
                           sounds = true;
                    else
                           sounds = false;
                      }

               }catch (Exception e) {
                      // TODO: handle exception

                                               17
}
       }

3.3.11 Keyboard input

KeyAdapter class is used to take input from the user in this game. Java language rules are such
that we must implement all the methods of an interface even if we can put them into empty
braces i.e we must override all the methods declared in the interface.


But we can create our classes as subclasses of one of the adapter classes then we need to override
only some of the methods we need. An adapter calss provides an empty implementationof all
methods declared in listener concerned interface.


Keypressed(KeyEventke) method is used to identify which key has been pressed.
Ke.getkeycode() method returns the Unicode of the character. When a key is pressed, it will be
checked with getkeycode() method and the corresponding action will be performed.




3.3.12 The KeyEvent Class
IntgetKeyChar( ) which returns the character that was entered, and intgetKeyCode( ) which
returns the key code.


It defines many integer constants:
VK_ENTER VK_ESCAPE VK_CANCEL                         VK_UP
VK_DOWN VK_LEFT               VK_RIGHT       VK_PAGE_DOWN VK_PAGE_UP
VK_SHIFT       VK_ALT         VK_CONTROL




                                                18
3.4 High Scores Screen

User high scores are saved using text file. A text file is created through the code and user‟s high
scores are saved in it. When the user opens the game, the list of high scores are loaded into the
game. Every time, when user completes the game, he is prompted to save his score.
This score is checked with the list of high scores and will be saved if it is better than top 10th
high score in the list.

Sample code for creating new text file
File f;
                  f=newFile("HighScore.txt");
                if(!f.exists()){
                f.createNewFile();
                  }
Sample code for reading file contents.

FileInputStreamfstream = newFileInputStream(f);
             DataInputStream in = newDataInputStream(fstream);
             BufferedReaderbr = newBufferedReader(newInputStreamReader(in));
               String line;
             String[] all = new String[3];


                while((line=br.readLine())!=null)
                  {
                       all = line.split(",");
                       al.add((Object)all);

                   }



Sample code for writing file contents.

fwriter = newFileWriter(f);

                BufferedWriter br2 = newBufferedWriter(fwriter);
                for(int i = 0;i<al.size();i++)
                  {
                       String[] p = (String[])al.get(i);
                       br2.write(p[0]+","+p[1]+","+p[2]+"n");
                  }
                br2.close();




                                                 19
3.5 Options Screen

User‟s setting are also saved in a text file. Buffered reader and buffered writer classes are used to
save settings into the text file. Two settings(usercarimage,sounds) are saved in the file. User
settings are loaded into the game when user opens the game for the first time.


Sample code for saving settings

publicvoidsaveSettings(){
FileWriterfwriter = newFileWriter(f);
             BufferedWriter br2 = newBufferedWriter(fwriter);
             br2.write(selectedcar+","+sound+"n");
             br2.close();
}
Sample code for reading user settings

while((line=br.readLine())!=null)
                           all = line.split(",");
                    selectedcar = all[0] ;
                    sound = all[1];

                       if(selectedcar.equals("usercar1.jpg"))
                              carnum = 1;
                       elseif(selectedcar.equals("usercar2.jpg"))
                              carnum = 2;




3.6 Help Screen

All the help information for the user is painted in the paint method. A user interface component
is placed in the screen for the user to go to the main menu.



Sample code for displaying help information

                                                 20
publicvoid paint(Graphics g) {
             // TODO Auto-generated method stub
             super.paint(g);

             g.setFont(bigfont);
             g.setColor(Color.red);
             g.drawString("Help", 300, 50);
g.setColor(Color.yellow);
             g.setFont(mediumfont);
g.drawString("DIRECTION KEYS", 20, 100);
             g.setFont(smallfont);
             g.setColor(Color.red);
g.drawString("UP ARROW ",20,150);
             g.drawString("DOWNN ARROW ",20,200);
             g.drawString("LEFT ARROW ",20,250);
             g.drawString("RIGHT ARROW ",20,300);
}




Testing:


When the user clicks on any of the buttons available, he will be directed to a new screen. Based
on the user actions, he will be proceeded further in the game.




                                              21
When the user clicks on Start Game button he will be redirected to new window in which the
user can play the game. In this user can find many features like
    1. Level
    2. Score
    3. Time
    4. Lives left
    5. Health
    6. Accelerometer
    7. And a small window showing position of car in the main track.




                                           22
As shown in the figure, Level indicates the current level the user is playing. It shows 1 when the
game is started indicating that the user is in 1st level of the game. When the user completes the
first level, the value of Level tab will become 2.That is each time when the user completes a
level value of level tab will be automatically incremented by 1.There are maximum of ten levels
in the game.

When the user finishes the level, to indicate the end of the level Finish line will be displayed.




                                                 23
When the user finishes all the levels successfully, a message will be displayed congratulating the
winner.


                                               24
Another important feature in this game is the Score tab. When the user starts the game initial
score of the user is zero. As the user proceeds in the game he will be awarded the score
according to the distance he race through. Score will be awarded for the distance he travel. There
is a maximum of 3000 meters track in the game, when the user finishes the level he will have the

                                               25
score of 3000. In addition to the score awarded based on distance he travel, additional scores will
be awarded when the user attacks the opponent cars with the provided bullets. User can fire
bullets by pressing “X” key in key board. Each time user attacks the opponent he will be
awarded the bonus of 100 points. The more user attacks the opponents more he gets bonus and
more score.




As shown in the above figure, Score increased to 8001 and level changed to 2 indicating that the
user is now in 2nd level. Also, the figure shows the bullets released by the user when he is
attacking the opponents. Each time bullet hits theopponent, user gets a bonus of 100 points.
Anytime, user can be redirected to Start Screen by pressing “M” key in the key board.

Time indicates the time left for the user to reach the destination. User will be given a time of 60
seconds to reach the destination. If he failed to do so he will lose the game. If he reaches the
destination within the given 60 seconds he will be promoted to next level.


                                                26
Health of the user is indicated by a special bar at the bottom of the screen. Initially user has full
health. Each time user collides with an obstacle, health will be reduced by 25%. When user
collides with obstacles for 4 times, user‟s car will explode and user will lose one of his lives and
the level will restarted.

As shown in the above figures, Lives of the user are denoted by the special symbol in the
window below the time tab. Each time user‟s health reduced to zero one out of four lives will be
reduced.




When user loses all his four lives he can no longer continue with the game. He will be asked to
save his score in the High Scores window and exit the game.

                                                 27
User will be redirected to High Scores window. In High Scores window a new text field and
button named “ok” will be displayed allowing the user to register his name to save his score.




If the users score stands in top 10 scores it will be displayed in the top scores list with serial
name indicating position he is standing, name of the user and his score.

Name of the user should not include special characters. It should be a plain text. If the user enters
any wrong details he will be prompted with a warning dialog box and will be asked to enter
correct details.




                                                 28
When the user clicks on Main menu button in the High Scores tab he will be redirected to Start
Screen window.

Accelerometer on the right side of the main track indicates the speed at which car is moving. The
maximum speed of the car is 156.

Small track with a small car to the right of the main track indicates the position of the car in the
track. It gives an idea to the user about the distance left to reach the destination so that the user
can speed up or slow down to reach the destination in given time.

During the race when the users proceed special features like health, speed and time booster will
arise along the track. When user takes this booster, respective powers will be activated.
There are 3 types of boosters.
    1. Health
    2. Speed

                                                 29
3. Time




When the user gets the Health Booster, health of the user will be increased to maximum. This
feature helps the user to increase the health when the health is going down. It helps the user in
reaching the destination with less chance of losing the life.




When user gets the Speed booster, speed of the user will be incremented. Initially user has a
maximum speed of 156. But, when the user takes the Speed Booster speed will be increased to
220. This feature helps the user to reach the destination with more speed and thereby saves the
time of the user.



                                               30
This speed added by this feature stands until the end of the level.




                                                 31
When the user gets the Time Booster, it will add additional time of 20 seconds to the user. This
feature helps the user when he is running short of time. So that user can reach the destination
with the help of this additional time.




These 3 boosters Health, Speed and Time will rise randomly in the track.


When the User clicks on Option Button in the Start Screen, he will be redirected to Options
window. In the Option window user can select car of his choice and also user can set sounds On
or Off.



                                              32
In Select car tab, user will be provided with 4 different types of cars. User can select one of the
four cars.

In Sounds tab, user can set the game sounds On/Off with the help of the radio buttons provided

When the user clicks on the Main menu tab in Option window he will be redirected to Start
Screen of the game.




                                                33
After making the required changes user have to save the changes. He can do so by clicking on
save button to save changes. When user clicks on save button, a new dialog will be displayed
prompting the user that the settings are saved.




When the user clicks on Ok button in dialog box he will be redirected to Start Screen Window to
continue with the game. Now the when the user starts the game selected car will be used in the
game and sound changes also will be effective.




                                              34
When user clicks on High Scores button in the Start Screen, he will be redirected to High Scores
window. High Scores window displays logs of high scores recorded in the game.




High Scores window displays the high scores of the users in descending order. That is top scores
stands first in the position of rankings.

High Scores window can display the records of 10 users. When a new record is created it will be
recorded into the log based on the score and least score will be taken out from the high scores
log.




                                              35
When the user clicks on Help button in the Start Screen window, he will be redirected to Help
Window. Help contains information needed for the user to play the game.


Help Contains information about
   1. Direction Keys
   2. Special features.

Direction Keys helps the user in controlling the car.
   1. UP Arrow – Move forward
   2. DOWN Arrow – Apply breaks
   3. Left Arrow – Move left
   4. Right Arrow – Move right




                                                36
Special Features contains information about special buttons and booster icons.

1. X : To fire Bullets
2. P : To pause the game
3. M : To display main menu
And also contains information needed to identify the boosters.

To exit from the game user can click the Exit button in Start Screen window. When the
user clicks on the exit button he will be directed out of the game.




                                       37
5. Conclusion

Practical Training is very important part of the curriculum as it strengthens the concepts and
enhances knowledge about the practical implementation of all theory concepts, we have learnt so
far in different subjects.


In future we can enhance this “Extreme Racing Game” using new technologies because its codes
are so simple that a lay man can understand. Since this is developed in java which is truly object
oriented language it support the future additions and eliminations in the code. We can increase
the flexibility with adding new levels to the game and new items in the appearance of the game.


Although we have completed this project, due to lack of knowledge on a few concepts and
constraint of time, we could not include some more features we wanted to. We left these features
as a part of the future development.




                                               38
6. References

  •      The java Language specification, third edition by James Gosling, Bill Joy, Guy
  Steele, Gilad Bracha.


  •      Introduction to Programming using java, sixth edition by David J Eck


  •      http://www.mybringback.com/tutorials/


  •      http://www.tutorialspoint.com/


  •      http://www.java2s.com/Tutorial/Java/CatalogJava.html




                                          39

Mais conteúdo relacionado

Semelhante a Road attack

FIRST PERSON SHOOTER GAME UNITY 3D
 FIRST PERSON SHOOTER GAME UNITY 3D FIRST PERSON SHOOTER GAME UNITY 3D
FIRST PERSON SHOOTER GAME UNITY 3DRohith GS
 
RO Y1 GD Engine Terminology
RO Y1 GD Engine TerminologyRO Y1 GD Engine Terminology
RO Y1 GD Engine Terminologyrafiqfps
 
Ro y1 gd engine terminology
Ro y1 gd engine terminologyRo y1 gd engine terminology
Ro y1 gd engine terminologyrafiqfps
 
The complete srs documentation of our developed game.
The complete srs documentation of our developed game. The complete srs documentation of our developed game.
The complete srs documentation of our developed game. Isfand yar Khan
 
Car Game - Final Year Project
Car Game - Final Year ProjectCar Game - Final Year Project
Car Game - Final Year ProjectVivek Naskar
 
Car Game Final Year Project
Car Game Final Year ProjectCar Game Final Year Project
Car Game Final Year ProjectBithika Barik
 
ma project
ma projectma project
ma projectAisu
 
Android Beat the-quiz application
Android Beat the-quiz applicationAndroid Beat the-quiz application
Android Beat the-quiz applicationAyush Singh
 
Y1 gd engine_terminology (1)
Y1 gd engine_terminology (1) Y1 gd engine_terminology (1)
Y1 gd engine_terminology (1) TomCrook
 
Android technical quiz app
Android technical quiz appAndroid technical quiz app
Android technical quiz appJagdeep Singh
 
Y1 gd engine_terminology
Y1 gd engine_terminologyY1 gd engine_terminology
Y1 gd engine_terminologyrosstapher
 
Y1 gd engine_terminology (1) (4)
Y1 gd engine_terminology (1) (4) Y1 gd engine_terminology (1) (4)
Y1 gd engine_terminology (1) (4) TomCrook
 
Y1 gd engine_terminology (1)
Y1 gd engine_terminology (1) Y1 gd engine_terminology (1)
Y1 gd engine_terminology (1) TomCrook
 
CG_report_merged (1).pdf
CG_report_merged (1).pdfCG_report_merged (1).pdf
CG_report_merged (1).pdfrahul812082
 
Y1 ig gd engine terminology work
Y1 ig gd engine terminology work Y1 ig gd engine terminology work
Y1 ig gd engine terminology work Jellybabygod
 
Game Engine terminology
Game Engine terminologyGame Engine terminology
Game Engine terminologySamDuxburyGDS
 
Project Report Tron Legacy
Project Report Tron LegacyProject Report Tron Legacy
Project Report Tron LegacyManpreet Singh
 
The Purposes and Functions of components of Game Engines
The Purposes and Functions of components of Game EnginesThe Purposes and Functions of components of Game Engines
The Purposes and Functions of components of Game EnginesPaulinaKucharska
 

Semelhante a Road attack (20)

FIRST PERSON SHOOTER GAME UNITY 3D
 FIRST PERSON SHOOTER GAME UNITY 3D FIRST PERSON SHOOTER GAME UNITY 3D
FIRST PERSON SHOOTER GAME UNITY 3D
 
RO Y1 GD Engine Terminology
RO Y1 GD Engine TerminologyRO Y1 GD Engine Terminology
RO Y1 GD Engine Terminology
 
Ro y1 gd engine terminology
Ro y1 gd engine terminologyRo y1 gd engine terminology
Ro y1 gd engine terminology
 
The complete srs documentation of our developed game.
The complete srs documentation of our developed game. The complete srs documentation of our developed game.
The complete srs documentation of our developed game.
 
Car Game - Final Year Project
Car Game - Final Year ProjectCar Game - Final Year Project
Car Game - Final Year Project
 
Car Game Final Year Project
Car Game Final Year ProjectCar Game Final Year Project
Car Game Final Year Project
 
ma project
ma projectma project
ma project
 
Black book
Black bookBlack book
Black book
 
Android Beat the-quiz application
Android Beat the-quiz applicationAndroid Beat the-quiz application
Android Beat the-quiz application
 
Y1 gd engine_terminology (1)
Y1 gd engine_terminology (1) Y1 gd engine_terminology (1)
Y1 gd engine_terminology (1)
 
Android technical quiz app
Android technical quiz appAndroid technical quiz app
Android technical quiz app
 
Y1 gd engine_terminology
Y1 gd engine_terminologyY1 gd engine_terminology
Y1 gd engine_terminology
 
Y1 gd engine_terminology (1) (4)
Y1 gd engine_terminology (1) (4) Y1 gd engine_terminology (1) (4)
Y1 gd engine_terminology (1) (4)
 
Y1 gd engine_terminology (1)
Y1 gd engine_terminology (1) Y1 gd engine_terminology (1)
Y1 gd engine_terminology (1)
 
Climberreport
ClimberreportClimberreport
Climberreport
 
CG_report_merged (1).pdf
CG_report_merged (1).pdfCG_report_merged (1).pdf
CG_report_merged (1).pdf
 
Y1 ig gd engine terminology work
Y1 ig gd engine terminology work Y1 ig gd engine terminology work
Y1 ig gd engine terminology work
 
Game Engine terminology
Game Engine terminologyGame Engine terminology
Game Engine terminology
 
Project Report Tron Legacy
Project Report Tron LegacyProject Report Tron Legacy
Project Report Tron Legacy
 
The Purposes and Functions of components of Game Engines
The Purposes and Functions of components of Game EnginesThe Purposes and Functions of components of Game Engines
The Purposes and Functions of components of Game Engines
 

Último

Mysore Call Girls 7001305949 WhatsApp Number 24x7 Best Services
Mysore Call Girls 7001305949 WhatsApp Number 24x7 Best ServicesMysore Call Girls 7001305949 WhatsApp Number 24x7 Best Services
Mysore Call Girls 7001305949 WhatsApp Number 24x7 Best Servicesnajka9823
 
Turkiye Vs Georgia Turkey's UEFA Euro 2024 Journey with High Hopes.pdf
Turkiye Vs Georgia Turkey's UEFA Euro 2024 Journey with High Hopes.pdfTurkiye Vs Georgia Turkey's UEFA Euro 2024 Journey with High Hopes.pdf
Turkiye Vs Georgia Turkey's UEFA Euro 2024 Journey with High Hopes.pdfEticketing.co
 
Austria vs France David Alaba Switches Position to Defender in Austria's Euro...
Austria vs France David Alaba Switches Position to Defender in Austria's Euro...Austria vs France David Alaba Switches Position to Defender in Austria's Euro...
Austria vs France David Alaba Switches Position to Defender in Austria's Euro...Eticketing.co
 
Technical Data | ThermTec Wild 650L | Optics Trade
Technical Data | ThermTec Wild 650L | Optics TradeTechnical Data | ThermTec Wild 650L | Optics Trade
Technical Data | ThermTec Wild 650L | Optics TradeOptics-Trade
 
Expert Pool Table Refelting in Lee & Collier County, FL
Expert Pool Table Refelting in Lee & Collier County, FLExpert Pool Table Refelting in Lee & Collier County, FL
Expert Pool Table Refelting in Lee & Collier County, FLAll American Billiards
 
Italy Vs Albania Euro Cup 2024 Italy's Strategy for Success.docx
Italy Vs Albania Euro Cup 2024 Italy's Strategy for Success.docxItaly Vs Albania Euro Cup 2024 Italy's Strategy for Success.docx
Italy Vs Albania Euro Cup 2024 Italy's Strategy for Success.docxWorld Wide Tickets And Hospitality
 
France's UEFA Euro 2024 Ambitions Amid Coman's Injury.docx
France's UEFA Euro 2024 Ambitions Amid Coman's Injury.docxFrance's UEFA Euro 2024 Ambitions Amid Coman's Injury.docx
France's UEFA Euro 2024 Ambitions Amid Coman's Injury.docxEuro Cup 2024 Tickets
 
JORNADA 3 LIGA MURO 2024GHGHGHGHGHGH.pdf
JORNADA 3 LIGA MURO 2024GHGHGHGHGHGH.pdfJORNADA 3 LIGA MURO 2024GHGHGHGHGHGH.pdf
JORNADA 3 LIGA MURO 2024GHGHGHGHGHGH.pdfArturo Pacheco Alvarez
 
Instruction Manual | ThermTec Hunt Thermal Clip-On Series | Optics Trade
Instruction Manual | ThermTec Hunt Thermal Clip-On Series | Optics TradeInstruction Manual | ThermTec Hunt Thermal Clip-On Series | Optics Trade
Instruction Manual | ThermTec Hunt Thermal Clip-On Series | Optics TradeOptics-Trade
 
Instruction Manual | ThermTec Wild Thermal Monoculars | Optics Trade
Instruction Manual | ThermTec Wild Thermal Monoculars | Optics TradeInstruction Manual | ThermTec Wild Thermal Monoculars | Optics Trade
Instruction Manual | ThermTec Wild Thermal Monoculars | Optics TradeOptics-Trade
 
IPL Quiz ( weekly quiz) by SJU quizzers.
IPL Quiz ( weekly quiz) by SJU quizzers.IPL Quiz ( weekly quiz) by SJU quizzers.
IPL Quiz ( weekly quiz) by SJU quizzers.SJU Quizzers
 
Real Moto 2 MOD APK v1.1.721 All Bikes, Unlimited Money
Real Moto 2 MOD APK v1.1.721 All Bikes, Unlimited MoneyReal Moto 2 MOD APK v1.1.721 All Bikes, Unlimited Money
Real Moto 2 MOD APK v1.1.721 All Bikes, Unlimited MoneyApk Toly
 
8377087607 ☎, Cash On Delivery Call Girls Service In Hauz Khas Delhi Enjoy 24/7
8377087607 ☎, Cash On Delivery Call Girls Service In Hauz Khas Delhi Enjoy 24/78377087607 ☎, Cash On Delivery Call Girls Service In Hauz Khas Delhi Enjoy 24/7
8377087607 ☎, Cash On Delivery Call Girls Service In Hauz Khas Delhi Enjoy 24/7dollysharma2066
 
Technical Data | ThermTec Wild 335 | Optics Trade
Technical Data | ThermTec Wild 335 | Optics TradeTechnical Data | ThermTec Wild 335 | Optics Trade
Technical Data | ThermTec Wild 335 | Optics TradeOptics-Trade
 
Austria VS France Injury Woes a Look at Euro 2024 Qualifiers.docx
Austria VS France Injury Woes a Look at Euro 2024 Qualifiers.docxAustria VS France Injury Woes a Look at Euro 2024 Qualifiers.docx
Austria VS France Injury Woes a Look at Euro 2024 Qualifiers.docxWorld Wide Tickets And Hospitality
 

Último (16)

Mysore Call Girls 7001305949 WhatsApp Number 24x7 Best Services
Mysore Call Girls 7001305949 WhatsApp Number 24x7 Best ServicesMysore Call Girls 7001305949 WhatsApp Number 24x7 Best Services
Mysore Call Girls 7001305949 WhatsApp Number 24x7 Best Services
 
Turkiye Vs Georgia Turkey's UEFA Euro 2024 Journey with High Hopes.pdf
Turkiye Vs Georgia Turkey's UEFA Euro 2024 Journey with High Hopes.pdfTurkiye Vs Georgia Turkey's UEFA Euro 2024 Journey with High Hopes.pdf
Turkiye Vs Georgia Turkey's UEFA Euro 2024 Journey with High Hopes.pdf
 
Austria vs France David Alaba Switches Position to Defender in Austria's Euro...
Austria vs France David Alaba Switches Position to Defender in Austria's Euro...Austria vs France David Alaba Switches Position to Defender in Austria's Euro...
Austria vs France David Alaba Switches Position to Defender in Austria's Euro...
 
Technical Data | ThermTec Wild 650L | Optics Trade
Technical Data | ThermTec Wild 650L | Optics TradeTechnical Data | ThermTec Wild 650L | Optics Trade
Technical Data | ThermTec Wild 650L | Optics Trade
 
Expert Pool Table Refelting in Lee & Collier County, FL
Expert Pool Table Refelting in Lee & Collier County, FLExpert Pool Table Refelting in Lee & Collier County, FL
Expert Pool Table Refelting in Lee & Collier County, FL
 
Italy Vs Albania Euro Cup 2024 Italy's Strategy for Success.docx
Italy Vs Albania Euro Cup 2024 Italy's Strategy for Success.docxItaly Vs Albania Euro Cup 2024 Italy's Strategy for Success.docx
Italy Vs Albania Euro Cup 2024 Italy's Strategy for Success.docx
 
France's UEFA Euro 2024 Ambitions Amid Coman's Injury.docx
France's UEFA Euro 2024 Ambitions Amid Coman's Injury.docxFrance's UEFA Euro 2024 Ambitions Amid Coman's Injury.docx
France's UEFA Euro 2024 Ambitions Amid Coman's Injury.docx
 
JORNADA 3 LIGA MURO 2024GHGHGHGHGHGH.pdf
JORNADA 3 LIGA MURO 2024GHGHGHGHGHGH.pdfJORNADA 3 LIGA MURO 2024GHGHGHGHGHGH.pdf
JORNADA 3 LIGA MURO 2024GHGHGHGHGHGH.pdf
 
Instruction Manual | ThermTec Hunt Thermal Clip-On Series | Optics Trade
Instruction Manual | ThermTec Hunt Thermal Clip-On Series | Optics TradeInstruction Manual | ThermTec Hunt Thermal Clip-On Series | Optics Trade
Instruction Manual | ThermTec Hunt Thermal Clip-On Series | Optics Trade
 
Instruction Manual | ThermTec Wild Thermal Monoculars | Optics Trade
Instruction Manual | ThermTec Wild Thermal Monoculars | Optics TradeInstruction Manual | ThermTec Wild Thermal Monoculars | Optics Trade
Instruction Manual | ThermTec Wild Thermal Monoculars | Optics Trade
 
IPL Quiz ( weekly quiz) by SJU quizzers.
IPL Quiz ( weekly quiz) by SJU quizzers.IPL Quiz ( weekly quiz) by SJU quizzers.
IPL Quiz ( weekly quiz) by SJU quizzers.
 
Denmark Vs Serbia Haaland Euro Cup CPR Drive Incident.docx
Denmark Vs Serbia Haaland Euro Cup CPR Drive Incident.docxDenmark Vs Serbia Haaland Euro Cup CPR Drive Incident.docx
Denmark Vs Serbia Haaland Euro Cup CPR Drive Incident.docx
 
Real Moto 2 MOD APK v1.1.721 All Bikes, Unlimited Money
Real Moto 2 MOD APK v1.1.721 All Bikes, Unlimited MoneyReal Moto 2 MOD APK v1.1.721 All Bikes, Unlimited Money
Real Moto 2 MOD APK v1.1.721 All Bikes, Unlimited Money
 
8377087607 ☎, Cash On Delivery Call Girls Service In Hauz Khas Delhi Enjoy 24/7
8377087607 ☎, Cash On Delivery Call Girls Service In Hauz Khas Delhi Enjoy 24/78377087607 ☎, Cash On Delivery Call Girls Service In Hauz Khas Delhi Enjoy 24/7
8377087607 ☎, Cash On Delivery Call Girls Service In Hauz Khas Delhi Enjoy 24/7
 
Technical Data | ThermTec Wild 335 | Optics Trade
Technical Data | ThermTec Wild 335 | Optics TradeTechnical Data | ThermTec Wild 335 | Optics Trade
Technical Data | ThermTec Wild 335 | Optics Trade
 
Austria VS France Injury Woes a Look at Euro 2024 Qualifiers.docx
Austria VS France Injury Woes a Look at Euro 2024 Qualifiers.docxAustria VS France Injury Woes a Look at Euro 2024 Qualifiers.docx
Austria VS France Injury Woes a Look at Euro 2024 Qualifiers.docx
 

Road attack

  • 1. A Group Project Report on ROAD ATTACK Submitted to The Department of Electronics and Computer Engineering In partial fulfillment of the academic requirements of SNIST For The award of the degree of Bachelor of Technology In Electronic and Computer Engineering (2010 – 2014) By T samba siva rao 11315A1919 B sandeep kumar 11315A1921 P rakesh kumar 11315A1922 Under the Guidance of Shayam babu Sreenidhi Institute of Science and Technology (AUTONOMOUS) Yamnampet, Ghatkesar, R.R. District, Hyderabad - 501301
  • 2. Department of ElectronicsAnd Computer Engineering Sreenidhi Institute of Science and Technology CERTIFICATE This is to certify that this project report on “EXTREME RACING”, submitted by T.sambasiva(11315A1919), B.sandeep (11315A1921),P.rakesh(11315A1922) in the year 2012 in partial fulfillment of the academic requirements of Sreenidhi Institute of Science and Technology for the award of the degree of Bachelor of Technology inElectronics and Computer Engineering, is a bonafide work that has been carried out by them as part of their Group Project during Third Year First Semester, under our guidance. This report has not been submitted to any other institute or university for the award of any degree. M.Shyam babu K.SASIDHAR Assistant Professor Department of ECMHOD Internal Guide Department of ECM
  • 3. ACKNOWLEDGEMENT This project report is the outcome of the efforts of many people, who have driven my passion to explore into Java. We have received great guidance, encouragement and support from them and have learned a lot because of their willingness to share their knowledge and experience. Primarily, we should express our deepest sense of gratitude to our internal guide Mr.M.shyam babu, Assistant Professor, Department of ECM. His guidance has been of immense help in surmounting various hurdles along the path of our goal. We are deeply indebted to Mrs. Sasidhar .K, Head, and Department of ECM, who spared her most valuable time without any hesitation whenever we wanted. We record with a great feeling of gratitude, the contributions of all the faculty members, who encouraged us during this project by rendering their help when needed. Finally we thank our parents and adore Almighty God who has made us come in contact with such worthy people at the right time, provided us with all the necessary resources and made us accomplish this task. T. samba siva P.rakesh kumar B. sandeep kumar
  • 4. INDEX Abstract i List of Figures ii 1.INTRODUCTION 1 1.1 Project Specification 2 2.SYSTEM DESIGN 4 2.1 Modules 4 3.SYSTEM IMPLEMENTATION 07 4.TEST 20 5. CONCLUSION 37 6.REFERENCE 38
  • 5. ABSTRACT The main objective of this project is to develop a Java based personal computer game. Basically it‟s a car racing game in which user‟s car has to reach the destination in the given time by avoiding the obstacles. If user completes one level successfully, he will be forwarded to next level with increased complexity. User can change his car, save his score and enable or disable back ground sounds. User can use special features like Health, Time and Speed booster in reaching the destination. 1
  • 6. 1. INTRODUCTION About Game: Extreme Racing is a JAVA based PC game where the user‟s car has to reach the destination within a given time avoiding the Obstacles.There will be maximum ten levels. User has to cross ten levels to win the game. User will be provided with 4 lives to complete the game. In addition, he can use additional features like weapons to fire the enemies and special features like boosters to reach the destination. JAVA: Java is a Programming Language and computing platform first released by Sun Microsystems in 1995.It is the underlying technology that powers state-of-art technology including utilities,games and applications. It was started in 1991 as a project named “Green”, to develop a platform-independent language that can be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls etc.  Java runs inside a piece of software known as a Java Virtual Machine.  In many languages, such as C and C++, the source code (.c and .cpp files) is portable. What makes Java unique is that Java‟s executable code is also portable (.class files).  This means that the same application can be run without modification on any system that has a Java Virtual Machine without being recompiled. 2
  • 7. 1.1 Project Specifications: Software Requirements: 1. Java SE 1.6 2. Any OS that supports java Hardware Requirements: A personal computer with 1. Processor – PIV or above 2. RAM – Minimum of 512 3
  • 8. 2. System Design 2.1 Modules There are 5 Panels in this project. They are 1. Start Screen 2. Game Panel 3. Options 4.High Scores 5.Help Panel 4
  • 9. 2.2.1 Use case Diagram: Figure 2.1 : Use case Diagram 5
  • 10. 2.2.2 Class Diagram: Figure 2.2 : Class Diagram 6
  • 11. 2.2.3 Sequence Diagram: Figure 2.3:Sequence Diagram 7
  • 12. 2.2.4 Collaboration Diagram: Figure 2.4: Collaboration diagram 8
  • 13. 2.1.1 START SCREEN: Start Screen is the interface between the user and the game. It allows the user to select the options of his own.It is the first screen that appears when a user opens the game.It provides user interface components to start the game, to view the high scores, to exit from the application, game options etc.Depending on the user input in this screen, user will be taken further in to the game. Start screen includes features like Start game:Takes user in to the Game Options :Gives Options like Select Car and background music High Score : Displays the High Scores of the previous users Help : Shows the game controls and special features. Exit : Exit the game. 2.1.2 Game Panel When the user clicks on start game button in start screen, he will be brought to this screen. This is the Panel where the user plays the game. This panel contains some components on either sides to display information about the game. Components that appear on Game Panel: Score – displays the score of the user Level – Shows the current level. Lives – Shows number of lives left Time – Shows time left to reach the destination. 9
  • 14. 2.1.3Options Panel This is the panel where the user can select options of his choice. This panel allows the user to select car and change the sounds on/off. Components that appear on Option Panel: Select Car-Allows user to select the car. Sound-Allows the users to set sounds on/off. 2.1.4 High Scores This panel displays the High Scores to the User. When the user finishes the game he will prompted to enter user‟s name to stores his score. This window can be focused in two ways: When the User click on High Scores button on Start Screen. When the user finished the game, he will be directed to High Scores Panel. 2.1.5 Help Panel This panel displays help information for user. Help Screen include: Direction Keys-It tells the keys to be used in directing the car Special Features-It tells about special features in the game like Bullets, Pause, MainMenu, Boosters. 10
  • 15. 3. System Implementation 3.1 Game Window: This class extends JFrame. JFrame creates a window. This is the only window in the project. All the panels in the game are added to this window and switched according to the user input. Creation of multiple objects is avoided by using the concept „singleton object‟. Card layout is used to set the layout of the main frame. Panels are switched based upon the user input. Sample code for creating singleton object: publicstaticGamePanelgetGamePanel() { if(gamepanel == null) gamepanel = newGamePanel(); returngamepanel; } 3.2 Start Screen: This class extends a Jpanel. Jpanel is a plain surface that can be added to frames. An object for this screen is created and added to the main frame (Game window). This panel contains 5 buttons start game, options, high score, help, exit. When user clicks on a specific button we switch the panel in the cardlayout (maincardlayout). Several images will be displayed in this screen. Following is the sample code for loading images into the project. Sample code for creating image: ImageIconstarticon = newImageIcon(this.getClass().getResource("startgame.jpg")); startimage = starticon.getImage(); 11
  • 16. getContentPane() method returns the object of the default panel on game window. By using this method, an object of default panel is created and other panels are added to it. sample code for adding panel to cardlayout startScreen = newStartScreen(); getContentPane().add(startScreen,"start screen"); Sample code for switching panels GameWindow.getGameWindowInstance().changePanel(GameWindow.getContentP ane(),”game panel”); 3.3 Game Panel 3.3.1 Timer Class Creates a Timer and initializes both the initial delay and between-event delay to delaymilliseconds. If delay is less than or equal to zero, the timer fires as soon as it is started. If listener is not null, it's registered as an action listener on the timer. Fires one or more action events after a specified delay. For example, an animation object can use a Timer as the trigger for drawing its frames. Setting up a timer involves creating a Timer object, registering one or more action listeners on it, and starting the timer using the start method. For example, the following code creates and starts a timer that fires an action event once per second (as specified by the first argument to the Timer constructor). The second argument to the Timer constructor specifies a listener to receive the timer's action events. Sample code int delay = 10; //milliseconds Timer timer = new Timer(delay,this); timer.start(); 12
  • 17. 3.3.2 Paint Method Invoked by Swing to draw components. This method actually paints all the images in our game. Applications should not invoke paint directly, but should instead use the repaint method to schedule the component for redrawing. Sample code publicvoid paint(Graphics g) { super.paint(g); g.drawImage(roadimage, road_x, road_y[0], this); g.drawImage(roadimage, road_x, road_y[1], this); } 3.3.3 ActionPerformed method This method many actions in our game such as calculating the score, levels, lives, distance, changing the position of the road, changing position of the enemy cars, changing positions of the bullets etc. All these are maintained in different methods. This method gets called every time the timer object raises the event. Sample code public void actionPerformed(ActionEvent e) { accelerate(); moveRoad(); moveBullets(); moveEnemies(); checkCollision(); } 3.3.4 Moving road Timer object fires the event for every 10 milli seconds i.e paint method, actionPerformed method gets called 100 times for every second. The position of the images is changed in actionPerformed method. Beacause of changing positions of the images and repainting, user gets illusion that the car is moving. The position of the road is changed in actionperformed method. 13
  • 18. Sample code for changing position of the road. road_y[1]+=acceleration; if(road_y[1]>=(810-acceleration)) road_y[1] = 0; road_y[0] = road_y[1]-810; When the road crosses the position of 810, it‟s position has been changed to 0. An another road image in road[0] position will always follow the road in road[1] position. So the road images will be moved in a continuous loop. 3.3.5 Acceleration of user’s car Acceleration of the user car is maintained by using a variable called acceleration. As long as the user presses the up arrow key, this variable gets incremented. Acceleration decrement is constantly maintained by decrementing the acceleration variable when the user does nor presses the up arrow key. Sample code of maintaining acceleration if(upkeypressed){ if(acceleration<max_acceleration) { acceleration++; }} 14
  • 19. 3.3.6 Moving bullets Two arrays are created to maintain the x and y positions of the bullets. When the user presses the button „x‟ the positions(x,y) of one bullet is initialized. As long as user presses the x button, the x,y positions of bullets are initialized. These positions are moved by changing these positions in actionperformed method. When a bullet crosses the border, it will be initialized to zero. Bullets are painted in paint method when their positions are not zero. Sample code PrivatevoidmoveBullets() { for(int i = 0;i<bullet_y.length;i++) { if(bullet_y[i] != 0) bullet_y[i]-=10; if(bullet_y[i] < 0) bullet_y[i] = 0; } } 3.3.7 Moving enemies Enemy car‟s y position is changed every time action performed method gets called. When the enemy car crosses the border, it‟sy position is initialized to a value less than zero so that it comes from the starting position again. It‟s x position is relocated by using locateEnemyPosition method. Enemy car is moved with a value greater than user car‟s acceleration so that if the user car moves fast, enemy car also moves fast. Sample code PublicvoidmoveEnemies() { enemy_y+=(acceleration+4); if(enemy_y>810){ enemy_y = -200;locateEnemyPosition();} } 15
  • 20. 3.3.8 Checking collision Enemy car‟s collision with user car is maintained in the checkcollision method. This method is called in actionperformed method. Each time enemy car‟s position is changed, it‟s collision with the user‟s car is checked. If enemy car hits the user car 4 times, a variable called lives is decremented. When this variable comes to zero, the game is ended and user is prompted to save his score. Sample code publicvoidcheckCollision(){ if((enemy_y+85)>=car_y&&enemy_x>=(car_x-45) &&enemy_x<=(car_x+45)){ enemy_y = -200; locateEnemyPosition(); energy-=100; if(energy == 0) { energy = 400;lives--; lifeover = true; if(lives == 0) gameover = true; } } } 3.3.9 Playing Audio User can enable or disable sounds from the options screen. Audio is played by using the classes AudioSystem, Clip. Audio files are loaded and played in GamePanel class. Sample code for loading audio files into the project publicvoid initAudioFiles() { try{ File file = new File("sound.wav"); audioIn = AudioSystem.getAudioInputStream(file); // Get a sound clip resource. mainaudioclip = AudioSystem.getClip(); audioIn2 = AudioSystem.getAudioInputStream(file2); bulletclip = AudioSystem.getClip(); audioIn3 = AudioSystem.getAudioInputStream(file3); explosionclip = AudioSystem.getClip(); // Open audio clip and load samples from the audio input stream. 16
  • 21. mainaudioclip.open(audioIn); // Open an audio input stream. }catch(Exception e){} } Sample code for starting an audio clip mainaudioclip.start(); mainaudioclip.loop(mainaudioclip.LOOP_CONTINUOUSLY); 3.3.10 Reading User Settings User settings saved in highscores.txt are read by using the method getUserSettings(). Sample code for reading user settings publicvoid getUserSettings() { try{ File f; f=new File("settings.txt"); if(!f.exists()){ f.createNewFile(); usercar = "usercar2.jpg"; sounds = false; return; } else{ FileInputStream fstream = new FileInputStream(f); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; String[] all = new String[3]; while((line=br.readLine())!=null) { all = line.split(","); } if(all[0]!=null) usercar = all[0]; else usercar = "usercar2.jpg"; if(all[1].equals("on")) sounds = true; else sounds = false; } }catch (Exception e) { // TODO: handle exception 17
  • 22. } } 3.3.11 Keyboard input KeyAdapter class is used to take input from the user in this game. Java language rules are such that we must implement all the methods of an interface even if we can put them into empty braces i.e we must override all the methods declared in the interface. But we can create our classes as subclasses of one of the adapter classes then we need to override only some of the methods we need. An adapter calss provides an empty implementationof all methods declared in listener concerned interface. Keypressed(KeyEventke) method is used to identify which key has been pressed. Ke.getkeycode() method returns the Unicode of the character. When a key is pressed, it will be checked with getkeycode() method and the corresponding action will be performed. 3.3.12 The KeyEvent Class IntgetKeyChar( ) which returns the character that was entered, and intgetKeyCode( ) which returns the key code. It defines many integer constants: VK_ENTER VK_ESCAPE VK_CANCEL VK_UP VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN VK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL 18
  • 23. 3.4 High Scores Screen User high scores are saved using text file. A text file is created through the code and user‟s high scores are saved in it. When the user opens the game, the list of high scores are loaded into the game. Every time, when user completes the game, he is prompted to save his score. This score is checked with the list of high scores and will be saved if it is better than top 10th high score in the list. Sample code for creating new text file File f; f=newFile("HighScore.txt"); if(!f.exists()){ f.createNewFile(); } Sample code for reading file contents. FileInputStreamfstream = newFileInputStream(f); DataInputStream in = newDataInputStream(fstream); BufferedReaderbr = newBufferedReader(newInputStreamReader(in)); String line; String[] all = new String[3]; while((line=br.readLine())!=null) { all = line.split(","); al.add((Object)all); } Sample code for writing file contents. fwriter = newFileWriter(f); BufferedWriter br2 = newBufferedWriter(fwriter); for(int i = 0;i<al.size();i++) { String[] p = (String[])al.get(i); br2.write(p[0]+","+p[1]+","+p[2]+"n"); } br2.close(); 19
  • 24. 3.5 Options Screen User‟s setting are also saved in a text file. Buffered reader and buffered writer classes are used to save settings into the text file. Two settings(usercarimage,sounds) are saved in the file. User settings are loaded into the game when user opens the game for the first time. Sample code for saving settings publicvoidsaveSettings(){ FileWriterfwriter = newFileWriter(f); BufferedWriter br2 = newBufferedWriter(fwriter); br2.write(selectedcar+","+sound+"n"); br2.close(); } Sample code for reading user settings while((line=br.readLine())!=null) all = line.split(","); selectedcar = all[0] ; sound = all[1]; if(selectedcar.equals("usercar1.jpg")) carnum = 1; elseif(selectedcar.equals("usercar2.jpg")) carnum = 2; 3.6 Help Screen All the help information for the user is painted in the paint method. A user interface component is placed in the screen for the user to go to the main menu. Sample code for displaying help information 20
  • 25. publicvoid paint(Graphics g) { // TODO Auto-generated method stub super.paint(g); g.setFont(bigfont); g.setColor(Color.red); g.drawString("Help", 300, 50); g.setColor(Color.yellow); g.setFont(mediumfont); g.drawString("DIRECTION KEYS", 20, 100); g.setFont(smallfont); g.setColor(Color.red); g.drawString("UP ARROW ",20,150); g.drawString("DOWNN ARROW ",20,200); g.drawString("LEFT ARROW ",20,250); g.drawString("RIGHT ARROW ",20,300); } Testing: When the user clicks on any of the buttons available, he will be directed to a new screen. Based on the user actions, he will be proceeded further in the game. 21
  • 26. When the user clicks on Start Game button he will be redirected to new window in which the user can play the game. In this user can find many features like 1. Level 2. Score 3. Time 4. Lives left 5. Health 6. Accelerometer 7. And a small window showing position of car in the main track. 22
  • 27. As shown in the figure, Level indicates the current level the user is playing. It shows 1 when the game is started indicating that the user is in 1st level of the game. When the user completes the first level, the value of Level tab will become 2.That is each time when the user completes a level value of level tab will be automatically incremented by 1.There are maximum of ten levels in the game. When the user finishes the level, to indicate the end of the level Finish line will be displayed. 23
  • 28. When the user finishes all the levels successfully, a message will be displayed congratulating the winner. 24
  • 29. Another important feature in this game is the Score tab. When the user starts the game initial score of the user is zero. As the user proceeds in the game he will be awarded the score according to the distance he race through. Score will be awarded for the distance he travel. There is a maximum of 3000 meters track in the game, when the user finishes the level he will have the 25
  • 30. score of 3000. In addition to the score awarded based on distance he travel, additional scores will be awarded when the user attacks the opponent cars with the provided bullets. User can fire bullets by pressing “X” key in key board. Each time user attacks the opponent he will be awarded the bonus of 100 points. The more user attacks the opponents more he gets bonus and more score. As shown in the above figure, Score increased to 8001 and level changed to 2 indicating that the user is now in 2nd level. Also, the figure shows the bullets released by the user when he is attacking the opponents. Each time bullet hits theopponent, user gets a bonus of 100 points. Anytime, user can be redirected to Start Screen by pressing “M” key in the key board. Time indicates the time left for the user to reach the destination. User will be given a time of 60 seconds to reach the destination. If he failed to do so he will lose the game. If he reaches the destination within the given 60 seconds he will be promoted to next level. 26
  • 31. Health of the user is indicated by a special bar at the bottom of the screen. Initially user has full health. Each time user collides with an obstacle, health will be reduced by 25%. When user collides with obstacles for 4 times, user‟s car will explode and user will lose one of his lives and the level will restarted. As shown in the above figures, Lives of the user are denoted by the special symbol in the window below the time tab. Each time user‟s health reduced to zero one out of four lives will be reduced. When user loses all his four lives he can no longer continue with the game. He will be asked to save his score in the High Scores window and exit the game. 27
  • 32. User will be redirected to High Scores window. In High Scores window a new text field and button named “ok” will be displayed allowing the user to register his name to save his score. If the users score stands in top 10 scores it will be displayed in the top scores list with serial name indicating position he is standing, name of the user and his score. Name of the user should not include special characters. It should be a plain text. If the user enters any wrong details he will be prompted with a warning dialog box and will be asked to enter correct details. 28
  • 33. When the user clicks on Main menu button in the High Scores tab he will be redirected to Start Screen window. Accelerometer on the right side of the main track indicates the speed at which car is moving. The maximum speed of the car is 156. Small track with a small car to the right of the main track indicates the position of the car in the track. It gives an idea to the user about the distance left to reach the destination so that the user can speed up or slow down to reach the destination in given time. During the race when the users proceed special features like health, speed and time booster will arise along the track. When user takes this booster, respective powers will be activated. There are 3 types of boosters. 1. Health 2. Speed 29
  • 34. 3. Time When the user gets the Health Booster, health of the user will be increased to maximum. This feature helps the user to increase the health when the health is going down. It helps the user in reaching the destination with less chance of losing the life. When user gets the Speed booster, speed of the user will be incremented. Initially user has a maximum speed of 156. But, when the user takes the Speed Booster speed will be increased to 220. This feature helps the user to reach the destination with more speed and thereby saves the time of the user. 30
  • 35. This speed added by this feature stands until the end of the level. 31
  • 36. When the user gets the Time Booster, it will add additional time of 20 seconds to the user. This feature helps the user when he is running short of time. So that user can reach the destination with the help of this additional time. These 3 boosters Health, Speed and Time will rise randomly in the track. When the User clicks on Option Button in the Start Screen, he will be redirected to Options window. In the Option window user can select car of his choice and also user can set sounds On or Off. 32
  • 37. In Select car tab, user will be provided with 4 different types of cars. User can select one of the four cars. In Sounds tab, user can set the game sounds On/Off with the help of the radio buttons provided When the user clicks on the Main menu tab in Option window he will be redirected to Start Screen of the game. 33
  • 38. After making the required changes user have to save the changes. He can do so by clicking on save button to save changes. When user clicks on save button, a new dialog will be displayed prompting the user that the settings are saved. When the user clicks on Ok button in dialog box he will be redirected to Start Screen Window to continue with the game. Now the when the user starts the game selected car will be used in the game and sound changes also will be effective. 34
  • 39. When user clicks on High Scores button in the Start Screen, he will be redirected to High Scores window. High Scores window displays logs of high scores recorded in the game. High Scores window displays the high scores of the users in descending order. That is top scores stands first in the position of rankings. High Scores window can display the records of 10 users. When a new record is created it will be recorded into the log based on the score and least score will be taken out from the high scores log. 35
  • 40. When the user clicks on Help button in the Start Screen window, he will be redirected to Help Window. Help contains information needed for the user to play the game. Help Contains information about 1. Direction Keys 2. Special features. Direction Keys helps the user in controlling the car. 1. UP Arrow – Move forward 2. DOWN Arrow – Apply breaks 3. Left Arrow – Move left 4. Right Arrow – Move right 36
  • 41. Special Features contains information about special buttons and booster icons. 1. X : To fire Bullets 2. P : To pause the game 3. M : To display main menu And also contains information needed to identify the boosters. To exit from the game user can click the Exit button in Start Screen window. When the user clicks on the exit button he will be directed out of the game. 37
  • 42. 5. Conclusion Practical Training is very important part of the curriculum as it strengthens the concepts and enhances knowledge about the practical implementation of all theory concepts, we have learnt so far in different subjects. In future we can enhance this “Extreme Racing Game” using new technologies because its codes are so simple that a lay man can understand. Since this is developed in java which is truly object oriented language it support the future additions and eliminations in the code. We can increase the flexibility with adding new levels to the game and new items in the appearance of the game. Although we have completed this project, due to lack of knowledge on a few concepts and constraint of time, we could not include some more features we wanted to. We left these features as a part of the future development. 38
  • 43. 6. References • The java Language specification, third edition by James Gosling, Bill Joy, Guy Steele, Gilad Bracha. • Introduction to Programming using java, sixth edition by David J Eck • http://www.mybringback.com/tutorials/ • http://www.tutorialspoint.com/ • http://www.java2s.com/Tutorial/Java/CatalogJava.html 39