Go Back   TechArena Community > ARENA > Guides & Tutorials
Become a Member!
Forgot your username/password?
Register Tags Active Topics RSS Search Mark Forums Read

Sponsored Links



Demo of a simple 2D game in Java

Guides & Tutorials


Reply
 
Thread Tools Search this Thread
  #1  
Old 01-12-2010
Member
 
Join Date: Sep 2010
Posts: 73
Well due to the concerns of some users, I decided to do something simple in java that can be exploited to others who want to make games or applications on this platform, the main idea is to lay the bases, because I know many who You start with programming, here to there without having a clear idea of why the design, reducing the importance of this, and finally come the problems, mistakes, and everything becomes incomprehensible and unreadable. So I stopped chattering, and go with what we are. First, if we speak of a 2D game, we need Sprites, Sprites are the basis of bitmap, mainly get the picture of the resources previously stored in a default package, so it is good that we are organized and that the names used in a project, they are always in our native language, and have understandable names. I know many of you too lazy to write variables with more than three characters in a row, but it will help us fully understand the code, and if we work together, help us understand that the team also.

Code:
/ * 
* To change this template, choose Tools | Templates 
* And open the template in the editor. 
* / 

package game; 

import java.awt .*; 
javax.swing.ImageIcon import; 
/ ** 
* 
* @ Author TechArena
* / 
public class SpriteTrial { 
private int x, y, / / coordinates 
private boolean visible; / / if visible or not 
SpriteTrial private String / / the image name 

public SpriteTrial () / / Constructor 
{ 
visible = true; 
x = y = 0; 
} 

public boolean isVisble () 
{ 
return visible; 
} 

public void setVisible (boolean state) 
{ 
visible = state; 
} 

public int getX () / / Get the current horizontal coordinate SpriteTrial 
{ 
return x; 
} 

public void setX (int value) / / Assign the current horizontal coordinate SpriteTrial 
{ 
x = value; 
} 

public int getY () / / Get the current vertical coordinate SpriteTrial 
{ 
return y; 
} 

public void setY (int value) / / Assign the current vertical coordinate SpriteTrial 
{ 
y = value; 
} 

public int getWidth () / / Width of SpriteTrial 
{ 
return new ImageIcon (getClass (). getResource (SpriteTrial)). getImage (). getWidth (null); 
} 

public int getHeight () / / Height of SpriteTrial 
{ 
return new ImageIcon (getClass (). getResource (SpriteTrial)). getImage (). getHeight (null); 
} 

public void setSpriteTrial (String name) / / Assign the image file to SpriteTrial 
{ 
SpriteTrial = name; 
} 

getSpriteTrial public String () / / It returns the image of the SpriteTrial file 
{ 
return SpriteTrial; 
} 

public void putSpriteTrial (Graphics graphics, int coordinateHorizontal, coordinateVertical int) / / Paste the SpriteTrial on the screen 
{ 
x = coordinateHorizontal; 
y = coordinateVertical; 
if (visible) graph.drawImage (new ImageIcon (getClass (). getResource (SpriteTrial)). getImage (), x, y, null); 
} 

}
In this class, we have included the basics of a Sprite, its purpose is that it can be printed on any device Graphics, allowing movement and get some of their properties, which can modify, including that of visible stress. This property can give us a lot of play. Imagine my character kills an enemy with one shot, then if we want to repeat the level, we need not destroy the enemy, and only tell you that is not visible. Visible also can serve to optimize the application, for example, we have the case that we have a scroll game screen, and we want to show that currently are in the area of the main character, and they are moving out of we are not interested to screen print them, and their subsequent painting process, which slows down the game, especially when we have zillions of Sprites, then modify the visible property to false and problem solved.

Reply With Quote
  #2  
Old 01-12-2010
Member
 
Join Date: Sep 2010
Posts: 73
Re: Demo of a simple 2D game in Java

I'll give an example of use of the class, because I observed that many are having the same doubts :
Code:
/ * 
* To change this template, choose Tools | Templates 
* And open the template in the editor. 
* / 

