Author Topic: The MASSIVE Java Game Development Source Code Thread  (Read 23589 times)

Ollie

  • Administrator
  • Legendary Member
  • *****
  • Posts: 1541
    • View Profile
    • TheJavaHub
  • Programming Languages: Java, (X)HTML, CSS & PHP
The MASSIVE Java Game Development Source Code Thread
« on: August 10, 2011, 09:56:35 PM »
Java Game Programming for Beginners - #10 - More Collision Detection

Main.java:
Code: [Select]
package collision;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;

public class Main extends JFrame {
   
    private Image dbImage;
    private Graphics dbg;
   
    int rectX, rectY;
   
    public Main(){
        setSize(400,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);
        addMouseMotionListener(new AL());
    }
   
    @Override
    public void paint(Graphics g){
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }
    public void paintComponent(Graphics g){
        Rectangle r1 = new Rectangle(rectX, rectY, 25, 25);
        Rectangle r2 = new Rectangle(175, 75, 50, 50);
        g.setColor(Color.RED);
        g.fillRect(r2.x, r2.y, r2.width, r2.height);
        g.setColor(Color.BLUE);
        g.fillRect(r1.x, r1.y, r1.width, r1.height);
       
        //Collision
        if(r1.intersects(r2))
            g.drawString("Collision!!", 175, 75);
       
        repaint();
    }
   
    public class AL extends MouseAdapter {
        @Override
        public void mouseMoved(MouseEvent e){
            rectX = e.getX()-12;
            rectY = e.getY()-12;
        }
    }
   
    public static void main(String[] args) {
        Main main = new Main();
    }
}
« Last Edit: August 10, 2011, 10:26:31 PM by Ollie »

Ollie

  • Administrator
  • Legendary Member
  • *****
  • Posts: 1541
    • View Profile
    • TheJavaHub
  • Programming Languages: Java, (X)HTML, CSS & PHP
Java Game Programming for Beginners - #11 - Shooting a Bullet
« Reply #1 on: August 11, 2011, 05:01:17 PM »
Main.java:
Code: [Select]
package javaapplication13;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Shoot extends JFrame {
   
    private Image dbImage;
    private Graphics dbg;
   
    static Ship s1 = new Ship();
       
    public Shoot(){
        setSize(400,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);
        addKeyListener(new AL());
    }
   
    @Override
    public void paint(Graphics g){
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }
    public void paintComponent(Graphics g){
        //Draw the ship
        s1.draw(g);
       
        repaint();
    }
   
    public class AL extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e){
            s1.keyPressed(e);
        }
        @Override
        public void keyReleased(KeyEvent e){
            s1.keyReleased(e);
        }
    }
   
    public static void main(String[] args) {
        Shoot shoot = new Shoot();
        //Threads
        Thread ship = new Thread(s1);
        ship.start();
    }
}

Ship.java:
Code: [Select]
package javaapplication13;

import java.awt.*;
import java.awt.event.*;

public class Ship implements Runnable {
   
    int x, y, xDirection;
   
    public Ship(){
        x = 175;
        y = 275;
    }
   
    public void draw(Graphics g){
        g.setColor(Color.BLUE);
        g.fillRect(x, y, 40, 10);
        g.fillRect(x+18, y-7, 4, 7);
    }
   
    public void move(){
        x += xDirection;
        if(x <= 0)
            x = 0;
        if(x >= 360)
            x = 360;
    }
   
    public void setXDirection(int xdir){
        xDirection = xdir;
    }
   
    public void keyPressed(KeyEvent e){
        int keyCode = e.getKeyCode();
        if(keyCode == e.VK_LEFT){
            setXDirection(-1);
        }
        if(keyCode == e.VK_RIGHT){
            setXDirection(1);
        }
    }
    public void keyReleased(KeyEvent e){
        int keyCode = e.getKeyCode();
        if(keyCode == e.VK_LEFT){
            setXDirection(0);
        }
        if(keyCode == e.VK_RIGHT){
            setXDirection(0);
        }
    }
   
    @Override
    public void run(){
        try{
            while(true){
                move();
                Thread.sleep(5);
            }
        }catch(Exception e){System.err.println(e.getMessage());}
    }
   
}

Ninjason

  • Ninjasonz on PSN
  • Sr. Programmer
  • ****
  • Posts: 359
  • Ninjas are Programmers too...
    • View Profile
  • Programming Languages: Java (Still learning), C++(also learning)
