Jump to content

  • Log In with Google      Sign In   
  • Create Account


Code review Pong - Java


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.

  • You cannot reply to this topic
No replies to this topic

#1 axel1994   Members   -  Reputation: 409

Like
0Likes
Like

Posted 24 June 2013 - 02:21 PM

So perhaps an introduction first.

I'm Axel, 19 years old. From Belgium, Europe.

 

This year I was studying for engineering.

But I found that I have an big interest in Programming and the theory behind it.

 

Like lots of "kids", I like games. And making games sounds interesting.

This is an interest I have always had.

 

But now I wanted to test that interest, to know I'm actually serious about it.

 

(But that isn't my only interest, I'm interested in Computer science in general)

 

I did a lot of research this past half year. And I like it, just the fact that lots of people say that there is a big chance that you need to work long hours scares me.

 

This September I'm starting in Computer science. The bachelor is a bit of everything and after that I can still chose what direction I want to take.

(In my university I can chose: multimedia (with focus on game programming, If i saw it correctly), Human-computer interaction (which I don't find that interesting)and Databases (with lots of networking, which looks interesting as well), they also have AI but thats only Master after Master.

Software engineering is included in all programs.

 

I learned python in the engineering courses. An learned Java on my own, I bought a couple books. Read them, made every exercise.

So I started making little programs. And now I made my first "moving" game. 

 

I made it first in Slick. But I wanted to know how to do it without slick.

So I made the following code.

 

I know the code probably sucks, yet I'm still kind of proud.

But you can always improve.

 

I got some other questions and insecurities. (mainly because this year in engineering went really bad for me in certain ways I definitely didn't expect) . But I'll post those in another thread.

 

One note with my code: the gameloop code isn't mine.

I looked on how looping works, tried lots of different methods.

Then I realized that working with something like I have now would be great.

But I didn't know how to begin writing the code. So I looked around, found a great tutorial thread which showed this code.

I do understand every line from it, but it's still copied.

So now (I'm going for another classic like tetris, space invaders or duck hunt) I'm going to write something myself.

Now I know what the theory behind the gameloop is.

 

Thank you for reading/commenting. :)

package Pong_Original_no_slick;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;


public class Mainframe implements MouseListener, KeyListener {

	JFrame window = new JFrame();
	Menu menuscreen = new Menu();
	Pauses pausescreen = new Pauses();
	JLabel text = new JLabel();
	
	private boolean running = true;
	private boolean paused = false;
	
	public static final String gamename = "Original Pong!";
	public static final int menu = 0;
	public static final int play = 1;
	public static final int pause = 2;
	private int menuselect=menu;
	
	private static final int screenwidth = 1000;
	private static final int screenheight = 600;
	
	private String mouse = "no input!";
	
	double x;
	double y;
	
	private static final int panellength = 130;
	private static final int panelwidth = 20;
	private static final int ballsize = 10;
	
	private static final int savetyborder = 20;
	
	private static final int playerx = 20; 
	double playery = 20.0;
	
	private static final int AIx = 960; 
	int AIy = 20;
	
	double ballx = 500.0;
	double bally = 300.0;
	double ballspeedx = -1;
	double ballspeedy = -1;
	
	int scoreplayer = 0;
	int scoreAI = 0;
	
	private static final int scorex = 470;
	private static final int scorey = 40;
	
	Pongscreen pong;
	int addscreen = 0;
	int counter=0;
	
	public static void main(String[] args) {
		new Mainframe();
	}
	
	public Mainframe(){
		window.setTitle(gamename);
		window.setSize(screenwidth+20, screenheight+40);
		
		window.add(menuscreen);
		
		window.setVisible(true);
		window.addMouseListener(this);
		window.addKeyListener(this);
		
		runGameLoop();
	}
	
	private void getcoordinates(){
		Point a = MouseInfo.getPointerInfo().getLocation();
		SwingUtilities.convertPointFromScreen(a, menuscreen);
		x = a.getX();
		y = a.getY();
		
		mouse = "Xpos: " +x+ "Ypos: "+y;
	}
	
	private void updateGame(){
		if (menuselect==menu){
			getcoordinates();
			text.setText(mouse);
			
			menuscreen.add(text);
			
			menuscreen.revalidate();
			window.revalidate();
			
			menuscreen.repaint();
			window.repaint();
		}
		if (menuselect==pause){
			menuscreen.setVisible(false);
			pong.setVisible(false);
			
			window.add(pausescreen);
			
			pausescreen.setVisible(true);
			window.revalidate();
			window.repaint();
		}
		if (menuselect==play){
			menuscreen.setVisible(false);
			pausescreen.setVisible(false);
			
	        moveplayer();
			moveAI();
			moveball();
			collisiondetection();
			
			
		}

	}
	private void drawGame(float interpolation){
	    //gamePanel.setInterpolation(interpolation);
		pong = new Pongscreen(){
            public void paintComponent (Graphics g){
        	    g.setColor(Color.GREEN);
        	    g.drawRect(20, 20, 1000-2*20, 600-2*20);
        	    
        	    String score="player:"+scoreplayer+"  AI:"+scoreAI;
    			g.drawString(score,scorex,scorey);
    		
    			g.fillRect(playerx, (int) playery, panelwidth, panellength); //player
    			g.fillRect(AIx, AIy, panelwidth, panellength); //AI
    		
    			g.fillOval((int) ballx,(int) bally, ballsize, ballsize); //the ball
             }
        };
        
        window.setBackground(Color.BLACK);
        
        if (addscreen==0){
        	window.add(pong);
        	addscreen++;
        }
        
	    pong.revalidate();
	    pong.repaint();
	    
	    window.revalidate();
		window.repaint();
	}
	
	public void runGameLoop(){
		Thread loop = new Thread(){
			public void run(){
				gameLoop();
			}
		};
		loop.start();
	}
	
	private void gameLoop(){
	    final double GAME_HERTZ = 100.0;
	      
	    //Calculate how many ns each frame should take for our target game hertz.
	    final double TIME_BETWEEN_UPDATES = 1000000000 / GAME_HERTZ;
	      
	    //At the very most we will update the game this many times before a new render.
	    //If you're worried about visual hitches more than perfect timing, set this to 1.
	    final int MAX_UPDATES_BEFORE_RENDER = 1;
	      
	    //We will need the last update time.
	    double lastUpdateTime = System.nanoTime();
	      
	    //Store the last time we rendered.
	    double lastRenderTime = System.nanoTime();
	      
	    //If we are able to get as high as this FPS, don't render again.
	    final double TARGET_FPS = 100;
	    final double TARGET_TIME_BETWEEN_RENDERS = 1000000000 / TARGET_FPS;  
	    
		while(running){
			
			double now = System.nanoTime();
	        int updateCount = 0;
	         
	        if (!paused){
	        	//Do as many game updates as we need to, potentially playing catchup.
	            while( now - lastUpdateTime > TIME_BETWEEN_UPDATES && updateCount < MAX_UPDATES_BEFORE_RENDER ){
	               updateGame();
	               lastUpdateTime += TIME_BETWEEN_UPDATES;
	               updateCount++;
	            }
	            //If for some reason an update takes forever, we don't want to do an insane number of catchups.
	            //If you were doing some sort of game that needed to keep EXACT time, you would get rid of this.
	            if ( now - lastUpdateTime > TIME_BETWEEN_UPDATES)
	            {
	               lastUpdateTime = now - TIME_BETWEEN_UPDATES;
	            }
	         
	            //Render. To do so, we need to calculate interpolation for a smooth render.
	            float interpolation = Math.min(1.0f, (float) ((now - lastUpdateTime) / TIME_BETWEEN_UPDATES) );
	            drawGame(interpolation);
	            //drawGame(interpolation);
	            lastRenderTime = now;
	         
	            //Yield until it has been at least the target time between renders. This saves the CPU from hogging.
	            while ( now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < TIME_BETWEEN_UPDATES)
	            {
	               Thread.yield();
	            
	               //This stops the app from consuming all your CPU. It makes this slightly less accurate, but is worth it.
	               //You can remove this line and it will still work (better), your CPU just climbs on certain OSes.
	               //FYI on some OS's this can cause pretty bad stuttering. Scroll down and have a look at different peoples' solutions to this.
	               try {Thread.sleep(1);} catch(Exception e) {} 
	            
	               now = System.nanoTime();
	            }
	         }
		}
	}
	
	private void moveplayer(){
		counter=0;
		window.addKeyListener(new KeyListener(){
			@Override
			public void keyPressed(KeyEvent e) {
				int source = e.getKeyCode();
				if (source==KeyEvent.VK_UP){
					if ((playery> savetyborder+2)&&(counter<10)){
						playery-=1.2;
						counter++;
					}
				}
				if (source==KeyEvent.VK_DOWN){
					if ((playery<screenheight-savetyborder-panellength)&&(counter<10)){
						playery+=1.2;
						counter++;
					}
				}
			}

			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
	}
	private void moveAI(){
		if ((bally<(AIy+panellength/2))&&(AIy> savetyborder)){ //goes up
			AIy-=1;
		} 
		if ((bally>(AIy+panellength/2))&&(AIy< screenheight-savetyborder-panellength)){ //goes down
			AIy+=1;
		}	
	}
	private void moveball(){
		//give ball movement
		ballx+=ballspeedx;
		bally+=ballspeedy;
	}
	private void collisiondetection(){
		//AI scores
		if (ballx==savetyborder){ 
			ballx=500;
			bally=300;
			scoreAI+=1;
			playsound();
		}
		//player scores
		if (ballx==screenwidth-savetyborder-ballsize){
			ballx=500;
			bally=300;
			scoreplayer+=1;
			playsound();
		}
		//connect with leftpanel
		if ((ballx==savetyborder+panelwidth)&&(bally>playery)&&(bally<playery+panellength)){
			ballspeedx*=-1;
			playsound();
		}
		
		//connect with rightpanel
		if ((ballx==screenwidth-savetyborder-panelwidth-ballsize)&&(bally>AIy)&&(bally<AIy+panellength)){
			ballspeedx*=-1;
			playsound();
		}
		
		//connect with top screen
		if (bally==savetyborder){
			ballspeedy*=-1;
			playsound();
		}
		
		//connect with bottomscreen
		if (bally==screenheight-savetyborder-ballsize){ //player scores
			ballspeedy*=-1;
			playsound();
		}
	}
	private void playsound(){
		try {
	
	        URL url = this.getClass().getClassLoader().getResource("ponga.wav");
	        AudioInputStream song = AudioSystem.getAudioInputStream(url);
	        
	        Clip clip = AudioSystem.getClip();
	        
	        clip.open(song);
	        clip.start();
	     } 
catch (Exception e) {} 
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		if (((330<x) && (x<680)) && ((y>300)&&(y<345))){
			menuselect=play;
		}
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyPressed(KeyEvent e) {
		int source = e.getKeyCode();
		if (source==KeyEvent.VK_SPACE){
			menuselect=pause;
		}
		if (source==KeyEvent.VK_ENTER){
			menuselect=play;
		}
		
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		
	}
}


package Pong_Original_no_slick;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JPanel;

public class Menu extends JPanel{
	
	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		
		setBackground(Color.BLACK);
		
		g.setFont(new Font("default", Font.BOLD, 30));
	    g.setColor(Color.GREEN);
		g.drawString("Welcome to the original Pong game!",260 ,270);
		g.drawString("Press here to play!",375 ,330);
		g.drawRect(330, 300, 350, 45); 
	}
	
}


package Pong_Original_no_slick;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JPanel;

public class Pauses extends JPanel{

	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		
		setBackground(Color.BLACK);
		
		g.setFont(new Font("default", Font.BOLD, 30));
	    g.setColor(Color.GREEN);
		g.drawString("Welcome to the original Pong game!",260 ,270);
		g.drawString("Game is paused, press enter to unpause!",225 ,330);
	}
	
}



package Pong_Original_no_slick;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JPanel;

public class Pongscreen extends JPanel{
	
	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		
		setBackground(Color.BLACK);
	    g.setColor(Color.GREEN);
	    
	    //g.drawRect(savetyborder, savetyborder, screenwidth-2*savetyborder, screenheight-2*savetyborder);
	    g.drawRect(20, 20, 1000-2*20, 600-2*20);
	}

}



"Talk is cheap. Show me the code."

- Linus Torvalds

Sponsor:



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