Having trouble with the special drawing.

Ok, so I am still fairly new to java and am working on this game to improve myself. When my special is set to true it does not draw for some reason can someone tell me what I am doing wrong?

Below are the files containing code having to deal with the special.

Special.java
[spoiler]

package com.chimpygames;

import java.awt.Color;
import java.awt.Graphics2D;

public class Special {

	// fields
	private double x;
	private double y;
	private int r;
	private int increase;

	private Color color1;

	
	//constructor
	public Special(int x, int y) {
		//new code
		this.x = x;
		this.y = y;
		r = 0;
		increase = 1;

		color1 = Color.WHITE;
	}

	// functions
	
	public double getx() { return x; }
	public double gety() { return y; }
	public double getr() { return r; }

	public boolean update() {
		//new true code
			while (r <= 10) {
			r += increase;
			r++;
			return false;
		}
		
		return false;
	}

	public void draw(Graphics2D g) {
		g.setColor(color1);
		g.drawOval((int) x,(int) y, 5 * r, 5 * r);
	}
}

[/spoiler]

GamePanel.java
[spoiler]

package com.chimpygames;

import javax.swing.JPanel;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.*;
import java.util.ArrayList;

import javax.swing.JPanel;

public class GamePanel extends JPanel implements Runnable, KeyListener {

	// Fields
	public static int WIDTH = 400;
	public static int HEIGHT = 500;

	private Thread thread;
	private boolean isRunning;

	private BufferedImage image;
	private Graphics2D g;

	private int FPS = 30;
	private double averageFPS;

	public Player player;
	public static ArrayList<Bullet> bullets;
	public static ArrayList<Enemy> enemies;
	public static ArrayList<Special> special;

	// Constructor
	public GamePanel() {
		super();
		setPreferredSize(new Dimension(WIDTH, HEIGHT));
		setFocusable(true);
		requestFocus();
	}

	// Functions
	public void addNotify() {
		super.addNotify();
		if (thread == null) {
			thread = new Thread(this);
			thread.start();
		}
		addKeyListener(this);
	}

	@Override
	public void run() {
		isRunning = true;

		image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		g = (Graphics2D) image.getGraphics();

		player = new Player();
		bullets = new ArrayList<Bullet>();
		enemies = new ArrayList<Enemy>();
		for (int i = 0; i < 2000; i++) {
			enemies.add(new Enemy(1,1));
		}
		
		long startTime;
		long URDTimeMillis;
		long waitTime;
		long totalTime = 0;

		int frameCount = 0;
		int maxFrameCount = 30;

		long targetTime = 1000 / FPS;

		// GAME LOOP
		while (isRunning) {

			startTime = System.nanoTime();

			gameUpdate();
			gameRender();
			gameDraw();

			URDTimeMillis = (System.nanoTime() - startTime) / 1000000;
			waitTime = targetTime - URDTimeMillis;

			try {
				Thread.sleep(waitTime);
			} catch (Exception e) {
			}

			totalTime += System.nanoTime() - startTime;
			frameCount++;
			if (frameCount == maxFrameCount) {
				averageFPS = 1000.0 / ((totalTime / frameCount) / 1000000);
				frameCount = 0;
				totalTime = 0;
			}

		}
	}