Re: Java Game Programming for Beginners - #11 - Shooting a Bullet
« Reply #2 on: August 11, 2011, 05:04:51 PM »
ty ty ty ty ty ty so much  :D
Ninjas are programmers too...
Ninja Overkill Operations Brigade

Ollie

  • Administrator
  • Legendary Member
  • *****
  • Posts: 1541
    • View Profile
    • TheJavaHub
  • Programming Languages: Java, (X)HTML, CSS & PHP
Re: Java Game Programming for Beginners - #11 - Shooting a Bullet
« Reply #3 on: August 11, 2011, 05:27:23 PM »
ty ty ty ty ty ty so much  :D
There is nothing going on with the code yet, just a ship moving. My tutorial will be out later today :)

Ollie

  • Administrator
  • Legendary Member
  • *****
  • Posts: 1541
    • View Profile
    • TheJavaHub
  • Programming Languages: Java, (X)HTML, CSS & PHP
Java Game Programming for Beginners - #12 - Making Pong
« Reply #4 on: August 12, 2011, 04:46:30 PM »
The complete source code for Pong game!

Main.java
Code: [Select]
package ponggame;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class Main extends JFrame {
   
    //Double buffering
    Image dbImage;
    Graphics dbg;
   
    //Ball objects
    static Ball b = new Ball(193, 143);
   
    //Variables for screen size
    int
    GWIDTH = 400,
    GHEIGHT = 300;
    //Dimension of GWIDTH*GHEIGHT
    Dimension screenSize = new Dimension(GWIDTH, GHEIGHT);
   
    //Create constructor to spawn window
    public Main(){
        this.setTitle("Pong Game");
        this.setSize(screenSize);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        this.setBackground(Color.DARK_GRAY);
        this.addKeyListener(new AL());
    }
   
    public static void main(String[] args){
        Main m = new Main();
        //Create and start threads
        Thread ball = new Thread(b);
        ball.start();
        Thread p1 = new Thread(b.p1);
        Thread p2 = new Thread(b.p2);
        p1.start();
        p2.start();
    }
   
    @Override
    public void paint(Graphics g){
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        draw(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }
    public void draw(Graphics g){
        b.draw(g);
        b.p1.draw(g);
        b.p2.draw(g);
       
        g.setColor(Color.WHITE);
        g.drawString(""+b.p1Score, 15, 50);
        g.drawString(""+b.p2Score, 370, 50);
       
        repaint();
    }
   
    ////////EVENT LISTENER CLASS/////////
    public class AL extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e){
            b.p1.keyPressed(e);
            b.p2.keyPressed(e);
        }
        @Override
        public void keyReleased(KeyEvent e){
            b.p1.keyReleased(e);
            b.p2.keyReleased(e);
        }
    }
    ///////END EVENT LISTENER CLASS/////
   
}
Ball.java
Code: [Select]
package ponggame;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;

public class Ball implements Runnable {
   
    //Gloabal variables
    int x, y, xDirection, yDirection;
   
    //Score
    int p1Score, p2Score;
   
    Paddle p1 = new Paddle(15, 140, 1);
    Paddle p2 = new Paddle(370, 140, 2);
   
    Rectangle ball;
   
    public Ball(int x, int y){
        p1Score = p2Score = 0;
        this.x = x;
        this.y = y;
        //Set ball moving randomly
        Random r = new Random();
        int rDir = r.nextInt(1);
        if(rDir == 0)
            rDir--;
        setXDirection(rDir);
        int yrDir = r.nextInt(1);
        if(yrDir == 0)
            yrDir--;
        setYDirection(yrDir);
        //Create 'ball'
        ball = new Rectangle(this.x, this.y, 7, 7);
    }
   
    public void setXDirection(int xdir){
        xDirection = xdir;
    }
    public void setYDirection(int ydir){
        yDirection = ydir;
    }
   
    public void draw(Graphics g){
        g.setColor(Color.WHITE);
        g.fillRect(ball.x, ball.y, ball.width, ball.height);
    }
   
    public void collision(){
        if(ball.intersects(p1.paddle))
            setXDirection(+1);
        if(ball.intersects(p2.paddle))
            setXDirection(-1);
    }
   
