2 player Java game

Started by
20 comments, last by Mossflower 17 years, 4 months ago
Ok, thx! And I know what you mean, my first exam is tommorow.
Advertisement
Does anyone else have other suggestions?
You don't need to use two threads for multiple player input: the keyPressed method is called any time a key is pressed. All you need to do in that function is to check which key was pressed and move the associated player.

The game loop is just a while loop that runs as long as the game isn't over. In this case, you don't need to check for input, since that's event-driven. So, all that's left is an update part and the rendering part. This game loop should probably be placed in a game thread. Anyway, in pseudocode (along with some suggestions for the game's structure):

void run(){	while(gameIsRunning)	{		update();		repaint();	}}void update(){	// Handle anything that needs to be updated here, such as moving objects, etc.}void paint(Graphics g){	// Paint everything here. It may be usefull to provide all paintable game objects	// with a virtual draw(Graphics g) function or something similar, and	// derive them all from a single GameObject class, for example, and use	// a vector of GameObjects so repainting the screen is a simple for loop	// that runs through this vector and calls the draw function of each object.	// The same can be applied to the update function, by providing this GameObject	// class with an update() function, where each derived class fills in it's	// behaviour. For example, a character might do an idle animation now and then,	// which could be determined in it's update() function.}
Create-ivity - a game development blog Mouseover for more information.
The game loop sounds like a great idea, so I'll use that. But my problem is that the keyPressed method only checks one button at a time. The players will probably be pressing buttons at the same time quite often, but they won't be able to move at the same time.
Instead of handline the input in the keyup and keydown events, create a container full of every possible key that Can be pressed. I don't know how to do arrays in java(or really anything in java), but it would be something like this:

Class Keyboard {    KeyboardArray    ...}Class Player    ...    public void keyPressed(KeyEvent pressed)    {            if(pressed.getKeyCode() == KeyEvent.VK_A)                KeyboardArray[KeyEvent.VK_A] = true            if(pressed.getKeyCode() == KeyEvent.VK_W)                KeyboardArray[KeyEvent.VK_W] = true            if(pressed.getKeyCode() == KeyEvent.VK_D)                KeyboardArray[KeyEvent.VK_D] = true            ....    }    public void keyReleased(keyEvent released)    {            if(released.getKeyCode() == KeyEvent.VK_A)                KeyboardArray[KeyEvent.VK_A] = false            if(pressed.getKeyCode() == KeyEvent.VK_W)                KeyboardArray[KeyEvent.VK_W] = false            if(pressed.getKeyCode() == KeyEvent.VK_D)                KeyboardArray[KeyEvent.VK_D] = false            ....    }    public void handleInput()    {        if(keyBoardArray[KeyEvent.VK_LEFT])            moveLeft();            COMMENT: What you Really want to do is have a speed variable and            COMMENT: Update it here        if(keyBoardArray[KeyEvent.VK_RIGHT)            moveRight();            COMMENT: What you Really want to do is have a speed variable and            COMMENT: Update it here        ....}


Hope this makes Some sense. I'm in a hurry and don't know java, but the principle is the same

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

Erm.. I don't really understand that last post. Does he want me to put the input in the player class? Because I already decided I shouldn't do that.
The previous poster is suggesting you use an array of bools to keep track of whether or not a key has been pressed. It will make your character movement smoother for example:

Public Class mainGameClass implements KeyListener{    private boolean keyPressed[] = new boolean[256];//...     public void keyPressed(KeyEvent pressed)    {           //set the key pressed to true           keyPressed[pressed.getKeyCode()] = true;        }    public void keyReleased(keyEvent released)    {           //set the key pressed to false           keyPressed[pressed.getKeyCode()] = false;    }//...   //then later in your program you could respond to the input with something like this   public void run()   {      if(keyPressed[VK_A] == true)          p1.moveLeft();       //... etc etc   }}


As for pressing multiple buttons at the same time I've run into this several times with java and I haven't figured out a solution :\. From what I can tell it usuall happens with the arrow keys as well as control, shift and space. You might want to try using letter keys only and see if that helps (although admitedly that probably wont make for the easiest control scheme, i just dont know a better way :\).
I can't seem to be able to get that to work. I get all sorts of weird errors in all the differnet ways that I try it. It's probably because I don't know much about arrays yet.....
It occurred to me last night that you'd want to set a movement flag rather than do movement in the keyPressed() function, indeed. Whether or not you use an array for this doesn't matter for now. Let's just say that, when the left button is pressed, you set player 1's moveLeft boolean to true, and when you release that button (I assume you can use the keyReleased() function for that) you set it to false.

In your player's update function, you check for this boolean, and move the character accordingly. That should do the trick.
Create-ivity - a game development blog Mouseover for more information.
I think I understand what you're saying, but when I try it, the characters FLY across the screen. I think that the loop happens several times when I press it (even every quickly) and that's what causes it, but I don't really know about that. Here's what I tried:
//imports herepublic class LIBnationGame extends JApplet implements Runnable{	Thread GameRun;	//some variables are here, not needed for this	private boolean GameRunning	private boolean p1moveRight, p2moveLeft; 	//more variables here	KeyListener Controller;/**The control movements for a player */	class Controls implements KeyListener	{/**Unused Method *@param the key typed */		public void keyTyped (KeyEvent typed)		{		}/**Controls the characters *@param the key pressed */		public void keyPressed (KeyEvent pressed)		{			if(pressed.getKeyCode() == KeyEvent.VK_D)				p1moveRight = true;			if(pressed.getKeyCode() == KeyEvent.VK_L)				p2moveLeft = true;		}/**Stops Character movement *@param the key released */		public void keyReleased (KeyEvent released)		{			if(released.getKeyCode() == KeyEvent.VK_D)				p1moveRight = false;			if(released.getKeyCode() == KeyEvent.VK_L)				p2moveLeft = false;		}	}/**Initializes the game by loading all necessary files */	public void init ()	{		setSize (APPLET_WIDTH, APPLET_HEIGHT);		background = getImage (getDocumentBase(), level+".jpg");		music = getAudioClip (getDocumentBase(), level+".au");		backbuffer = createImage(APPLET_WIDTH, APPLET_HEIGHT);      	        backg = backbuffer.getGraphics();      	        Stringmaker = (Graphics2D) backg; //helps with context		context = Stringmaker.getFontRenderContext(); //helps with drawP1&P2		backg.setFont (font);		Controller = new Controls();		GameRun = new Thread(this);	}/**Starts the game by drawing the screen and looping the music */	public void start ()	{		GameRunning = true;		p1 = new Player(name1, p1width, p1height, 1, health, p1atk, p1def, p1speed, p1range);		p2 = new Player(name2, p2width, p2height, 2, health, p2atk, p2def, p2speed, p2range);		music.loop();		addKeyListener(Controller);		GameRun.start();	}/**Runs a game loop to for the game to occur in */ 	public void run () 	{ 		while(GameRunning) 		{ 			update(); 			repaint(); 		} 		removeKeyListener(Controller); 	}/**Handles all the game logic and movements of the characters */	public void update ()	{		if(p1moveRight)			p1.moveRight();		if(p2moveLeft)			p2.moveLeft();		if(p1.isDead() && p2.isDead())		{			victory = "It's a Tie!";			GameRunning = false;		}		else if(p1.isDead())		{			victory = name2+" has won.";			GameRunning = false;		}		else if(p2.isDead())		{			victory = name1+" has won.";			GameRunning = false;		}	}/**Draws the screen *@param screen the screen that is drawn on */	public void paint (Graphics screen)	{		update (screen);	}/**Method used by paint to prevent flickering *@param screen the screen that the screen is drawn on */	public void update (Graphics screen) 	{		backg.drawImage(background, 0, 0, this);      	drawP1();      	drawP2();      	if(!GameRunning)      	{      		backg.setColor(Color.RED);      		backg.drawString (victory, 187, 250);      	}      	screen.drawImage(backbuffer, 0, 0, this );   	}//Game continues but I don't think the problem is in there


[Edited by - Mossflower on December 14, 2006 9:50:21 PM]

This topic is closed to new replies.

Advertisement