	private void gameUpdate() {

		//player update
		player.update();
		
		//bullet update
		for (int i = 0; i < bullets.size(); i++) {
			boolean remove = bullets.get(i).update();
			if (remove) {
				bullets.remove(i);
				i--;
			}
		}
		
		//enemy update
		for (int i = 0; i < enemies.size(); i++) {
			enemies.get(i).update();
		}
		
		//bullet and enemy collisions
		for (int i = 0; i < bullets.size(); i++) {
			
			Bullet b = bullets.get(i);
			double bx = b.getx();
			double by = b.gety();
			double br = b.getr();
			
			for (int j = 0; j < enemies.size(); j++) {
			
				Enemy e = enemies.get(j);
				double ex = e.getx();
				double ey = e.gety();
				double er = e.getr();
				
				double dx = bx - ex;
				double dy = by - ey;
				double dist = Math.sqrt(dx * dx + dy * dy);
				
				if (dist < br + er) {
					e.hit();
					bullets.remove(i);
					i--;
					break;
				}				
			}
		}
		
		
		//special update
		try {
			for (int t = 0; t < special.size(); t++) {
				boolean remove = special.get(t).update();
				if (remove) {
					special.remove(t);
					t--;
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		//enemy and player collision
		for (int i = 0; i < enemies.size(); i++) {
			
			Enemy e = enemies.get(i);
			
			double ex = e.getx();
			double ey = e.gety();
			double er = e.getr();

			double px = player.getx();
			double py = player.gety();
			double pr = player.getr();
			
			double dx = ex - px;
			double dy = ey - py;
			double dist = Math.sqrt(dx * dx + dy * dy);
				
			if (player.getSpecial()) {
				if (dist < (er + 10) + (pr + 10)) {
					e.hit();
				}
			}
		}
		
		//check dead enemies
		for(int i=0; i < enemies.size(); i++) {
			if(enemies.get(i).isDead()) {
				enemies.remove(i);
				i--;
			}
		}
	}

	private void gameRender() {
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, WIDTH, HEIGHT);
		g.setColor(Color.WHITE);
		g.drawString("FPS: " + averageFPS, 10, 10);
		g.drawString("Bullets: " + bullets.size(), 10, 20);
		g.drawString("Enemies: " + enemies.size(), 10, 30);
		g.drawString("X: " + player.x + "  Y: " + player.y, 10, 40);
		
		//draw special
		try {
			for(int i =0; i < special.size(); i++){
				special.get(i).draw(g);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		
		//draw player
		player.draw(g);
		
		//draw bullets
		for(int i =0; i < bullets.size(); i++){
			bullets.get(i).draw(g);
		}
		
		//draw enemies
		for (int i = 0; i < enemies.size(); i++) {
			enemies.get(i).draw(g);
		}
	}

	private void gameDraw() {
		Graphics g2 = this.getGraphics();
		g2.drawImage(image, 0, 0, null);
		g2.dispose();
	}

	public void keyTyped(KeyEvent key) {
	}

	public void keyPressed(KeyEvent key) {

		int keyCode = key.getKeyCode();

		switch (keyCode) {
		case KeyEvent.VK_LEFT:
			player.setLeft(true);
			break;
		case KeyEvent.VK_RIGHT:
			player.setRight(true);
			break;
		case KeyEvent.VK_UP:
			player.setUp(true);
			break;
		case KeyEvent.VK_DOWN:
			player.setDown(true);
			break;
		case KeyEvent.VK_Z:
			player.setFiring(true);
			break;
		case KeyEvent.VK_X:
			player.setSpecial(true);
			break;

		default:
			break;
		}

	}

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

		switch (keyCode) {
		case KeyEvent.VK_LEFT:
			player.setLeft(false);
			break;
		case KeyEvent.VK_RIGHT:
			player.setRight(false);
			break;
		case KeyEvent.VK_UP:
			player.setUp(false);
			break;
		case KeyEvent.VK_DOWN:
			player.setDown(false);
			break;
		case KeyEvent.VK_Z:
			player.setFiring(false);
			break;
		case KeyEvent.VK_X:
			player.setSpecial(false);
			break;

		default:
			break;
		}
	}
}

[/spoiler]

Player.java
[spoiler]

package com.chimpygames;

import java.awt.*;

public class Player {

	// fields
	public int x;
	public int y;
	public int r;

	public int dx;
	public int dy;
	private int speed;

	private boolean left;
	private boolean right;
	private boolean up;
	private boolean down;
	
	private boolean firing;
	private long firingTimer;
	private long firingDelay;
	
	private boolean special;
	private long specialTimer;
	private long specialDelay;

	private int lives;
	private Color color1;
	private Color color2;

	// constructor
	public Player() {

		x = GamePanel.WIDTH / 2;
		y = GamePanel.HEIGHT / 2;
		r = 5;

		dx = 0;
		dy = 0;
		speed = 6;

		lives = 3;
		color1 = Color.WHITE;
		color2 = Color.RED;
		
		firing = false;
		firingTimer = System.nanoTime();
		firingDelay = 200;
		
		special = false;
		specialTimer = System.nanoTime();
		specialDelay = 5000;
	}

	// functions
	public int getx() {
		return x;
	}
	
	public int gety() {
		return y;
	}
	
	public int getr() {
		return r;
	}
	
	public boolean getSpecial() {
		return special;
	}

	public void setLeft(boolean b) {
		left = b;
	}

	public void setRight(boolean b) {
		right = b;
	}

	public void setUp(boolean b) {
		up = b;
	}

	public void setDown(boolean b) {
		down = b;
	}
	
	public void setSpecial(boolean b) {
		special = b;
	}
	
	public void setFiring(boolean b) { firing = b;}

	public void update() {

		if (left) {
			dx = -speed;
		}
		if (right) {
			dx = speed;
		}
		if (up) {
			dy = -speed;
		}
		if (down) {
			dy = speed;
		}

		x += dx;
		y += dy;

		if (x < r)
			x = r;
		
		if (y < r)
			y = r;
		
		if (x > GamePanel.WIDTH - r)
			x = GamePanel.WIDTH - r;
		
		if (y > GamePanel.HEIGHT - r)
			y = GamePanel.HEIGHT - r;

		dx = 0;
		dy = 0;
		
		if(firing) {
			long elapsed = (System.nanoTime() - firingTimer) / 1000000;
			if(elapsed > firingDelay) {
				GamePanel.bullets.add(new Bullet(270, x, y));
				firingTimer = System.nanoTime();
			}
		}
		
		if(special) {
			long elapsed = (System.nanoTime() - specialTimer) / 1000000;
			if(elapsed > specialDelay) {
				try {
					GamePanel.special.add(new Special(getx(), gety()));
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				specialTimer = System.nanoTime();
			}
		}
	}

	public void draw(Graphics2D g) {

		g.setColor(color1);
		g.fillOval(x - r, y - r, 2 * r, 2 * r);

		g.setStroke(new BasicStroke(3));
		g.setColor(color1.darker());
		g.drawOval(x - r, y - r, 2 * r, 2 * r);
		g.setStroke(new BasicStroke(1));

	}

}

[/spoiler]

Well, there are 2 problems here (assuming you are just learning the basics and using Java2D)…

  1. You aren’t actually over-ridding anything to draw into (paint/ paintComponent) or using any frame (Frame, Canvas, etc)
  2. You aren’t running any type of Thread so your game can update itself (Runnable)

A post like this would automatically get tossed into the “learnz Java” part of the board telling you to read the Java Tutorials, or take a look at one of these beginner threads. However, I’m feeling in a giving mood today and I’ll just give you working code that has all the parts in it already. I suggest that you study it to figure out what all the parts of my code does.


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class SnowExample extends JComponent implements Runnable{

	private JFrame window;
	private BufferedImage bimg;

	public static void main(String args[]){
		SnowExample cool = new SnowExample();
		cool.showWindow();
	}

	/** How often the snow is produced */
	public final int FREQUENCY = 500;
	/** The maximum amount of particles allowed */
	public final int MAX_PARTICLE = 100;

	/** The random number generator */
	public Random rand;
	/** The type of snow ball to draw */
	public int[] type;
	/** The x-axis position of the snow ball */
	public double[] posx;
	/** The y-axis position of the snow ball */
	public double[] posy;
	/** The flash of the snow ball */
	public boolean[] flash;
	/** Temporary variable */
	public int temp;

	public void init(){
		type = new int[MAX_PARTICLE];
		posx = new double[MAX_PARTICLE];
		posy = new double[MAX_PARTICLE];
		flash = new boolean[MAX_PARTICLE];
		rand = new Random();
		for(int i = 0; i < MAX_PARTICLE; i++)
			type[i] = -1;
	}

	public void updateRender(Graphics2D g, int w, int h){

		//Create new snow particles
		for(int i = 0; i < MAX_PARTICLE; i++){
			if(type[i] == -1 && rand.nextInt(FREQUENCY) == 0){
				type[i] = rand.nextInt(3);
				posx[i] = (rand.nextInt((w+100)/10)*10) - 100;
				posy[i] = -10;
				flash[i] = rand.nextBoolean();
				break;
			}
		}

		//Snow particle updates
		for(int i = 0; i < MAX_PARTICLE; i++){
			if(type[i] == -1)
				continue;

			if(type[i] == 2){
				posx[i] += 0.5;
			}
			posx[i] += 0.5;
			posy[i] += 2;
			flash[i] = !flash[i];

			//Destroy particles
			if(posy[i] > h)
				type[i] = -1;
		}

		//Render particles
		g.setColor(Color.WHITE);
		for(int i = 0; i < MAX_PARTICLE; i++){
			if(type[i] == -1)
				continue;
			if(type[i] == 0 && flash[i])
				g.fillOval((int)posx[i], (int)posy[i], 4, 4);
			else if(type[i] == 1 && flash[i])
				g.fillOval((int)posx[i], (int)posy[i], 6, 6);
			else if(type[i] == 2 && flash[i])
				g.fillOval((int)posx[i], (int)posy[i], 8, 8);
		}
	}

	/////////////////////////////////////
	//The infrastructure stuff under here...
	/////////////////////////////////////

	public SnowExample(){
		 window = new JFrame("Snow Example");
        window.setBackground(Color.BLACK);
        setBackground(Color.BLACK);
        init();
	}

	public void showWindow(){
		 Thread looper = new Thread(this);
         looper.start();
		 window.add(this, BorderLayout.CENTER);
		 window.addWindowListener(new WindowAdapter() {
             @Override
              public void windowClosing(WindowEvent e) {
                  window.dispose();
                  System.exit(0);
              }
          });
	     window.validate();
	     window.setVisible(true);
	     window.pack();
	}

	@Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        createGraphics2D((Graphics2D)g, getSize().width, getSize().height);
        //Draws a non-flickering image
        g.drawImage(bimg, 0, 0, this);
    }

	private void createGraphics2D(Graphics2D g2, int w, int h) {
        if (bimg == null || bimg.getWidth() != w || bimg.getHeight() != h)
            bimg = (BufferedImage) createImage(w, h);

        g2 = bimg.createGraphics();
        g2.setColor(Color.BLACK);
        g2.fillRect(0, 0, w, h);
        
        updateRender(g2, w, h);
    }

	@Override
    public Dimension getPreferredSize(){
        return new Dimension(400, 300);
    }

	@Override
	public final void run() {
        try{           
            while(true){
                Thread.sleep(10);
                repaint();
            }
        }catch(Exception e){
            System.err.println(e.getMessage());
            System.exit(0);
        }
    }

}

Copy and paste it into your IDE. Make sure you study “How it is done” and use the tutorial links to supplement your training. It isn’t the greatest example, but it should get you show you how to create a window with Graphics. All you’d have to research after this is how to display Images, which should be found within the Java Graphics classes. Best of luck.

Both please use paste bin next time. It makes the posts look much more readable.

Well I have read a few java tutorials but as I stated I am still fairly new, but thank you for your assistance.

As for next time alright I can use paste bin.

Edit
You will be happy to know I have downloaded all of the videos from thenewboston website on java development this way I am not in need of any more assistance that is, how shall I say…Ignorant.