    public void move(){
        collision();
        ball.x += xDirection;
        ball.y += yDirection;
        //Bounce the ball when edge is detected
        if(ball.x <= 0){
            setXDirection(+1);
            p2Score++;
        }
        if(ball.x >= 385){
            setXDirection(-1);
            p1Score++;
        }
        if(ball.y <= 15)
            setYDirection(+1);
        if(ball.y >= 285)
            setYDirection(-1);
    }
   
    @Override
    public void run(){
        try{
            while(true){
                move();
                Thread.sleep(7);
            }
        }catch(Exception e){System.err.println(e.getMessage());}
    }
   
}
Paddle.java
Code: [Select]
package ponggame;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;

public class Paddle implements Runnable {
   
    int x, y, yDirection, id;
   
    Rectangle paddle;
   
    public Paddle(int x, int y, int id){
        this.x = x;
        this.y = y;
        this.id = id;
        paddle = new Rectangle(x, y, 10, 50);
    }
   
    public void keyPressed(KeyEvent e){
        switch(id){
            default:
                System.out.println("Please enter a valid ID in Paddle constructor");
                break;
            case 1:
                if(e.getKeyCode() == e.VK_W){
                    setYDirection(-1);
                }
                if(e.getKeyCode() == e.VK_S){
                    setYDirection(1);
                }
                break;
            case 2:
                if(e.getKeyCode() == e.VK_UP){
                    setYDirection(-1);
                }
                if(e.getKeyCode() == e.VK_DOWN){
                    setYDirection(+1);
                }
                break;           
        }
    }
    public void keyReleased(KeyEvent e){
        switch(id){
            default:
                System.out.println("Please enter a valid ID in Paddle constructor");
                break;
            case 1:
                if(e.getKeyCode() == e.VK_W){
                    setYDirection(0);
                }
                if(e.getKeyCode() == e.VK_S){
                    setYDirection(0);
                }
                break;
            case 2:
                if(e.getKeyCode() == e.VK_UP){
                    setYDirection(0);
                }
                if(e.getKeyCode() == e.VK_DOWN){
                    setYDirection(0);
                }
                break;           
        }
    }
   
    public void setYDirection(int ydir){
        yDirection = ydir;
    }
   
    public void move(){
        paddle.y += yDirection;
        if(paddle.y <= 15)
            paddle.y = 15;
        if(paddle.y >= 250)
            paddle.y = 250;
    }
   
    public void draw(Graphics g){
        switch(id){
            default:
                System.out.println("Please enter a valid ID in Paddle constructor");
                break;
            case 1:
                g.setColor(Color.CYAN);
                g.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
                break;
            case 2:
                g.setColor(Color.PINK);
                g.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
                break;
        }
    }

    @Override
    public void run() {
        try{
            while(true){
                move();
                Thread.sleep(8);
            }
        }catch(Exception e){System.err.println(e.getMessage());}
    }
   
}
« Last Edit: August 12, 2011, 11:03:34 PM by Ollie »

