Jump to content

  • Log In with Google      Sign In   
  • Create Account


help/follow me evolve as a programmer[starting with Pong]!


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • This topic is locked This topic is locked
22 replies to this topic

#1 timgranstrom   Members   -  Reputation: 415

Like
1Likes
Like

Posted 10 April 2013 - 01:17 PM

Evolving as a programmer -- An active journal of my progress

 

LINK TO THE JOURNAL/BLOG

 

 

Hello! My name is Tim, I'am a first year computer engineer from sweden.

 

This year I learnt the basics of programming. That is, learning to crawl(learning programming basics using Python) and learning how to almost walk (learning some of the basics of object-oriented programming using Java).

 

I just finished the Java course, and found it highly entertaining. I do love programming, and can sit for hours just coding to see what I can do.

 

Already during the Python course, I felt that I wanted to create some type of game. But at that time, my programming experience was far too inferior to even think of anything graphical. But I still did not give in, and decided that the best way to learn was to try. So I made a very simple and meaningless(story-wise) text-based game that simply relied on inputing pre-determined words to move the game ahead.

 

This was fine, although looking back, it was ofcourse horribly coded. But we all start somewhere! sadly I no longer have the "game"-file.

 

However!


2 months after the Python course was finished, the Java course started, opening up a whole new world of impressions, resources and experiences. I loved it.

 

We learnt the basics of Java and widened our experience with the language every day.

 

My passion for wanting to make some type of game, any game. Drove me to go far beyond the basic lectures of our Java course.

And I started reading articles, forum posts, watching youtube tutorials etc. trying to learn more about where I should start and HOW I should start.

 

This brought me to a Java library for making 2d game, named slick2d.

For the last 2 months I have been familiarising myself with the library, learning about how to handle basic inputs, loading sprites, making simple(and without doubt, highly innefective) collission detections etc.

 

I've started on multiple projects, which naturally has led to me not getting anything done and probably only making my programming experience slow down much more then it has to.

 