package game; 

import java.awt .*; 
import java.awt.event .*; 
java.awt.image.BufferedImage import; 

/ ** 
* 
* @ Author TechArena
* / 
public class Game extends Canvas { 
/ / TODO code application logic here 
private Frame window; 
private Sprite sprite, otSprite; 
long time = System.currentTimeMillis (); 

public Game () { 
sprite = new Sprite (); 
otSprite = new Sprite (); 

window = new Frame (); 

window.setSize (350.200) 
window.add (this); 
window.setVisible (true); 
window.addWindowListener (new WindowAdapter () { 
public void windowClosing (WindowEvent e) { 
System.exit (0); 
} 
}); 

sprite.setSprite ("/ Images / characters.png"); 
otSprite.setSprite ("/ Images / characters.png"); 
while (true) 
{ 
if (System.currentTimeMillis ()-time> 25) {/ / update every 25 milliseconds 

if (sprite.getX ()> this.getWidth ()) sprite.setX (0); 
else sprite.setX (sprite.getX () +1); 

draw (this.getGraphics ()); 
time = System.currentTimeMillis (); 
} 
} 
} 

public void draw (Graphics graphics) 
{ 
/ / The OpenGL or DirectX Begin 
Display = new BufferedImage BufferedImage (this.getWidth (), this.getHeight (), BufferedImage.TYPE_INT_RGB) 

sprite.putSprite (screen.getGraphics (), sprite.getX (), sprite.getY ()); 
otSprite.putSprite (screen.getGraphics (), 110, 100); 

/ / The End 
graph.drawImage (screen, 0, 0, this); 
} 
}
Reply With Quote
  #3  
Old 01-12-2010
Member
 
Join Date: Sep 2010
Posts: 73
Re: Demo of a simple 2D game in Java

Well, how have the base and Sprite, and we can get in order to move the player or user. The playable characters, forward PJ, has the property that has the attributes and properties required for the game you're designing will be controlled by any input device, like a joystick or in this case, with the keyboard. Among its attributes, for example, we can add a property of life, which can be initialized in the constructor with a value, which will diminish as we receive damage or collision with something, until it reaches zero, then it will be the death of Pj. We can also include an array of sprites that we may be used to store frames of animation, if we want to encourage him. Commented how the structure can vary but the basic and necessary, which is the control panel by the arrow, the body is essential.

Code:
/ * 
* To change this template, choose Tools | Templates 
* And open the template in the editor. 
* / 
package game; 

import java.awt.event .*; 
/ ** 
* @ Author TechArena
* / 
Playable Character public class extends Sprite implements KeyListener { 

private boolean up, down, left, right; 

public void update () { 
if (top == true) this.setY (this.getY () -10); 
if (down == true) this.setY (this.getY () +10); 
if (left == true) this.setX (this.getX () -10); 
if (right == true) this.setX (this.getX () +10); 
} 

/ / Key not pressed 
public void keyReleased (KeyEvent ke) { 
switch (ke.getKeyCode ()) { 
KeyEvent.VK_DOWN case: 
down = false; 
break; 
KeyEvent.VK_UP case: 
up = false; 
break; 
KeyEvent.VK_LEFT case: 
left = false; 
break; 
KeyEvent.VK_RIGHT case: 
right = false; 
break; 
} 
} 

/ / Key pressed 
public void keyPressed (KeyEvent ke) { 
switch (ke.getKeyCode ()) { 
KeyEvent.VK_UP case: 
up = true; 
break; 
KeyEvent.VK_LEFT case: 
left = true; 
break; 
KeyEvent.VK_RIGHT case: 
right = true; 
break; 
KeyEvent.VK_DOWN case: 
down = true; 
break; 
} 
} 

public void keyTyped (KeyEvent ke) { 
throw new UnsupportedOperationException ("not supported yet.") 
} 
}
Now the problem we will not find, as we discussed a partner in a thread, is that we lose focus while creating the components. We must also say we need to implement the KeyListener object above it, for it to be focused and route keys capture by the addKeyListener (), Pj already created object, which contains methods to process the keys. Similarly, we can always address dynamically at run-time events making a particular object.
Reply With Quote
  #4  