scott bannon

  • Newbie
  • *
  • Posts: 6
    • View Profile
  • Programming Languages: C(++/#) / PHP / BASIC (lost art) / Java (learning) / Several Lesser Scripting Languages
Re: The MASSIVE Java Game Development Source Code Thread
« Reply #5 on: August 12, 2011, 07:36:46 PM »
Ollie, just wanted to post a huge "Thank you!" for your series of Java game tuts. I've learned every language I know via game creation learning, so naturally that's what I was looking for with Java when I decided to jump into it, and while I found and went through several different series out there, many of them were difficult to sit through for various reasons, or spent more time cheerleading for a specific IDE rather than focusing on learning the actual language. So, I feel like I'm getting exactly what I needed with yours and appreciate that.

I also really enjoy your style of video tut making. Especially the fact that you move quick through the lessons, cramming them with good info. You don't seem to ever skip necessary stuff, but you also don't waste time going over the same basic principals over and over again either. I think that's perfect with video tuts since it's simple for someone who misses something to go back to it again, but also prevents those of us who have a basic foundation in programming from getting bored too.

So, kudos and thank you for what you're doing here. I hope you keep them coming.

Ollie

  • Administrator
  • Legendary Member
  • *****
  • Posts: 1541
    • View Profile
    • TheJavaHub
  • Programming Languages: Java, (X)HTML, CSS & PHP
Re: The MASSIVE Java Game Development Source Code Thread
« Reply #6 on: August 12, 2011, 08:09:36 PM »
Ollie, just wanted to post a huge "Thank you!" for your series of Java game tuts. I've learned every language I know via game creation learning, so naturally that's what I was looking for with Java when I decided to jump into it, and while I found and went through several different series out there, many of them were difficult to sit through for various reasons, or spent more time cheerleading for a specific IDE rather than focusing on learning the actual language. So, I feel like I'm getting exactly what I needed with yours and appreciate that.

I also really enjoy your style of video tut making. Especially the fact that you move quick through the lessons, cramming them with good info. You don't seem to ever skip necessary stuff, but you also don't waste time going over the same basic principals over and over again either. I think that's perfect with video tuts since it's simple for someone who misses something to go back to it again, but also prevents those of us who have a basic foundation in programming from getting bored too.

So, kudos and thank you for what you're doing here. I hope you keep them coming.
Wow, all I can say is thank you so much. It means so much to me that you are benefiting from them enough to post such a nice comment :D

Ninjason

  • Ninjasonz on PSN
  • Sr. Programmer
  • ****
  • Posts: 359
  • Ninjas are Programmers too...
    • View Profile
  • Programming Languages: Java (Still learning), C++(also learning)
Re: The MASSIVE Java Game Development Source Code Thread
« Reply #7 on: August 13, 2011, 04:44:24 AM »
Yes thanks Ollie or TheJavaHub which ever one you prefer. I had learn also a great amount from you and hope to learn more and make games beyond pong.
Ninjas are programmers too...
Ninja Overkill Operations Brigade

Randomix

  • Newbie
  • *
  • Posts: 10
    • View Profile
  • Programming Languages: Lua, HTML, Learning JAVA
Re: The MASSIVE Java Game Development Source Code Thread
« Reply #8 on: August 24, 2011, 11:10:57 AM »
-   http://www.youtube.com/user/TheJavaHub#p/c/6E90696571998DC2/4/ysKatUy8FB8


Source Code from 'Java Game Programming for Beginners - #5 - More on Styling your Game'

Code: [Select]

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;




public class JavaGame extends JFrame {
   
    int x, y;
    private Image dbImage;
    private Graphics dbg;
   
Font font = new Font("Arial", Font.BOLD, 15);
   
   
   
   
    public class AL extends KeyAdapter {
       
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if(keyCode== e.VK_LEFT){
                if(x <=4)
                    x=4;
                else
                x+=-5;
               
            }
            if(keyCode== e.VK_RIGHT){
                if(x>=275)
                    x=275;           
                else
                x+=+5;
               
            }
            if(keyCode== e.VK_UP){
                if(y<=25)
                    y=25;
                else
                         
                y+=-5;
               
            }
            if(keyCode== e.VK_DOWN){
                if(y>=260)
                    y=260;
                else
                y+=+5;
               
            }
        }
        public void keyReleased(KeyEvent e) {
           
        }
    }
   
   
   
   
    public JavaGame() {
       
        //Game Propeties
        addKeyListener(new AL());
        setTitle("Tutorial Template");
        setSize(300, 300);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBackground(Color.CYAN);
       
        x=125;
        y=125;
       
    }
    public void paint(Graphics g){
        dbImage = createImage(getWidth(), getHeight());
        dbg= dbImage.getGraphics();      // db
        paintComponent(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }

    public void paintComponent (Graphics g) {
        g.setFont(font);
        g.setColor(Color.white);
        g.drawString("This is a template", 5 ,290);       
        g.setColor(Color.red);
        g.fillOval(x, y, 20, 20);
        repaint();
       
       
       
       
       
       
       
    }
    public static void main(String[] args) {
        new JavaGame();
    }
   
}


If you use NetBeans IDE to compile this then be sure to add the code below to the top

Code: [Select]
package javagame;

To change the the image, please see the next tutorial - The source code will be up soon.

http://www.youtube.com/user/TheJavaHub#p/c/6E90696571998DC2/5/_B5rQB79SzY


Thanks,


Ollie

  • Administrator
  • Legendary Member
  • *****
  • Posts: 1541
    • View Profile
    • TheJavaHub
  • Programming Languages: Java, (X)HTML, CSS & PHP
Re: The MASSIVE Java Game Development Source Code Thread
« Reply #9 on: August 28, 2011, 11:37:59 AM »
Map.java
Code: [Select]
package map;

import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.*;

public class Map extends JFrame{
   
    int
    GWIDTH  = 325,
    GHEIGHT = 250;
    Dimension screenSize = new Dimension(GWIDTH, GHEIGHT);
   
    ImageIcon[] paths = new ImageIcon[140];
    Image[] tiles = new Image[140];
   
    int imageX = 0, imageY = 0;
   
    private void loadTiles(String mapPath){
        try{
            Scanner s = new Scanner(new File(mapPath));
            if(s.hasNext()){
                System.out.println("Map file loaded!");
            }
            else
                System.out.println("Map file is blank! Check map at: "+mapPath);
           
            for(int i = 0; i < paths.length; i++){
                if(s.hasNext()){
                    paths[i] = new ImageIcon(s.next());
                    tiles[i] = paths[i].getImage();
                    if(tiles[i] != null){
                        System.out.println("tiles["+i+"] loaded, ("+paths[i]+")");
                    }
                }
            }
        }catch(FileNotFoundException ex){
            System.err.println(ex.getMessage());
        }
    }
   
    public void drawMap(Graphics g){
        for(Image i : tiles){
            if(imageX > this.getWidth()){
                imageX = 0;
                imageY += 25;
            }
            g.drawImage(i, imageX, imageY, this);
           
            imageX += 25;
        }
    }
   
    @Override
    public void paint(Graphics g){
        drawMap(g);
    }
   
    public Map(){
        //Load Tiles method
        loadTiles("C:/Users/Oliver/Documents/NetBeansProjects/Map/src/map/map.txt");
       
        setSize(screenSize);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        Map m = new Map();
    }
}

Ollie

  • Administrator
  • Legendary Member
  • *****
  • Posts: 1541
    • View Profile
    • TheJavaHub
  • Programming Languages: Java, (X)HTML, CSS & PHP
Java Game Programming for Beginners - #14 - Menus & Buttons For Games
« Reply #10 on: September 10, 2011, 09:22:20 AM »
Remember to add the package at the top of your java file if you create a package!
Ball.java & Paddle.java (Same as the Pong we made earlier)
Click here

Main.java
Code: [Select]
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

public class Main extends JFrame {
   
    //Double buffering
    Image dbImage;
    Graphics dbg;
   
    //Ball objects
    static Ball b = new Ball(193, 143);
   
    //Menu Buttons
    Rectangle startButton = new Rectangle(150, 100, 100, 25);
    Rectangle quitButton = new Rectangle(150, 150, 100, 25);
    //Variables for screen size
    int
    GWIDTH = 400,
    GHEIGHT = 300;
    //Dimension of GWIDTH*GHEIGHT
    Dimension screenSize = new Dimension(GWIDTH, GHEIGHT);
   
    //Create constructor to spawn window
    public Main(){
        this.setTitle("Pong Game");
        this.setSize(screenSize);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        this.setBackground(Color.DARK_GRAY);
        this.addKeyListener(new KeyHandler());
        this.addMouseListener(new MouseHandler());
        this.addMouseMotionListener(new MouseHandler());
    }
   
    public static void main(String[] args){
        Main m = new Main();
    }
   
    @Override
    public void paint(Graphics g){
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        draw(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }
    public void draw(Graphics g){
        //Menu
        g.setFont(new Font("Arial", Font.BOLD, 26));
        g.setColor(Color.WHITE);
        g.drawString("Pong Game!", 125, 75);
        g.setColor(Color.CYAN);
        g.fillRect(startButton.x, startButton.y, startButton.width, startButton.height);
        g.setFont(new Font("Arial", Font.BOLD, 12));
        g.setColor(Color.GRAY);
        g.drawString("Start Game", startButton.x+20, startButton.y+17);
        g.setColor(Color.CYAN);
        g.fillRect(quitButton.x, quitButton.y, quitButton.width, quitButton.height);
        g.setColor(Color.GRAY);
        g.drawString("Quit Game", quitButton.x+20, quitButton.y+17);
        //Game drawings
        b.draw(g);
        b.p1.draw(g);
        b.p2.draw(g);
        //Scores
        g.setColor(Color.WHITE);
        g.drawString(""+b.p1Score, 15, 50);
        g.drawString(""+b.p2Score, 370, 50);
           
       
        repaint();
    }
   
    ////////EVENT LISTENER CLASSES/////////
    public class KeyHandler extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e){
            b.p1.keyPressed(e);
            b.p2.keyPressed(e);
        }
        @Override
        public void keyReleased(KeyEvent e){
            b.p1.keyReleased(e);
            b.p2.keyReleased(e);
        }
    }
    public class MouseHandler extends MouseAdapter {
        @Override
        public void mouseMoved(MouseEvent e){
           
        }
        @Override
        public void mousePressed(MouseEvent e){
           
        }
    }
    ///////END EVENT LISTENER CLASSES/////
   
}