(Note that I'am familiar with 2d game development from younger days, using RPG maker XP. But never did any scripting in it.)

 

I've been reading quite a hand full of articles here at gamedev.net the past 2-3 weeks, and found them very interesting and educational.

But I still feel that I'am too "wet behind my ears" to truly understand and implement the ideas and concepts from the articles that I've read.

 

This brings me to the topic.

I read a very interesting article here a few days ago. (Klick here to read it!).

 

It basicly said that in order to truly learn and evolve during your first steps as a game developer, you need to get one game done a time.
Not bothering making the biggest most innovative and advanced game ever built.

And as you complete game, you step up the difficulty each time.

 

So I decided, hey! This is exactly what I need to do. (with my own little twist of the whole idea ofcourse).

 

So 2 days ago, I started making a simple pong game using the slick2d and lwgl library for Java.

It currently containts the following:

  • Movable Brick
  • Moving Ball (randomly generated at start where it will move first)
  • Poor collission detection
  • score keeping
  • accelerating velocity of ball and brick based on number of times ball hits something (brick or walls)

 

What it's missing as far as I can imagine right now (Listed in order I believe it should be added):

  1. Object orientation (Everything is basicly just in one class atm)
  2. keep variables(data) and methods(behavior) of an object isolated within its own class.   (added thanks to warnexus)
  3. Better input control/implementation
  4. better and more general collission detection
  5. enemy ai
  6. Probably something more that I've forgotten.

As you can see, the list is quite tall and large(in amount of work that has to be done).

 

My largest concern for the moment is how I should make it better object oriented.

For example, I know that in general I should make something like an entity class and then make a ball class and playerclass (and ai when the time comes) that inherits the entity class. This in it's turn, leads me to reason that the entity class should be abstract.

 

However, this is a problem for me because I'am not sure how I should make the entity class. Should it contain just a little thing, like an id method and something more, or should it be alot of code in it that handels alot of stuff. And then, if I have a playerclass for example, how would it handle inputs? So many questions...

 

Thats why I thought that maybe if I made this topic here, I would get help along the way (starting with this Pong game). And as I learn, get help and improve the game. I'll post my progress and how I did it.

 

This way, I will document my experiences and maybe(hopefully) they will help someone else in a common situation.

That is why, naturally:

 

All source code will be shared.

 

I will however, only have the latest "code build" available in this topic, but you can follow my active journal where I will document everything, including sourcecode for each build. ( thanks to ultramailman and j-locke for recomending making an actual journal instead of uploading everything in this topic.)

 

I hope the people of this community read this topic and help me in my progress of becoming a better programmer and game developer.

Any comments or questions are highly appreciated and I hope we all can help each other!

 

Now lets get busy!

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

PONG - VERSION 1 (THE BEGINNING)

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

Pictures:

pong V1  1
pong V1  2

 

Code:

 

GameSetup (basicly the window that the game is in)

package engine;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;

public class GameSetup extends StateBasedGame {
	private static int width = 720;
	private static int height = (width / 12 * 9);
	public GameSetup(String name) {
		 super("Main Game");
		
	}
	
	public static void main(String args[]) {
        AppGameContainer app;
        try {
            app = new AppGameContainer(new GameSetup("Pong"));
            app.setDisplayMode(width, height, false);
            app.start();
        } catch (SlickException ex) {
            ex.printStackTrace();
        }
    }

	@Override
	public void initStatesList(GameContainer gc) throws SlickException {
		this.addState(new PongGame());
		
	}

}

 

PongGame (The actual game)

package engine;

import java.util.Random;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.KeyListener;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

public class PongGame extends BasicGameState implements KeyListener {
	
	private boolean gameStarted = false;
	private Random randomBool;
	private String start = "A self-educational game by Tim Granström\n\n         Press SPACE to start game.";
	private int width;
	private int height;
	private float pongY = 150.0f;
	private int pongLength = 55;
	private float velocityBall = 0.3f;
	private float velocityPlayer = 0.3f;
	private float ballX = -600.0f;
	private float ballY = -150.0f;
	private Input input;
	private boolean goLeft = true;
	private boolean goDown = true;
	private int score = 0;
	private int bestScore = 0;
	private String scoreBoard = "Current Score: ";
	private String scoreBestBoard = "Best Score: ";

	public void init(GameContainer gc, StateBasedGame sbg)
			throws SlickException {
		gc.setTargetFrameRate(60);
		input = gc.getInput();
		width = gc.getWidth();
		height = gc.getHeight();
		randomBool = new Random();

	}

	public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
			throws SlickException {

		// draw and color the brick, walls and ball.
		g.setColor(Color.white);
		g.drawString(scoreBoard+score, 85, 10);
		g.drawString(scoreBestBoard+bestScore, 280, 10);
		g.drawString(start, (width/2)-150, (height/2)-40);
		g.fillRect(5, pongY, 7, pongLength);
		g.fillRect(0, 0, width, 8);
		g.fillRect(0, height - 8, width, 8);
		g.fillRect(width - 8, 0, 8, height);
		g.setColor(Color.blue);
		g.fillOval(ballX, ballY, 15, 15);

	}

	public void update(GameContainer gc, StateBasedGame sbg, int delta)
			throws SlickException {
		
		if(!gameStarted){
		if (input.isKeyDown(Input.KEY_SPACE)) {
			goLeft = randomBool.nextBoolean();
			goDown = randomBool.nextBoolean();
			ballX = 600.0f;
			ballY = 150.0f;
			gameStarted = true;
		}
		}
		if(gameStarted){
		start = "";
		
		// move brick up
		if (input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_W)) {
			if (pongY > 8) {

				pongY -= velocityPlayer * delta;
			}
		}
		// move brick down
		if (input.isKeyDown(Input.KEY_DOWN) || input.isKeyDown(Input.KEY_S)) {
			if (pongY < height - (8 + pongLength)) {
				pongY += velocityPlayer * delta;
			}
		}

		// check if ball collide with brick on left.
		if (collideXLeft()) {
			goLeft = false;
		}

		// check if ball collide on right
		if (collideXRight(width - (15 + 10))) {
			score++;
			goLeft = true;
		}
		
		if(collideYDown()){
			goDown = false;
		}
		if(collideYUp()){
			goDown = true;
		}

		// if ball is moving to the left
		if (goLeft == true) {
			ballX -= velocityBall * delta ;
		}
		// if ball is moving to the right
		if (goLeft == false) {

			ballX += velocityBall * delta;
		}
		
		// if ball is moving up
		if (goDown == false){
			ballY -= velocityBall * delta;
		}
		
		// if ball is moving down
		if (goDown == true){
			ballY += velocityBall * delta;
		}
		
		if(ballX<0){
			if(score > bestScore){
				bestScore = score;
			}
			score = 0;
			velocityBall = 0.3f;
			ballX = 600.0f;
			ballY = 150.0f;
			gameStarted = false;
		}
		}

	}

	private boolean collideXLeft() {

		if (pongY - 15 < ballY & ballY < pongY + pongLength+15) {

			if (ballX < 13 & ballX > 6) {
				velocityBall += 0.0015f;
				velocityPlayer += 0.0013f;
				return true;
			} 
			else {
				return false;
			}
		}
		else {
			return false;
		}

	}

	private boolean collideXRight(int widthEdge) {
		if (ballX > widthEdge) {
			velocityBall += 0.001f;
			velocityPlayer += 0.0008f;
			return true;
		} else {
			return false;
		}

	}
	
	private boolean collideYDown() {
		if (ballY > height-8-20) {
			velocityBall += 0.001f;
			velocityPlayer += 0.0008f;
			return true;
		} else {
			return false;
		}

	}

	private boolean collideYUp() {
		if (ballY < 8) {
			velocityBall += 0.001f;
			velocityPlayer += 0.0008f;
			return true;
		} else {
			return false;
		}

	}
	
	@Override
	public int getID() {
		return 0;
	}

}

 

