Jump to content

java game

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
javaman

javaman

    Newbie

  • Members
  • PipPip
  • 12 posts
Hi Guys,
I am trying to create a game of a two way traffic with a human trying to move between the cars to the other side without being hit by a car.

I can detect the collisions, but the main problem is my cars don't move. what maybe the problem?
another how can one mimics a person in java? i.e when i press the keys to move the player, the person act like he is really moving(right now, i'm jst using a picture block to represent a player). example codes will do.

any other improvement on my code is highly appreciated.

the code:

bottom lane cars:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package twowaytrafficgame;

/**
 *
 * @author Administrator
 */
public class BottomLaneCar extends Car {

    public int x,y;

    public BottomLaneCar(int x0, int y0, String c)
    {
        super(x0,y0,c);
     }
    public void move() {
        
        if (x < 0)
         x = 400;
         x -= 1;
    }

}

car class:
package twowaytrafficgame;

import java.awt.Image;
import java.awt.Rectangle;

import javax.swing.ImageIcon;


public abstract class Car {

  

    private int x;
    private int y;
    private int width;
    private int height;
    private boolean visible;
    private Image image;

    public Car(){}
    public Car(int x, int y, String cars) {

        ImageIcon ii = new ImageIcon(this.getClass().getResource(cars));
        image = ii.getImage();
        width = image.getWidth(null);
        height = image.getHeight(null);
        visible = true;
        this.x = x;
        this.y = y;
    }


    

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

   public void setVisible(Boolean visible) {
        this.visible = visible;
    }

    public Image getImage() {
        return image;
    }

    public Rectangle getBounds() {
        return new Rectangle(x, y, width, height);
    }
}

game panel:

package twowaytrafficgame;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.Timer;


public class GamePanel extends JPanel implements ActionListener {

    private Timer timer;
    private Player person;
    private ArrayList lowerlane, upperlane;
    private boolean ingame;
    private int B_WIDTH;
    private int B_HEIGHT;

   private String cars1 = "car.png";
    private String cars2 = "car2.png";

    private int[][] posL = {
        {10,200},{200,200}, {400,200}, {600, 200}, {900,200}
    };
    private int[][] posU = {
        {150,300},{20,300},{301,300},
        {650,300},{800,300},{980, 300},
        {1010,300},{1200,300}
     };

    public GamePanel() {

        addKeyListener(new TAdapter());
        setFocusable(true);
        setBackground(Color.white);
        setDoubleBuffered(true);
        ingame = true;

        //setSize(800, 600);

        person = new Player();

        initL();
        initU();

        timer = new Timer(5, this);
        timer.start();
    }

    public void addNotify() {
        super.addNotify();
        B_WIDTH = getWidth();
        B_HEIGHT = getHeight();
    }

    public void initL() {
        lowerlane = new ArrayList();

        for (int i=0; i<posL.length; i++ ) {
            lowerlane.add(new BottomLaneCar(posL[i][0], posL[i][1],cars2 ));
        }
    }
    public void initU() {
        upperlane = new ArrayList();

        for (int i=0; i<posU.length; i++ ) {
            upperlane.add(new UpperLaneCar(posU[i][0], posU[i][1],cars1));
        }
    }



    public void paint(Graphics g) {
        super.paint(g);

        Graphics2D g2 = (Graphics2D) g;
        Graphics2D g3 = (Graphics2D) g;
        Graphics2D g4 = (Graphics2D) g;
        Line2D lin1 = new Line2D.Float(-1, 180, 8000, 180);
        g2.setColor(Color.red);
        g2.draw(lin1);
        Line2D lin2 = new Line2D.Float(-1, 270, 8000, 270);
        g3.setColor(Color.black);
        g3.draw(lin2);
        Line2D lin3 = new Line2D.Float(-1, 370, 8000, 370);
        g4.setColor(Color.red);
        g4.draw(lin3);
        

        if(ingame) {

            Graphics2D g2d = (Graphics2D)g;
            Graphics2D g22d = (Graphics2D)g;
            Graphics2D g222d = (Graphics2D)g;


           if (person.isVisible())
           g2d.drawImage(person.getImage(), person.getX(), person.getY(),this);

            for (int i = 0; i < lowerlane.size(); i++) {
                BottomLaneCar a = (BottomLaneCar)lowerlane.get(i);
                g22d.drawImage(a.getImage(), a.getX(), a.getY(), this);
            }

             for (int i = 0; i < upperlane.size(); i++) {
                UpperLaneCar b = (UpperLaneCar)upperlane.get(i);
                g222d.drawImage(b.getImage(), b.getX(), b.getY(), this);
            }
            g2d.setColor(Color.WHITE);
           


        }
        else {
            String msg = "Game Over";
            Font small = new Font("Arial", Font.BOLD, 18);
             g.setColor(Color.black);
             g.setFont(small);
             g.drawString(msg, 350,160);
            }

        Toolkit.getDefaultToolkit().sync();
        g.dispose();
        
    }

    
    
   

    public void actionPerformed(ActionEvent e) {

       if (person.getY()== 50)
            person.y = 500;
               

      
        for (int i = 0; i < lowerlane.size(); i++) {
            BottomLaneCar a = (BottomLaneCar) lowerlane.get(i);
            a.move();
                
        }

        for (int k = 0; k < upperlane.size(); k++) {
          UpperLaneCar b = (UpperLaneCar) upperlane.get(k);
              b.move();
      }
        person.move();
        checkCollisions();
        repaint();
    }

    public void checkCollisions() {

        Rectangle r3 = person.getBounds();

        for (int j = 0; j<lowerlane.size(); j++) {
            BottomLaneCar a = (BottomLaneCar) lowerlane.get(j);
            Rectangle r2 = a.getBounds();
            if(r3.intersects(r2)){
                ingame = false;
            }
        }
        for (int i = 0; i<upperlane.size(); i++) {
            UpperLaneCar b = (UpperLaneCar) upperlane.get(i);
            Rectangle rr = b.getBounds();
            if (r3.intersects(rr)) {
                //person.setVisible(false);
               // b.setVisible(false);
                ingame = false;
            }
        }

        
    }


private class TAdapter extends KeyAdapter {

        public void keyReleased(KeyEvent e) {
            person.keyReleased(e);
        }

        public void keyPressed(KeyEvent e) {
            person.keyPressed(e);
        }
    }
}

player:

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

package twowaytrafficgame;

/**
 *
 * @author Administrator
 */
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;


import javax.swing.ImageIcon;

public class Player {

    private String person = "person.png";

    private int dx;
    private int dy;
    private int x;
    public int y;
    private int width;
    private int height;
    private boolean visible;
    private Image image;
   

    public Player() {
        ImageIcon ii = new ImageIcon(this.getClass().getResource(person));
        image = ii.getImage();
        width = image.getWidth(null);
        height = image.getHeight(null);
        visible = true;
        x = 400;
        y = 600;
    }


    public void move() {

        x += dx;
        y += dy;

        if (x < 1) {
            x = 1;
        } else if(x > 770)
        {
            x = 770;
        }


        if (y > 400) {
            y = 400;
        }
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public Image getImage() {
        return image;
    }

   
   // public void setVisible(boolean visible) {
  //      this.visible = visible;
  // }

   public boolean isVisible() {
       return visible;
    }

    public Rectangle getBounds() {
        return new Rectangle(x, y, width, height);
    }

    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

       if (key == KeyEvent.VK_LEFT) {
            dx = -1;
        }

        if (key == KeyEvent.VK_RIGHT) {
            dx = 1;
        }

        if (key == KeyEvent.VK_UP) {
            dy = -1;
        }

        if (key == KeyEvent.VK_DOWN) {
            dy = 1;
        }
    }

    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();

        if (key == KeyEvent.VK_LEFT) {
            dx = 0;
        }

        if (key == KeyEvent.VK_RIGHT) {
            dx = 0;
        }

        if (key == KeyEvent.VK_UP) {
            dy = 0;
        }

        if (key == KeyEvent.VK_DOWN) {
            dy = 0;
        }
    }
}