Ollie

  • Administrator
  • Legendary Member
  • *****
  • Posts: 1541
    • View Profile
    • TheJavaHub
  • Programming Languages: Java, (X)HTML, CSS & PHP
Java Game Programming for Beginners - #16 - Creating Basic AI
« Reply #11 on: September 20, 2011, 07:46:06 PM »
Main.java
Code: [Select]
package TheCarePackage;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;

public class Main extends JFrame implements Runnable{
   
    Rectangle player = new Rectangle(30, 50, 25, 25);
    static Rectangle object = new Rectangle(275, 175, 25, 25);
   
    private Image dbImage;
    private Graphics dbg;
   
    int xDirection, yDirection;
   
    public Main(){
        setSize(600,400);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        addKeyListener(new AL());
    }
   
    @Override
    public void paint(Graphics g){
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }
    private void paintComponent(Graphics g) {
        g.setColor(Color.RED);
        g.fillRect(player.x, player.y, player.width, player.height);
        repaint();
    }
   
    public void move(){
        player.x += xDirection;
        player.y += yDirection;
    }
   
    public void setYDirection(int ydir){
        yDirection = ydir;
    }
    public void setXDirection(int xdir){
        xDirection = xdir;
    }
   
    public class AL extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e){
            int keyCode = e.getKeyCode();
            if(keyCode == e.VK_LEFT){
                setXDirection(-1);
            }
            if(keyCode == e.VK_RIGHT){
                setXDirection(1);
            }
            if(keyCode == e.VK_UP){
                setYDirection(-1);
            }
            if(keyCode == e.VK_DOWN){
                setYDirection(1);
            }
        }
        @Override
        public void keyReleased(KeyEvent e){
            int keyCode = e.getKeyCode();
            if(keyCode == e.VK_LEFT){
                setXDirection(0);
            }
            if(keyCode == e.VK_RIGHT){
                setXDirection(0);
            }
            if(keyCode == e.VK_UP){
                setYDirection(0);
            }
            if(keyCode == e.VK_DOWN){
                setYDirection(0);
            }
        }
    }
   
    public static void main(String[] args) {
        Main main = new Main();
        Thread t = new Thread(main);
        t.start();
    }
   
    @Override
    public void run(){
        try{
            while(true){
                move();
                Thread.sleep(5);
            }
        }catch(Exception e){
            System.err.println(e.getMessage());
        }
    }
   
}