Eclipse Project file:

Here

 

 

Thank you for your time!

 

Cheers.
Tim.


Edited by timgranstrom, 11 April 2013 - 02:39 AM.


Sponsor:

#2 warnexus   Prime Members   -  Reputation: 1245

Like
1Likes
Like

Posted 10 April 2013 - 01:41 PM

It's nice you got the game to set up correctly. You're correct, you do need a ball class and Player class. You also need a brick(more appropriately called a paddle in Pong or in Breakout) class. So something like this:

 

4 classes

Ball 

Game

Player

Paddle

ScoreMenu

 

It's far more important than going any further in your game development: to keep your variables(data) and methods(behavior) of an object isolated within its own class. This should be the next best step. This will create a manageable code base and allow you to traverse through the code base much easier no matter how many classes made up the game.

 

Nice work and good luck!


Edited by warnexus, 10 April 2013 - 01:41 PM.


#3 timgranstrom   Members   -  Reputation: 415

Like
0Likes
Like

Posted 10 April 2013 - 01:56 PM

Thank you very much for you reply!

 

you do need a ball class and Player class. You also need a brick(more appropriately called a paddle in Pong or in Breakout) class.

 

I see what you mean!

 

Did I understand you correctly that this Paddle is the actual "brick" in my case, and that it should be controlled by implementing the Player class?

 

In my head, I imagined the Player class to include/be the actual Paddle.
But if this is ineffective or bad for other reasons, I'd love an explanation on why!

 

Also, would making an Entity class be 'overkill' or not so nessecary in my case?
 

keep your variables(data) and methods(behavior) of an object isolated within its own class. This should be the next best step.

 

I completely get what you mean! The list has been edited accordingly.


Edited by timgranstrom, 10 April 2013 - 01:57 PM.


#4 ultramailman   Prime Members   -  Reputation: 1463

Like
0Likes
Like

Posted 10 April 2013 - 04:52 PM

Hmm why not make a journal using the "Developer Journal" feature of this site?

http://www.gamedev.net/blogs

#5 warnexus   Prime Members   -  Reputation: 1245

Like
0Likes
Like

Posted 10 April 2013 - 09:45 PM

Thank you very much for you reply!

 

you do need a ball class and Player class. You also need a brick(more appropriately called a paddle in Pong or in Breakout) class.

 

I see what you mean!

 

Did I understand you correctly that this Paddle is the actual "brick" in my case, and that it should be controlled by implementing the Player class?

 

In my head, I imagined the Player class to include/be the actual Paddle.
But if this is ineffective or bad for other reasons, I'd love an explanation on why!

 