game class:


package twowaytrafficgame;

import javax.swing.JFrame;

public class TwoWayTrafficGame extends JFrame {

    public TwoWayTrafficGame() {

        add(new GamePanel());

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null);
        setTitle("Two Way Traffic Game");
        setResizable(true);
        setVisible(true);
    }

    public static void main(String[] args) {
        new TwoWayTrafficGame();
        
    }
}

upper lane cars:

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

package twowaytrafficgame;

/**
 *
 * @author Administrator
 */
public class UpperLaneCar extends Car {

    int x, y;
    public UpperLaneCar(int x, int y, String c)
    {
        super(x,y,c);
    }



    public void move() {
        if (x > 800)
            x = 0;
        x += 1;
    }

}


#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
You did something wrong with the UpperLaneCar and bottomlanecar.

To draw them you use the getX() and getY() methods of them. Those classes don't have those methods but Car does so Java uses the getX() and getY() of the class Car. In your move method, however, you change the x and y of the class UpperLaneCar and bottomlanecar.

Long story short: your x and y variables in the class Car never change, they only change in upperlanecar and bottomlanecar which you don't use to draw them.

So either add getX() and getY() to the upperlaneCar and lowerLanecar. or remove the x,y variables from the classes UpperLaneCar and bottomlanecar And set the x & y values of the class Car.
2 ways to solve this:
public class BottomLaneCar extends Car {