Ollie

  • Administrator
  • Legendary Member
  • *****
  • Posts: 1541
    • View Profile
    • TheJavaHub
  • Programming Languages: Java, (X)HTML, CSS & PHP
Java Game Programming for Beginners - #17 - Smart, Path-finding AI
« Reply #12 on: September 20, 2011, 10:56:41 PM »
Main.java
Code: [Select]
package TheCarePackage;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;

public class Main extends JFrame implements Runnable{
   
    static Rectangle player = new Rectangle(30, 50, 25, 25);
    static Rectangle enemy = new Rectangle(275, 175, 16, 16);
   
    private Image dbImage;
    private Graphics dbg;
   
    int xDirection, yDirection;
   
    static AI AI = new AI(enemy);
   
    public Main(){
        setSize(600,400);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setBackground(Color.LIGHT_GRAY);
        addKeyListener(new AL());
    }
   
    @Override
    public void paint(Graphics g){
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }
    private void paintComponent(Graphics g) {
        g.setColor(Color.RED);
        g.fillRect(player.x, player.y, player.width, player.height);
        AI.draw(g);
        repaint();
    }
   
    public void move(){
        player.x += xDirection;
        player.y += yDirection;
    }
   
    public void setYDirection(int ydir){
        yDirection = ydir;
    }
    public void setXDirection(int xdir){
        xDirection = xdir;
    }
   