Old 01-12-2010
Member
 
Join Date: Sep 2010
Posts: 73
Re: Demo of a simple 2D game in Java

Now that we move a Sprite, the ideal would encourage using multiple images one after another. To do this we must improve the Sprite class. The new upgrade features a couple of methods; resizeArray, setFrame and GetFrame. Is basically identical to the first one did, only this time working with an array that stores the names of image files that conform the animation. The operation differs slightly, if before the image we were assigned setSprite, now we can only assign a single image, because if we repeat the process with setSprite, we managed to store the next image and so on until we run out of memory . The variable responsible for displaying the image we want is the frame, which will be managed with the methods and setFrame GetFrame.
Code:
import java.awt .*; 
javax.swing.ImageIcon import; 
/ ** 
* 
* @ Author TechArena
* / 
public class SpriteTrial { 
private int x, y, frame, / / coordinates 
private boolean visible; / / if visible or not 
SpriteTrial private String [] / / The name of the image 

public SpriteTrial () / / Constructor 
{ 
SpriteTrial = new String [1]; 
frame = 0; 
visible = true; 
x = y = 0; 
} 

isVisble public boolean () / / we indicate whether or not it is visible 
{ 
return visible; 
} 

public void setVisible (boolean state) / / I will indicate whether it is visible or not 
{ 
visible = state; 
} 

public int getX () / / Get the current horizontal coordinate SpriteTrial 
{ 
return x; 
} 

public void setX (int value) / / Assign the current horizontal coordinate SpriteTrial 
{ 
x = value; 
} 

public int getY () / / Get the current vertical coordinate SpriteTrial 
{ 
return y; 
} 

public void setY (int value) / / Assign the current vertical coordinate SpriteTrial 
{ 
y = value; 
} 

public int getWidth () / / Width of SpriteTrial 
{ 
return new ImageIcon (getClass (). getResource (SpriteTrial [frame])). getImage (). getWidth (null); 
} 

public int getHeight () / / Height of SpriteTrial 
{ 
return new ImageIcon (getClass (). getResource (SpriteTrial [frame])). getImage (). getHeight (null); 
} 

private static Object resizeArray (Object oldArray, NewSize int) { 
java.lang.reflect.Array.getLength oldSize = int (oldArray) 
Class elementType = oldArray.getClass (). GetComponentType (); 
Object newArray = java.lang.reflect.Array.newInstance (elementType, NewSize) 
preserveLength int = Math.min (oldSize, NewSize) 
if (preserveLength> 0) 
System.arraycopy (oldArray, 0, newArray, 0, preserveLength) 
return newArray; 
} 

public void setSpriteTrial (String name) / / Assign the image file to SpriteTrial 
{ 
SpriteTrial [SpriteTrial.length-1] = name; 
SpriteTrial = (String []) resizeArray (SpriteTrial, SpriteTrial.length +1); 
} 

public void setFrame (int value) 
{ 
frame = value; 
} 

public int GetFrame () 
{ 
return frame; 
} 

getSpriteTrial public String () / / It returns the image of the SpriteTrial file 
{ 
return SpriteTrial [frame]; 
} 

public void putSpriteTrial (Graphics graphics, int coordinateHorizontal, coordinateVertical int) / / Paste the SpriteTrial on the screen 
{ 
x = coordinateHorizontal; 
y = coordinateVertical; 

if (visible) graph.drawImage (new ImageIcon (getClass (). getResource (SpriteTrial [frame])). getImage (), x, y, null); 
} 
}
Yes but, and animation? Worth it, the animation manually will work with the above methods, and GetFrame setFrame. But if you like to have a special function or method that does it all, and would have to work on the object or derivative Character Sprite, because not always all the characters or visual objects have the same behavior. So it is advisable to customize.
Reply With Quote
  #5  