Also, would making an Entity class be 'overkill' or not so nessecary in my case?
 

>

keep your variables(data) and methods(behavior) of an object isolated within its own class. This should be the next best step.

 

I completely get what you mean! The list has been edited accordingly.

Yes it is called a paddle. It would be weird to whack a ball with a brick. happy.png Might be heavy and difficult to play the game.

 

It is actually the other way around. If you think about it in the object oriented sense: each player should have their own paddle and their own score. You can make the paddle object be inside the Player class based on what I said previously. I would not make the paddle be the actual player because the player is controlling the paddle and the player is not necessarily a paddle.



#6 j-locke   Members   -  Reputation: 793

Like
0Likes
Like

Posted 10 April 2013 - 09:47 PM

Hmm why not make a journal using the "Developer Journal" feature of this site?

http://www.gamedev.net/blogs

I agree with this. Sharing your experiences is a very cool idea. But a forum will be a pretty poor way to do that about the time you're posting your 3rd update. A blog or journal sounds like exactly what you need.

 

GameDev has dev journals available. Google has Blogger available. WordPress has WordPress.com blogs available. And all for free. Pick one and go to town. And don't forget to share a link to it, where ever you end up posting at.



#7 timgranstrom   Members   -  Reputation: 415

Like
0Likes
Like

Posted 11 April 2013 - 02:44 AM

Hmm why not make a journal using the "Developer Journal" feature of this site?

http://www.gamedev.net/blogs

 

 

I agree with this. Sharing your experiences is a very cool idea. But a forum will be a pretty poor way to do that about the time you're posting your 3rd update. A blog or journal sounds like exactly what you need.



GameDev has dev journals available. Google has Blogger available. WordPress has WordPress.com blogs available. And all for free. Pick one and go to town. And don't forget to share a link to it, where ever you end up posting at.

 

 

Good idea, thanks! I have made a journal that I will update, and I will only "update" this topic with the latest builds, instead of adding them all into the topic. This was very reasonable smile.png

 

link can be found here and in the starting-post.

 

 

Thank you very much for you reply!

 

you do need a ball class and Player class. You also need a brick(more appropriately called a paddle in Pong or in Breakout) class.

 

I see what you mean!

 

Did I understand you correctly that this Paddle is the actual "brick" in my case, and that it should be controlled by implementing the Player class?

 

In my head, I imagined the Player class to include/be the actual Paddle.
But if this is ineffective or bad for other reasons, I'd love an explanation on why!

 

Also, would making an Entity class be 'overkill' or not so nessecary in my case?
 

"1365622876">&gt

;

keep your variables(data) and methods(behavior) of an object isolated within its own class. This should be the next best step.

lockquote>

 

I completely get what you mean! The list has been edited accor

dingly.

Yes it is called a paddle. It would be weird to whack a ball with a brick. happy.png Might be heavy and difficult to play the game.

 

It is actually the other way around. If you think about it in the object oriented sense: each player should have their own paddle and their own score. You can make the paddle object be inside the Player class based on what I said previously. I would not make the paddle be the actual player because the player is controlling the paddle and the player is not necessarily a paddle.

 

Haha yes that seems to make sense. ;)

 

Ah I see. Then, the Player class needs to handle the input then?



#8 warnexus   Prime Members   -  Reputation: 1245

Like
0Likes
Like

Posted 11 April 2013 - 11:11 AM

Let the game class handle the input

#9 timgranstrom   Members   -  Reputation: 415

Like
0Likes
Like

Posted 11 April 2013 - 11:17 AM

yes, I figured that out just a few minutes ago, I'm just about to start making an abstract Entity class and a Player class!



#10 timgranstrom   Members   -  Reputation: 415

Like
0Likes
Like

Posted 12 April 2013 - 02:45 AM

I've gotten my entities to work, but I'am having problem with the collision detection..

 

The problem is that, when I check if the player and the wall collide, it seems like it can't keep up with the collision detection..

 

For example: sometimes the paddle stops at the wall, sometime it doesn't, and it seems to be directly related to how "fast" the player moves.

package engine;

import engine.entities.Ball;
import engine.entities.Player;
import engine.walls.Wall;