    public class AL extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e){
            int keyCode = e.getKeyCode();
            if(keyCode == e.VK_LEFT){
                setXDirection(-1);
            }
            if(keyCode == e.VK_RIGHT){
                setXDirection(1);
            }
            if(keyCode == e.VK_UP){
                setYDirection(-1);
            }
            if(keyCode == e.VK_DOWN){
                setYDirection(1);
            }
        }
        @Override
        public void keyReleased(KeyEvent e){
            int keyCode = e.getKeyCode();
            if(keyCode == e.VK_LEFT){
                setXDirection(0);
            }
            if(keyCode == e.VK_RIGHT){
                setXDirection(0);
            }
            if(keyCode == e.VK_UP){
                setYDirection(0);
            }
            if(keyCode == e.VK_DOWN){
                setYDirection(0);
            }
        }
    }
   
    public static void main(String[] args) {
        Main main = new Main();
        Thread t = new Thread(main);
        t.start();
        Thread t1 = new Thread(AI);
        t1.start();
    }
   
    @Override
    public void run(){
        try{
            while(true){
                move();
                Thread.sleep(5);
            }
        }catch(Exception e){
            System.err.println(e.getMessage());
        }
    }
   
}

AI.java
Code: [Select]
package TheCarePackage;

import java.awt.*;
import javax.swing.ImageIcon;

public class AI implements Runnable {
   
    Rectangle AI, target;
   
    int xDirection, yDirection;
   
    boolean resting = false;
   
    Image octoroc;
   
    public AI(Rectangle r, Rectangle t){
        AI = r;
        target = t;
        octoroc = new ImageIcon("C:/Users/Oliver/Documents/NetBeansProjects/AI/src/TheCarePackage/down.gif").getImage();
    }
    public void draw(Graphics g){
        g.setColor(Color.LIGHT_GRAY);
        if(AI != null)
            g.drawRect(AI.x, AI.y, AI.width, AI.height);
        g.drawImage(octoroc, AI.x, AI.y, null);
    }
   
    //Find a path to the target
   
    //Move in that direction
    public void detectEdges(){
        if(AI.x <= 0)
            setXDirection(1);
        if(AI.x >= 600-AI.width)
            setXDirection(-1);
        if(AI.y <= 25)
            setYDirection(1);
        if(AI.y > 400-AI.height)
            setYDirection(-1);
    }
    public void setXDirection(int dir){
        xDirection = dir;
    }
    public void setYDirection(int dir){
        yDirection = dir;
    }
    public void move(){
        AI.x += xDirection;
        AI.y += yDirection;
        if(xDirection == 1)
            octoroc = new ImageIcon("C:/Users/Oliver/Documents/NetBeansProjects/AI/src/TheCarePackage/right.gif").getImage();
        if(xDirection == -1)
            octoroc = new ImageIcon("C:/Users/Oliver/Documents/NetBeansProjects/AI/src/TheCarePackage/left.gif").getImage();
        if(yDirection == 1)
            octoroc = new ImageIcon("C:/Users/Oliver/Documents/NetBeansProjects/AI/src/TheCarePackage/down.gif").getImage();
        if(yDirection == -1)
            octoroc = new ImageIcon("C:/Users/Oliver/Documents/NetBeansProjects/AI/src/TheCarePackage/up.gif").getImage();
    }
    //In Run method, move in that direction and then wait
    @Override
    public void run(){
        try{
            while(true){
                if(!resting){
                    long start = System.currentTimeMillis();
                    long end = start + 3*500;
                    while(System.currentTimeMillis() < end){
                        move();
                        detectEdges();
                        Thread.sleep(10);
                    }
                    resting = true;
                }
                else{
                    Thread.sleep(2000);
                    resting = false;
                }
            }
        }catch(Exception ex){
            System.err.println(ex.getMessage());
        }
    }
   
    public void log(String s){
        System.out.println(s);
    }
}

Matthew

  • Legenda Scintilla
  • Global Moderator
  • Legendary Member
  • *****
  • Posts: 2235
  • Sparked Studios
    • Skype username: matthewj234
    • View Profile
    • The Code Hub
  • Programming Languages: Java, and a few others :P
Re: The MASSIVE Java Game Development Source Code Thread
« Reply #13 on: October 24, 2011, 04:43:47 PM »
Map.java
Code: [Select]
package map;