Old 01-12-2010
Member
 
Join Date: Sep 2010
Posts: 73
Re: Demo of a simple 2D game in Java

Code:
import java.awt.event .*; 
/ ** 
* @ Author TechArena
* / 
PlayableCharacter public class extends Sprite implements KeyListener { 

private boolean up, down, left, right; 
private int accountActual, accountant; 

public int update () { 
int status = 0, / / Indicates the orientation or direction taken by the PJ 
if (counter + +> Integer.MAX_VALUE) counter = Integer.MIN_VALUE; 
if (top == true) {this.setY (this.getY () -10); state + = 1;} 
if (down == true) {this.setY (this.getY () +10); state + = 2;} 
if (left == true) {this.setX (this.getX () -10); state + = 4;} 
if (right == true) {this.setX (this.getX () +10); state + = 8;} 
return state; 
} 

encourages public void (int from, int to, int scale) 
{ 
if (Math.abs (counter-accountActual)> scale) { 
accountActual = counter; 
if (this.getFrame ()> = to) this.setFrame (from); else 
this.setFrame (this.getFrame () +1); 
} 
} 
/ / Key not pressed 
public void keyReleased (KeyEvent ke) { 
switch (ke.getKeyCode ()) { 
KeyEvent.VK_DOWN case: 
down = false; 
break; 
KeyEvent.VK_UP case: 
up = false; 
break; 
KeyEvent.VK_LEFT case: 
left = false; 
break; 
KeyEvent.VK_RIGHT case: 
right = false; 
break; 
} 
} 

/ / Key pressed 
public void keyPressed (KeyEvent ke) { 
switch (ke.getKeyCode ()) { 
KeyEvent.VK_UP case: 
up = true; 
break; 
KeyEvent.VK_LEFT case: 
left = true; 
break; 
KeyEvent.VK_RIGHT case: 
right = true; 
break; 
KeyEvent.VK_DOWN case: 
down = true; 
break; 
} 
} 

public void keyTyped (KeyEvent ke) { 
throw new UnsupportedOperationException ("not supported yet.") 
} 
}
So now the ideal is that if we are to create a main character, would create a class specifically for him, but that inherits all the properties of PlayableCharacter, such as:

Code:
/ ** 
* 
* @ Author TechArena
* / 
PlayableCharacter public class extends { 

public Lorna () 
{ 
super (); 
this.setSprite ("/ Images/lorna_walk1 .png"); 
this.setSprite ("/ Images/lorna_walk2.png"); 
this.setSprite ("/ Images/lorna_walk3.png"); 
this.setSprite ("/ Images/lorna_walk4.png"); 

} 

public void update () 
{ 
if (this. update ()> 0) this.solve(0,3,3); 

} 

}
We see in the constructor add the frames to the player with the setSprite, then to avoid confusion, we created a method updates, and PersonajeJugable class will rename its updates to be updated. The class updates the protagonist, will be responsible for capturing the keys, move the Sprite and now to cheer whenever the condition that we give, otherwise it would always be busy, but for example, must be conditioned as he moves, If it moves, if it does, if you miss, if reciobe damage, etc ... in the case of star nuetsro show the animation sequence while the Sprite to move in any direction, update ()> 0.
Reply With Quote
Reply

  TechArena Community > ARENA > Guides & Tutorials
Tags: , , , , ,



Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "Demo of a simple 2D game in Java"
Thread Thread Starter Forum Replies Last Post
how to create a simple student profile in java bluestar_me Software Development 2 20-01-2012 12:59 PM
How to calculate simple interest in java ? xanix Software Development 7 08-12-2011 10:47 PM
Implement Simple Database using BST in Java maxmidg412 Software Development 2 31-07-2011 03:22 AM
Running simple java program..... Kushan Software Development 4 16-11-2009 02:38 AM
Cannot launch simple applications (notepad, java) using Apache and PERL(CGI) Kretchy Software Development 5 02-06-2009 12:25 AM


All times are GMT +5.5. The time now is 10:06 AM.