public class CollisionDetection {
	private float x1,x2,y1,y2;
	
	
	//Check if ball and player entity intersect.
	public boolean collidesWith(Ball b, Player p){
		this.x1 = b.getX();
		this.y1 = b.getY();
		this.x2 = p.getX();
		this.y2 = p.getY();

		return collideCheck(b.getWidth(),p.getWidth(),b.getHeight(),p.getHeight());
		
	}
	
	//not finished.
	public boolean collidesWith(Ball b, Wall w){
		this.x1 = b.getX();
		this.y1 = b.getY();
		this.x2 = w.getX();
		this.y2 = w.getY();
		
		return true;
	}
	
	
	//Check if player entity and wall obstacle intersect
	public boolean collidesWith(Player p, Wall w){
		this.x1 = p.getX();
		this.y1 = p.getY();
		this.x2 = w.getX();
		this.y2 = w.getY();
		
		return collideCheck(p.getWidth(),w.getWidth(),p.getHeight(),w.getHeight());
		
		
	}
	
	
	//Check if objects intersect
	private boolean collideCheck(float width1,float width2, float height1,float height2){
		
		float deltaX;
		float deltaY;

		deltaX = delta(this.x1,this.x2);
		deltaY = delta(this.y1,this.y2);

		float halfWidth_x1 = width1/2;
		float halfHeight_y1 = height1/2;
		
		float halfWidth_x2 = width2/2;
		float halfHeight_y2 = height2/2;
		
		float gapBetweenX = deltaX - halfWidth_x1 - halfWidth_x2;
		float gapBetweenY = deltaY - halfHeight_y1 - halfHeight_y2;
		
		if(gapBetweenX>0 || gapBetweenY>0){
			return false;
		}
		
		if(gapBetweenX == 0 && gapBetweenY == 0){
			return false;
		}
		
		else{
			return true;
		}
		
	}
	
	//get delta of 2 values.
	private float delta(float x1, float x2){
		
		if(x1>x2){
			return x1-x2;
		}
		else{
			return x2-x1;
		}
		
	}
}


 

Is there a way to make this more effective?

 

Note that

each object (player, wall,ball) holds their current x,y-cords, width and height.

 

The collision detection is loosely based on the first part of this article (Projection along an arbitrary axis).

 

Any help, suggestions or explanations as to why this is happening or how to resolve this I would greatly appreciate. smile.png

 

Also note that the collission check between ball and player is working fine..

 

Is there a better (but still simple) way to do this kind of collision detection?


Edited by timgranstrom, 12 April 2013 - 02:52 AM.


#11 warnexus   Prime Members   -  Reputation: 1245

Like
0Likes
Like

Posted 12 April 2013 - 01:35 PM

The easy way to test collision detection between a ball and a paddle would be to use the Rectangle class built into the Java language. And use that class intersects method. The Rectangle class works well for oval, circle and rectangle shaped object for perfect collision.

 

Something like this:

 

ball.getRectangle().interesects(paddle.getRectangle());

 

The code that test to make sure the paddle does not go off the screen should not depend on the player velocity. It has to do with the position(represented by the x and y coordinates) of your paddle. I find it strange that your paddle sometimes stop at the wall and sometimes it does not. There should be no randomness. You can track the bug using println and see where the problem lies. 

 

The player is not moving. Your Player should only have basic information like "what score does the player?" and "name of the player".

 

Your paddle are moving. So the drawing movement code and the variables associated with it should be in Paddle class not the Player Class. 


Edited by warnexus, 12 April 2013 - 01:46 PM.


#12 timgranstrom   Members   -  Reputation: 415

Like
0Likes
Like

Posted 13 April 2013 - 05:28 AM

ball.getRectangle().interesects(paddle.getRectangle());

So I wouldn't need a collision class then?

 

You can track the bug using println and see where the problem lies.

 

I will do this! But using the Rectangleclass I think it will solve it self.

 

The player is not moving. Your Player should only have basic information like "what score does the player?" and "name of the player".

hmm okay, but then how will I actually controll the paddle? Basicly the Player class shouldn't be an actual entity then? but rather just a class that holdes these variables?

 

Earlier, you said:

If you think about it in the object oriented sense: each player should have their own paddle and their own score. You can make the paddle object be inside the Player class based on what I said previously. I would not make the paddle be the actual player because the player is controlling the paddle and the player is not necessarily a paddle.

I think that I get that..

I made it so that when I make a player object, a paddle object is always made inside the playerclass aswell. But how should I controll the paddle in the actual game loop if I don't have a way of controlling it in there?

 

This is my Entity code:

package engine.entities;

import org.newdawn.slick.Graphics;

public abstract class Entity {

	//x & y = x-coord & y-coord in game, width & height = width & height of the entity.
	protected float x,y;
	protected float velocity = 0.3f;
	protected int width,height;
	private boolean removed = false;
	
	public Entity(float x, float y){
		this.x = x;
		this.y = y;
	}
	
	public void render(Graphics g){
		
	}

	//Get width of entity
	public int getWidth(){
		return this.width;
	}
	//Get height of entity
	public int getHeight(){
		return this.height;
	}

	//get x-coord
	public float getX(){
		return this.x;
	}
	//get y-coord
	public float getY(){
		return this.y;
	}

	//Get velocity of entity
	public float getVelocity(){
		return this.velocity;
	}
	
	//Set remove-flag for an entity
	public void remove(){
		this.removed = true;
	}
	
	//Check the remove-flag for an entity
	public boolean checkRemoved(){
		return this.removed;
	}
}

This is my Player Code:

package engine.entities;

import org.newdawn.slick.Graphics;

public class Player extends Entity{
	private float xd,yd;
	private boolean goLeft = true; //not used for now
	private boolean goDown = true; // not used for now
	private Paddle paddle;
	
	//Constructor: Every time a Player object is made, a Paddle object is created for it.
	public Player(float x, float y) {
		super(x, y);
		this.width = 7;
		this.height = 55;
		paddle = new Paddle(this.x, this.y, this.width, this.height);
	}
	
	//Updates the actual position of the player
	private void movement(){
		this.x += this.xd*this.velocity;
		this.y += this.yd*this.velocity;
	}
	
	//sets X direction movement of player
	public void setXDir(float xd){
		this.xd = xd;
	}
	
	//sets Y direction movement of player
	public void setYDir(float yd){
		this.yd = yd;
	}
	
	//render the actual player entity(in this case, a paddle is rendered by the player Entity).
	public void render(Graphics g){
		this.movement();
		paddle.move(this.x, this.y);
		paddle.render(g);
		
	}

}

And finally this is my Paddle code:

package engine.entities;

import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;

public class Paddle extends Entity {

	private Color paddleColor = Color.white;
	
	//Constructor.
	public Paddle(float x, float y, int width, int height){
		super(x,y);
		this.width = width;
		this.height = height;
	}
	
	//Move the paddle
	protected void move(float x, float y){
		this.x = x;
		this.y = y;
	}
	
	//set new height of paddle
	protected void setHeight(int height){
		this.height = height;
	}
	
	//set new width of paddle
	protected void setWidth(int width){
		this.width = width;
	}
	
	//renders the paddle graphics.
	public void render(Graphics g){
		g.setColor(this.paddleColor);
		g.fillRect(this.x, this.y, this.width, this.height);
	}
	
}



#13 warnexus   Prime Members   -  Reputation: 1245

Like
0Likes
Like

Posted 13 April 2013 - 11:47 AM

Sure, if you get the collision to work, you can have a collision class if you want to isolate your functionality even further. 

 

To make the paddle move involves 3 things:

1) You would implement a KeyListener interface for your Paddle which is a set of methods associated with the KeyListener interface.

2) Add KeyListener to your Paddle.

3) Once you implemented the KeyListener interface, you need to override the methods from that interface so you can create very own desired effect of what should happen if a user presses a certain key which causes the paddle to move a certain direction.

3) The methods you override from the interface are called automatically for you by the parameter KeyEvent object when your added KeyListener has listened for a KeyEvent generated by the user. 

 

an example of the override method:

 

public void keyPressed(KeyEvent e)

{

 

 

 

Feedback on your code:

1) the boolean variables goLeft and goRight should be in the paddle. Why does player have width and height if your paddle has those variables already? Paddle should have the movement code not the Player.