     public BottomLaneCar(int x0, int y0, String c)
    {
        super(x0,y0,c);
     }
    public void move() {

        if (super.getX() < 0)
         super.setX(400);
         super.setX(super.getX() - 1);
    }
}

OR make x & y 'protected' instead of 'private' and use
public class UpperLaneCar extends Car {

    public UpperLaneCar(int x, int y, String c)
    {
        super(x,y,c);
    }



    public void move() {
        if (x > 800)
            x = 0;
        x += 1;
    }

Then the cars will move. You'll notice that the cars from the upperlane spawn in the middle of the screen ;) bottomlane works fine tho.

I also noticed how you always have to cast when you get something out of an ArrayList. This can be avoided by changing the way you define and create the ArrayList:
private ArrayList<LowerLaneCar> lowerlane;
....
lowerlane = new ArrayList<LowerLaneCar>();

You could make the player move forward automatically so he only has to use left & right. Makes it a bit more challenging :D

#3
javaman

javaman

    Newbie

  • Members
  • PipPip
  • 12 posts

oxano said:

You did something wrong with the UpperLaneCar and bottomlanecar.

To draw them you use the getX() and getY() methods of them. Those classes don't have those methods but Car does so Java uses the getX() and getY() of the class Car. In your move method, however, you change the x and y of the class UpperLaneCar and bottomlanecar.

Long story short: your x and y variables in the class Car never change, they only change in upperlanecar and bottomlanecar which you don't use to draw them.

So either add getX() and getY() to the upperlaneCar and lowerLanecar. or remove the x,y variables from the classes UpperLaneCar and bottomlanecar And set the x & y values of the class Car.
2 ways to solve this:
public class BottomLaneCar extends Car {


     public BottomLaneCar(int x0, int y0, String c)

    {

        super(x0,y0,c);

     }

    public void move() {


        if (super.getX() < 0)

         super.setX(400);

         super.setX(super.getX() - 1);

    }

}

OR make x & y 'protected' instead of 'private' and use
public class UpperLaneCar extends Car {


    public UpperLaneCar(int x, int y, String c)

    {

        super(x,y,c);

    }




    public void move() {

        if (x > 800)

            x = 0;

        x += 1;

    }


Then the cars will move. You'll notice that the cars from the upperlane spawn in the middle of the screen ;) bottomlane works fine tho.

I also noticed how you always have to cast when you get something out of an ArrayList. This can be avoided by changing the way you define and create the ArrayList:
private ArrayList<LowerLaneCar> lowerlane;

....

lowerlane = new ArrayList<LowerLaneCar>();


You could make the player move forward automatically so he only has to use left & right. Makes it a bit more challenging :D

hi oxano,

thanks for the reply.

hm! indeed that would be more challenging, if the player move forward automatically.

what i'm trying to figure out now is if the player fails, under the message "Game over". There is a message "Press any key to continue". then any key pressed will put the player for other try.

I'm not sure which will be fantastic between the two: if the play wins, the message pops out notify a winner and any key pressed again will put him for another try. or if a player crosses the lanes, he is automatically placed in the bottom.

but the problem i've noticed about the second is that if i keep the "UP arrow" pressed after the player is placed at the bottom, will make him bumps in to the cars before i even notice.

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts

Quote

what i'm trying to figure out now is if the player fails, under the message "Game over". There is a message "Press any key to continue". then any key pressed will put the player for other try.
Pretty easy:
GamePanel.java:
private class TAdapter extends KeyAdapter {
        @Override
        public void keyTyped(KeyEvent e) {
            if (!ingame) {
                person = new Player();
                initL();
                initU();
                ingame = true;
            }
        }

        public void keyReleased(KeyEvent e) {
            person.keyReleased(e);
        }

        public void keyPressed(KeyEvent e) {
            person.keyPressed(e);
        }
    }
And add the message "press any key to continue" offcourse
The any key doesn't work with the arrow keys for some reason :(

#5
guiness332

guiness332

    Newbie

  • Members
  • Pip
  • 3 posts
I'm trying to make circles randomly appear then click them, and keep a running count. I can make the circles appear on the scene, but not the other way around? can anyone help