import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.*;

public class Map extends JFrame{
   
    int
    GWIDTH  = 325,
    GHEIGHT = 250;
    Dimension screenSize = new Dimension(GWIDTH, GHEIGHT);
   
    ImageIcon[] paths = new ImageIcon[140];
    Image[] tiles = new Image[140];
   
    int imageX = 0, imageY = 0;
   
    private void loadTiles(String mapPath){
        try{
            Scanner s = new Scanner(new File(mapPath));
            if(s.hasNext()){
                System.out.println("Map file loaded!");
            }
            else
                System.out.println("Map file is blank! Check map at: "+mapPath);
           
            for(int i = 0; i < paths.length; i++){
                if(s.hasNext()){
                    paths[i] = new ImageIcon(s.next());
                    tiles[i] = paths[i].getImage();
                    if(tiles[i] != null){
                        System.out.println("tiles["+i+"] loaded, ("+paths[i]+")");
                    }
                }
            }
        }catch(FileNotFoundException ex){
            System.err.println(ex.getMessage());
        }
    }
   
    public void drawMap(Graphics g){
        for(Image i : tiles){
            if(imageX > this.getWidth()){
                imageX = 0;
                imageY += 25;
            }
            g.drawImage(i, imageX, imageY, this);
           
            imageX += 25;
        }
    }
   
    @Override
    public void paint(Graphics g){
        drawMap(g);
    }
   
    public Map(){
        //Load Tiles method
        loadTiles("C:/Users/Oliver/Documents/NetBeansProjects/Map/src/map/map.txt");
       
        setSize(screenSize);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        Map m = new Map();
    }
}

I couldnt find the images, so delete this post if I just havent found them, but if anyone else needs them, i have created 3 similar ones:




Psionic

  • Newbie
  • *
  • Posts: 7
    • View Profile
  • Programming Languages: Java , Basic C++ , Basic C
Re: Java Game Programming for Beginners - #11 - Shooting a Bullet
« Reply #14 on: November 26, 2011, 11:38:46 PM »
Main.java:
Code: [Select]
package javaapplication13;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Shoot extends JFrame {
   
    private Image dbImage;
    private Graphics dbg;
   
    static Ship s1 = new Ship();
       
    public Shoot(){
        setSize(400,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);
        addKeyListener(new AL());
    }
   
    @Override
    public void paint(Graphics g){
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }
    public void paintComponent(Graphics g){
        //Draw the ship
        s1.draw(g);
       
        repaint();
    }
   
    public class AL extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e){
            s1.keyPressed(e);
        }
        @Override
        public void keyReleased(KeyEvent e){
            s1.keyReleased(e);
        }
    }
   
    public static void main(String[] args) {
        Shoot shoot = new Shoot();
        //Threads
        Thread ship = new Thread(s1);
        ship.start();
    }
}

Ship.java:
Code: [Select]
package javaapplication13;

import java.awt.*;
import java.awt.event.*;

public class Ship implements Runnable {
   
    int x, y, xDirection;
   
    public Ship(){
        x = 175;
        y = 275;
    }
   
    public void draw(Graphics g){
        g.setColor(Color.BLUE);
        g.fillRect(x, y, 40, 10);
        g.fillRect(x+18, y-7, 4, 7);
    }
   
    public void move(){
        x += xDirection;
        if(x <= 0)
            x = 0;
        if(x >= 360)
            x = 360;
    }
   
    public void setXDirection(int xdir){
        xDirection = xdir;
    }
   
    public void keyPressed(KeyEvent e){
        int keyCode = e.getKeyCode();
        if(keyCode == e.VK_LEFT){
            setXDirection(-1);
        }
        if(keyCode == e.VK_RIGHT){
            setXDirection(1);
        }
    }
    public void keyReleased(KeyEvent e){
        int keyCode = e.getKeyCode();
        if(keyCode == e.VK_LEFT){
            setXDirection(0);
        }
        if(keyCode == e.VK_RIGHT){
            setXDirection(0);
        }
    }
   
    @Override
    public void run(){
        try{
            while(true){
                move();
                Thread.sleep(5);
            }
        }catch(Exception e){System.err.println(e.getMessage());}
    }
   
}


If I want to make it possible to shoot more bullets at a time and not waiting for the shot bullet to go out of the screen should I make more bullet variables or that is not the right way to solve the problem ?