2) I do not think an Entity class is necessary, it save you an extra class you do not need for a Pong Game. The reason being Paddle has position x,y and width and height but Player do not need these variables in the game. You should be moving and testing collision on the Paddle not the player. Player should only have to keep track of their own score and their own name. 

3) I made a mistake from what I told you yesterday. In this case, since your game has paddle being added into the game then each paddle should hold a Player object for (name and score). So, you were correct, Player object should be inside the Paddle class.


Edited by warnexus, 13 April 2013 - 12:06 PM.


#14 timgranstrom   Members   -  Reputation: 415

Like
0Likes
Like

Posted 13 April 2013 - 03:31 PM

To make the paddle move involves 3 things:

1) You would implement a KeyListener interface for your Paddle which is a set of methods associated with the KeyListener interface.

2) Add KeyListener to your Paddle.

3) Once you implemented the KeyListener interface, you need to override the methods from that interface so you can create very own desired effect of what should happen if a user presses a certain key which causes the paddle to move a certain direction.

3) The methods you override from the interface are called automatically for you by the parameter KeyEvent object when your added KeyListener has listened for a KeyEvent generated by the user.



an example of the override method:



public void keyPressed(KeyEvent e)

{



}

 

The problem with this is the updates, within the paddle it'd look something like this then right? (note I'am using a KeyListener interface from the slick2d library which is slightly different from the KeyListener interface from the Java library.):

 

public void keyPressed(int key, char c) {
			if (key == Input.KEY_W || key == Input.KEY_UP) {
	           this.setYDir(-1*delta); //Moves the paddle up.
	        } else if (key == Input.KEY_S || key == Input.KEY_DOWN) {
	        	this.setYDir(-1*delta); //Moves the paddle down.
	        }
	    }

The problem here is the delta, if I don't update the paddle with the delta I get from the game loop update function, it won't update correctly, and the paddle will move ultra fast..

 

also, if I have a keylistener interface implemented in the paddle object, will it be enough to just create the object in the game loop for it to actually draw and everything?

like, all I need is to put it in the render method of my game loop? I'm not sure about how to think about all of this, and then I'm having a hard time visualising the outcome..


Edited by timgranstrom, 13 April 2013 - 03:32 PM.


#15 timgranstrom   Members   -  Reputation: 415

Like
0Likes
Like

Posted 14 April 2013 - 02:57 PM

1) You would implement a KeyListener interface for your Paddle which is a set of methods associated with the KeyListener interface.

2) Add KeyListener to your Paddle.

3) Once you implemented the KeyListener interface, you need to override the methods from that interface so you can create very own desired effect of what should happen if a user presses a certain key which causes the paddle to move a certain direction.

3) The methods you override from the interface are called automatically for you by the parameter KeyEvent object when your added KeyListener has listened for a KeyEvent generated by the user.



an example of the override method:



public void keyPressed(KeyEvent e)

{



}

 

I need some serious help with the implementation.. I've been trying for 3 hours to no use..

I just can't get it to work..

I've implemented the KeyListener to the paddle.

public class Paddle extends Entity implements KeyListener {

but when I try to add a KeyListener with the

addKeyListener(this);

I only get the error that the method doesn't exist, I've tried using it in the main game loop aswell like this:

this.addKeyListener(paddle);

but to no use.. I'am completely confused why I can't add a listener to it...



#16 warnexus   Prime Members   -  Reputation: 1245

Like
0Likes
Like

Posted 14 April 2013 - 09:40 PM

import java.awt.event.*;
 
I never use slick2d but if you use the code above, your class that imports this library will know about other the functionality of classes in the java awt event library. This event library is needed if you decide to add any features that involves the mouse or the keyboard. If you are using another library, you should still be able to use standard Java library.
 
It seems you already made the paddle move then. The KeyListener interface is one of the steps needed to be implemented to make you be able to move your paddle with keys on your keyboard.
 
On a side note: avoid magic numbers in your code. Pretty much any value in a program that is not assign a variable is a magic number. For example: -1 is a magic number.  You should replace it with a general variable name so other people looking at the thread can help you too. I would not know what -1 mean in your code even though you know what it is.
 
On another side note: do not panic. It will be okay. This is the nature of general programming and programming games. Stick with it and struggle, you will learn a lot from your mistakes. Everyday is a progress. You will later find out, it will be worth it in the end. You might want to have a pencil and a paper handy and trace through your code carefully line by line.
 
A general rule of thumb your game constructor should be the one setting up the game(ie: setup the paddles and ball in the game).
After that your gameloop starts running. Your gameloop should be the method that draws and updates the game objects (paddle,ball,score)


#17 timgranstrom   Members   -  Reputation: 415

Like
0Likes
Like

Posted 15 April 2013 - 12:38 AM

I finally found where the 'addKeyListener()' method was in slick2d, it's in the gamecontainer, which makes sense since the method needs to use a frame!

 

However I'm not sure as to how I should implement it..?

 

since the object doesn't use a gamecontainer, should I send the gamecontainer to the object when I create it?

example:

//Constructor.
	public Paddle(float x, float y, int width, int height,GameContainer gc){
		super(x,y);
		this.width = width;
		this.height = height;
		this.player = new Player();
		gc.getInput().addKeyListener(this);
		
		
	}

 

or should I add it to where I initialize the game loop?

example:

public void init(GameContainer gc, StateBasedGame sbg)
			throws SlickException {
		gc.setTargetFrameRate(60);
		input = gc.getInput();
		width = gc.getWidth();
		height = gc.getHeight();
		randomBool = new Random();
		paddle = new Paddle(5,150,7,55,gc);
		//collision = new CollisionDetection();
		ball = new Ball(ballX,ballY,15,15);
		wallUp = new Wall(0,0, width, 8);
		wallDown = new Wall(0, height - 8, width, 8);
		wallRight = new Wall(width - 8, 0, 8, height);
		gc.getInput().addKeyListener(paddle); //Should the addKeyListener look like this and be here??
	}


#18 warnexus   Prime Members   -  Reputation: 1245

Like
0Likes
Like

Posted 15 April 2013 - 11:11 AM

Although both code would perform the same type of action. 

 

I never used Slick2D, but you could take advantage of inheritance and try creating a Game class that extends GameContainer very much like in Standard Java where you would do code like this : Game extends Canvas.

 

Can you add a paddle onto a GameContainer? If so then you are try something similar like:

 

 

public class Game extends GameContainer
{
 
public void int()
{
 
 
Paddle paddle = new Paddle(x,y,width,height);
getInput().add(KeyListener(paddle);
add(paddle);
}
 
}

 

This should eliminate passing the GameContainer as a parameter to your object or method everytime and make your codebase look more cleaner and well structured. 


Edited by warnexus, 15 April 2013 - 11:41 AM.


#19 timgranstrom   Members   -  Reputation: 415

Like
0Likes
Like

Posted 15 April 2013 - 11:36 AM

I've tried using both of them, but none works.. it seems as if it doesn't really listen and to the object if a key is pressed..

 

I'am not sure what the problem is, I've tried using a simple println to check if it ever recieves anything, but it prints nothing...

 

 

-------EDIT---------

 

I found the problem, I'am now cleaning up the mess!

 

----EDIT 2---------

 

I'am done with build 2 now, it's too late for me to update the journal right now since I want to comment as much as I can about the changes, whats change, and why I've changed it the way I have etc..

 

It's already 10.55PM here and I've got school early tomorrow, but I will try to get the build uploaded and journal updated tomorrow.

 

also, a giant thanks to warnexus who has been alot of help to me when I've hit an obstacle!


Edited by timgranstrom, 15 April 2013 - 02:55 PM.


#20 timgranstrom   Members   -  Reputation: 415

Like
0Likes
Like

Posted 17 April 2013 - 01:00 PM

I've updated the journal with all the new source code and uploaded the eclipse file aswell as pictures of it.

 

I was hoping anyone could check the code out and comment what I did good, bad and what I need to improve etc from your perspective!
This would be a great way for me to learn from it smile.png

I will keep posting in this topic as I progress with the game, I'm sure I'll have a few questions regarding this project!

Thanks!


Edited by timgranstrom, 17 April 2013 - 01:58 PM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS