Maze Game Programming - java

This my code for the simple maze game. Its being compiled and class file of MazeGame.java and Board.java are being created but not of Player.java and Map.java. The code is being compiled error free but its not running. Please help me out.
//MazeGame.java
package mygame;
import javax.swing.*;
public class MazeGame {
public static void main(String[] args) {
new MazeGame();
}
public MazeGame() {
JFrame f= new JFrame();
f.setTitle("Maze Game");
f.setSize(450,450);
f.setLocationRelativeTo(null);
f.add(new Board());
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//Board.java
package mygame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.*;
public class Board extends JPanel implements ActionListener {
private Timer timer;
private Map m;
private Player p;
private boolean win=false;
private String Message="";
private Font font = new Font("Comic Sans",Font.BOLD,50);
public Board() {
m = new Map();
p = new Player();
addKeyListener(new Al());
setFocusable(true);
timer = new Timer(25,this);
timer.start();
}
public void paint(Graphics g)
{
super.paint(g);
if(!win)
{
for(int y=0; y<14; y++) {
for(int x=0; x<14; x++) {
if(m.getMap(x,y).equals("f")) {
g.drawImage(m.getFinish(),x*32,y*32,null);
}
if(m.getMap(x,y).equals("g")) {
g.drawImage(m.getGrass(),x*32,y*32,null);
}
if(m.getMap(x,y).equals("w")) {
g.drawImage(m.getWall(),x*32,y*32,null);
}
}
}
g.drawImage(p.getPlayer(),p.getTileX()*32,p.getTileY()*32,null);
}
if(win)
{
g.setColor(Color.BLUE);
g.setFont(font);
g.drawString(Message,100,300);
}
}
public class Al extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if((keyCode==KeyEvent.VK_W) || (keyCode==KeyEvent.VK_UP)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(0,-1);
}
}
if((keyCode==KeyEvent.VK_S) || (keyCode==KeyEvent.VK_DOWN)) {
if(!(m.getMap(p.getTileX(),p.getTileY()+1).equals("w"))) {
p.move(0,1);
}
}
if((keyCode==KeyEvent.VK_A) || (keyCode==KeyEvent.VK_LEFT)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(-1,0);
}
}
if((keyCode==KeyEvent.VK_D) || (keyCode==KeyEvent.VK_RIGHT)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(1,0);
}
}
}
}
public void actionPerformed(ActionEvent e) {
if(m.getMap(p.getTileX(),p.getTileY()).equals("f")) {
Message = "WINNER!!!";
win = true;
}
repaint();
}
}
//Map.java
package mygame;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.*;
public class Map {
private Scanner s;
private String Map[] = new String[14];
private Image grass,wall,finish;
public Map() {
ImageIcon img = new ImageIcon("G://sonali_java//mygame//grass.png");
grass = img.getImage();
img = new ImageIcon("G://sonali_java//mygame//wall.png");
wall = img.getImage();
img = new ImageIcon("G://sonali_java//mygame//finish.png");
finish = img.getImage();
openFile();
readFile();
closeFile();
}
public String getMap(int x,int y) {
String index = Map[y].substring(x,x+1);
return index;
}
public Image getGrass() {
return grass;
}
public Image getWall() {
return wall;
}
public Image getFinish() {
return finish;
}
public void openFile() {
try {
s= new Scanner(new File("G://sonali_java//mygame//Map.txt"));
}
catch(Exception e) {
System.out.println("Error Loading File!!!!");
}
}
public void readFile() {
while(s.hasNext()) {
for(int i=0; i<14; i++) {
Map[i] = s.next();
}
}
}
public void closeFile() {
s.close();
}
}
//Player.java
package mygame;
import java.awt.*;
public class Player {
private int tileX,tileY;
private Image player;
public Player() {
tileX=1;
tileY=1;
ImageIcon img = new ImageIcon("G://sonali_java//mygane//object.png");
player = img.getImage();
}
public Image getPlayer() {
return player;
}
public int getTileX() {
return tileX;
}
public int getTileY() {
return tileY;
}
public void move(int dx, int dy) {
tileX += dx;
tileY += dy;
}
}

I dont want to be mad but you are defining different folder locations
in some places "G://sonali_java//mygane//object.png", check "mygaNe"
in some places "G://sonali_java//mygame//Map.txt", check "mygaMe"
Are you sure while loading it does not throw a NullPointerException ?

Are you aware that you can, place code like
public void draw(Graphics g){
g.drawImage(playerImg, getX(), getY(), null);
}
in your player class, thus leaving the player class with drawing the player and simply calling the players draw method inside your Board paint method? This can also be done for drawing the map. Remember to call the draw methods in the paint method.
ALSO, THIS
ImageIcon img = new ImageIcon("G://sonali_java//mygane//object.png");
check your directory location

Related

adding time i dont know how to add

Here is my maze code i want to add a timer in my game that if he dosent finish the maze in 60 seconds it will show a game over and the game will stop
Main class
package javamazegame;
import javax.swing.*;
public class JavaMazegame {
public JavaMazegame(){
JFrame f = new JFrame();
f.setTitle("MazeGame Version 1.0");
f.setSize(464,485);
f.add(new Board());
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JavaMazegame();
}
}
how to add a time in my maze game
Board Class
package javamazegame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
import javax.swing.*;
public class Board extends JPanel implements ActionListener{
private Timer timer;
private Map m;
private Player p;
public boolean win = false ;
private String Message = " ";
private Font font = new Font("Serif",Font.BOLD,48);
public Board(){
m = new Map();
p = new Player();
addKeyListener(new Al());
setFocusable(true);
timer = new Timer(25,this);
timer.start();
System.out.println(timer);
}
public void actionPerformed(ActionEvent e){
if(m.getMap(p.getTileX(),p.getTileY()).equals("f")){
Message = "Winner";
win = true;
}
repaint();
}
public void paint(Graphics g){
super.paint(g);
if(!win){
for(int y = 0 ; y <14 ; y++){
for(int x = 0 ; x <14 ; x++){
if(m.getMap(x,y).equals("f")){
g.drawImage(m.getFinish(),x*32,y*32,null);
}
if(m.getMap(x, y).equals("g")){
g.drawImage(m.getGrass(), x*32, y*32, null);
}
if(m.getMap(x, y).equals("w")){
g.drawImage(m.getWall(), x*32, y*32, null);
}
}
}
g.drawImage(p.getPlayer(),p.getTileX()* 32, p.getTileY() * 32,null);
}
if(win){
g.setColor(Color.GREEN);
g.setFont(font);
g.drawString(Message, 150, 200);
}
}
public class Al extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keycode = e.getKeyCode();
if(keycode == KeyEvent.VK_W){
if(!m.getMap(p.getTileX(),p.getTileY()-1).equals("w")){
p.move(0,-1);
}
}
if(keycode == KeyEvent.VK_S){
if(!m.getMap(p.getTileX(),p.getTileY()+1).equals("w")){
p.move(0,1);
}
}
if(keycode == KeyEvent.VK_A){
if(!m.getMap(p.getTileX()-1,p.getTileY()).equals("w")){
p.move(-1,0);
}
}
if(keycode == KeyEvent.VK_D){
if(!m.getMap(p.getTileX()+1,p.getTileY()).equals("w")){
p.move(1,0);
}
}
}
public void keyRelased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
}
}
Map Class
package javamazegame;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Map {
private Scanner m;
private String Map[] = new String[14];
private Image grass,
finish,
wall;
public Map(){
ImageIcon img = new ImageIcon("C://Users//Rayjay//Desktop//Assets//road.png");
grass = img.getImage();
img = new ImageIcon("C://Users//Rayjay//Desktop//Assets//wall.png");
wall = img.getImage();
img = new ImageIcon("C://Users//Rayjay//Desktop//Assets//finish.png");
finish = img.getImage();
openFile();
readFile();
closeFile();
}
public Image getGrass(){
return grass;
}
public Image getWall(){
return wall;
}
public Image getFinish(){
return finish;
}
public String getMap(int x , int y){
String index = Map[y].substring(x,x+1);
return index;
}
public void openFile(){
try{
m = new Scanner(new File("C://Users//Rayjay//Desktop//Assets//Map.txt"));
}
catch(Exception e){
System.out.println("Error Loading Map");
}
}
public void readFile(){
while(m.hasNext()){
for(int i = 0; i < 14; i++){
Map[i] = m.next();
}
}
}
public void closeFile(){
m.close();
}
}
Player class
package javamazegame;
import java.awt.Image ;
import javax.swing.ImageIcon;
player class this my class for player
public class Player {
private int tileX,tileY;
private Image player;
public Player(){
ImageIcon img = new ImageIcon("C://Users//Rayjay//Desktop//Assets//player.png");
player = img.getImage();
tileX = 1;
tileY = 1;
}
public Image getPlayer(){
return player;
}
public int getTileX(){
return tileX;
}
public int getTileY(){
return tileY;
}
public void move(int dx,int dy){
tileX += dx;
tileY += dy;
}
}
You could use the Timer class. There are several possibilities how you could work with this class. Here is the doc to Timer.

Draw on JPanel from other class

In my program I try to paint on a JPanel when the mouse is pressed. The mousePressed method is just to test the painting from another class. Later on the spawn method will be called by other class methods. When I press the mouse button spawnPedestrian() is called, but no Pedestrian is painted. Below is a running example with code from my project. If you create a project Roundabout and paste this code in it, you should be able to run it (images are hotlinked).
How to fix the spawnPedestrian() method?
public class Roundabout extends JFrame {
public static Surface surface;
public Roundabout() {
initUI();
}
private void initUI() {
setTitle("Roundabout");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
surface = new Surface();
add(surface);
this.addMouseListener(new MouseAdapter() {// empty implementation of all
// MouseListener`s methods
#Override
public void mousePressed(MouseEvent e) {
//Spawn
Spawn sp = new Spawn();
sp.spawnPedestrian(300, 100);
}
});
setSize(1618, 850);
setLocationRelativeTo(null);
}
public static JPanel getSurface() {
return surface;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Roundabout roundabout = new Roundabout();
roundabout.setVisible(true);
}
});
}
//Track class
class Track {
BufferedImage track;
Point trackPosition;
Point TRACK_POS = new Point(0, 0);
public Track() {
try {
track = ImageIO.read(new URL("http://i.stack.imgur.com/2U3j5.png"));
} catch (Exception ex) {
System.out.println("Problem loading track image: " + ex);
}
trackPosition = new Point(TRACK_POS.x, TRACK_POS.y);
}
public void paint(Graphics g) {
g.drawImage(track, TRACK_POS.x, TRACK_POS.y, null);
}
}
//Surface class
public class Surface extends JPanel {
Track track = new Track();
public List<Vehicle> toDraw = new ArrayList<>();
public Surface() {
Pedestrian p = new Pedestrian(100, 100);
toDraw.add(p);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//setLayout(null);
track.paint(g);
//Make sure the track is painted first
for (Vehicle v : toDraw) {
v.paint(g);
}
}
}
class Pedestrian extends Vehicle {
BufferedImage pedestrian;
Point pedestrianPosition;
double pedestrianRotation = 0;
int pedestrianW, pedestrianH;
public Pedestrian(int x, int y) {
try {
pedestrian = ImageIO.read(new URL("http://i.stack.imgur.com/wm0I5.png"));
} catch (IOException e) {
System.out.println("Problem loading pedestrian images: " + e);
}
pedestrianPosition = new Point(x, y);
pedestrianW = pedestrian.getWidth();
pedestrianH = pedestrian.getHeight();
}
#Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.rotate(Math.toRadians(pedestrianRotation), pedestrianPosition.x, pedestrianPosition.y);
g2d.drawImage(pedestrian, pedestrianPosition.x, pedestrianPosition.y, null);
}
#Override
public void setPath(List<Point> path) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void update(double i) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
//Spawn class
class Spawn {
public void spawnPedestrian(int x, int y) {
//Create a new pedestrian.
System.out.println("Spawn a pedestrian.");
Pedestrian p = new Pedestrian(x, y);
Roundabout.surface.toDraw.add(p);
Roundabout.surface.revalidate();
Roundabout.surface.repaint();
}
}
public abstract class Vehicle {
public abstract void setPath(List<Point> path);
public abstract void update(double i);
public abstract void paint(Graphics g);
}
}
EDIT: It works now Pedestrian is spawned on mouse click.
Basically, you want to decouple your code and centralise the responsible to the classes. So the "data" should be maintained by a model of some kind, the rendering should be handle by some kind of view and the updates to the model and view should be handled by some kind of controller.
This makes it easier to swap out any one part with out requiring a whole bunch of new code or other changes. It also means that each class has a defined domain of responsibility and discourages you from trying to, for example, make changes to state from within the view which should be handled by the model (which could put the state into disarray)
Let's start with something that what's to be painted
public interface Sprite {
public void paint(Graphics2D g2d);
}
public interface MoveableSprite extends Sprite {
public void update(Container container);
}
These represent either a static sprite (like a tree for example) or a sprite which is moving (and wants to be updated on a regular bases)
These are contained within a model
public interface GameModel {
public List<Sprite> getSprites();
public void setObserver(Observer<MoveableSprite> observer);
public Observer<MoveableSprite> getObserver();
public void spawnSprite();
}
Which provides some means by which it can notify (in this case, a single) interested party about some kind of state change. For this example, that means a new MoveableSprite has become available
The Observer is pretty basic and just has a single call back...
public interface Observer<T> {
public void stateChanged(T parent);
}
And an "engine" to help drive it...
public class GameEngine {
private GameModel model;
private SurfacePane surface;
private Timer timer;
public GameEngine(GameModel model, SurfacePane surface) {
this.model = model;
this.surface = surface;
model.setObserver(new Observer<MoveableSprite>() {
#Override
public void stateChanged(MoveableSprite sprite) {
sprite.update(getSurface());
}
});
timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Sprite sprite : getModel().getSprites()) {
if (sprite instanceof MoveableSprite) {
((MoveableSprite) sprite).update(getSurface());
}
}
getSurface().repaint();
}
});
}
public GameModel getModel() {
return model;
}
public SurfacePane getSurface() {
return surface;
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
}
This is a pretty basic example, but basically, it updates the position of MoveableSprite and asks the surface to repaint itself. It's also observing the GameModel for any new sprites and it will update their position immediately, so they don't appear in some "weird" place
Okay, now we actually need to implement some of this to make it work
public class DefaultGameModel implements GameModel {
private Observer<MoveableSprite> observer;
private List<Sprite> sprites;
public DefaultGameModel() {
sprites = new ArrayList<>(25);
for (int index = 0; index < 10; index++) {
spawnSprite();
}
}
#Override
public List<Sprite> getSprites() {
return Collections.unmodifiableList(sprites);
}
public void spawnSprite() {
try {
ZombieSprite sprite = new ZombieSprite();
sprites.add(sprite);
Observer<MoveableSprite> observer = getObserver();
if (observer != null) {
observer.stateChanged(sprite);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void setObserver(Observer<MoveableSprite> observer) {
this.observer = observer;
}
#Override
public Observer<MoveableSprite> getObserver() {
return observer;
}
}
public class ZombieSprite implements MoveableSprite {
private int x;
private int y;
private int xDelta;
private int yDelta;
private BufferedImage img;
private Observer<Sprite> observer;
private boolean initialised = false;
public ZombieSprite() throws IOException {
img = ImageIO.read(getClass().getResource("/LogoZombi.png"));
}
#Override
public void update(Container container) {
if (!initialised) {
x = (int) (Math.random() * container.getWidth());
y = (int) (Math.random() * container.getHeight());
Random rnd = new Random();
xDelta = rnd.nextBoolean() ? 1 : -1;
yDelta = rnd.nextBoolean() ? 1 : -1;
initialised = true;
}
x += xDelta;
y += yDelta;
if (x < 0) {
x = 0;
xDelta *= -1;
} else if (x + img.getWidth() > container.getWidth()) {
x = container.getWidth() - img.getWidth();
xDelta *= -1;
}
if (y < 0) {
y = 0;
yDelta *= -1;
} else if (y + img.getHeight() > container.getHeight()) {
y = container.getHeight() - img.getHeight();
yDelta *= -1;
}
}
#Override
public void paint(Graphics2D g2d) {
g2d.drawImage(img, x, y, null);
}
}
These two classes implement the GameModel and MoveableSprite interfaces. We use interfaces to decouple the code, which makes it easier to change the way in which things work and provides a jumping off point for agreed to contracts and exceptions of the implemenations
And finally, something that actually paints the current state...
public class SurfacePane extends JPanel {
private GameModel model;
public SurfacePane(GameModel model) {
this.model = model;
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
getModel().spawnSprite();
}
});
}
public GameModel getModel() {
return model;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
GameModel model = getModel();
for (Sprite sprite : model.getSprites()) {
sprite.paint(g2d);
}
g2d.dispose();
}
}
You'll not that this class has the MouseListener, this is kind of deliberate, as other components which might be added to this container could prevent the MouseListener from been notified, so don't do that. But the MouseListener just calls the model to spawn another zombie...
And finally, we need to plumb it altogether...
GameModel model = new DefaultGameModel();
SurfacePane surfacePane = new SurfacePane(model);
GameEngine engine = new GameEngine(model, surfacePane);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(surfacePane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
engine.start();
And just because I know that's a lot of disjointed concepts to put together, a complete example...
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
GameModel model = new DefaultGameModel();
SurfacePane surfacePane = new SurfacePane(model);
GameEngine engine = new GameEngine(model, surfacePane);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(surfacePane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
engine.start();
}
});
}
public class SurfacePane extends JPanel {
private GameModel model;
public SurfacePane(GameModel model) {
this.model = model;
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
getModel().spawnSprite();
}
});
}
public GameModel getModel() {
return model;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
GameModel model = getModel();
for (Sprite sprite : model.getSprites()) {
sprite.paint(g2d);
}
g2d.dispose();
}
}
public class GameEngine {
private GameModel model;
private SurfacePane surface;
private Timer timer;
public GameEngine(GameModel model, SurfacePane surface) {
this.model = model;
this.surface = surface;
model.setObserver(new Observer<MoveableSprite>() {
#Override
public void stateChanged(MoveableSprite sprite) {
sprite.update(getSurface());
}
});
timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Sprite sprite : getModel().getSprites()) {
if (sprite instanceof MoveableSprite) {
((MoveableSprite) sprite).update(getSurface());
}
}
getSurface().repaint();
}
});
}
public GameModel getModel() {
return model;
}
public SurfacePane getSurface() {
return surface;
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
}
public interface Observer<T> {
public void stateChanged(T parent);
}
public interface Sprite {
public void paint(Graphics2D g2d);
}
public interface MoveableSprite extends Sprite {
public void update(Container container);
}
public interface GameModel {
public List<Sprite> getSprites();
public void setObserver(Observer<MoveableSprite> observer);
public Observer<MoveableSprite> getObserver();
public void spawnSprite();
}
public class DefaultGameModel implements GameModel {
private Observer<MoveableSprite> observer;
private List<Sprite> sprites;
public DefaultGameModel() {
sprites = new ArrayList<>(25);
for (int index = 0; index < 10; index++) {
spawnSprite();
}
}
#Override
public List<Sprite> getSprites() {
return Collections.unmodifiableList(sprites);
}
public void spawnSprite() {
try {
ZombieSprite sprite = new ZombieSprite();
sprites.add(sprite);
Observer<MoveableSprite> observer = getObserver();
if (observer != null) {
observer.stateChanged(sprite);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void setObserver(Observer<MoveableSprite> observer) {
this.observer = observer;
}
#Override
public Observer<MoveableSprite> getObserver() {
return observer;
}
}
public class ZombieSprite implements MoveableSprite {
private int x;
private int y;
private int xDelta;
private int yDelta;
private BufferedImage img;
private Observer<Sprite> observer;
private boolean initialised = false;
public ZombieSprite() throws IOException {
img = ImageIO.read(getClass().getResource("/LogoZombi.png"));
}
#Override
public void update(Container container) {
if (!initialised) {
x = (int) (Math.random() * container.getWidth());
y = (int) (Math.random() * container.getHeight());
Random rnd = new Random();
xDelta = rnd.nextBoolean() ? 1 : -1;
yDelta = rnd.nextBoolean() ? 1 : -1;
initialised = true;
}
x += xDelta;
y += yDelta;
if (x < 0) {
x = 0;
xDelta *= -1;
} else if (x + img.getWidth() > container.getWidth()) {
x = container.getWidth() - img.getWidth();
xDelta *= -1;
}
if (y < 0) {
y = 0;
yDelta *= -1;
} else if (y + img.getHeight() > container.getHeight()) {
y = container.getHeight() - img.getHeight();
yDelta *= -1;
}
}
#Override
public void paint(Graphics2D g2d) {
g2d.drawImage(img, x, y, null);
}
}
}

Can't subtract 1 from bank

PS: the links you have to take out the () from http because I don't have enough rep points or something.
Board:
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener {
Turn_Ticker turn = new Turn_Ticker();
Bank bank = new Bank();
Image Background;
Timer timer;
String time="";
public Board() {
setFocusable(true);
ImageIcon icon = new ImageIcon("res/Level1.png"); // calls image for background
Background = icon.getImage(); // sets variable background to icon image
timer = new Timer(5,this); // sets how fast page refreshes
timer.start();
}
public void actionPerformed(ActionEvent event) { // Refreshes page according to timer
repaint();
}
public void paint(Graphics paint) { // paints on frame
super.paint(paint);
Graphics2D p = (Graphics2D) paint;
turn.getTick();
bank.subBank();
p.drawImage(Background, 0, 0, null);
p.drawString(bank.getBank()+"",125,70);
p.drawString(bank.getEnemy_Bank()+"",125,115);
p.drawString(turn.getSecond()+" Second(s) Turn: "+turn.getTurn(), 120, 200);
if(turn.getTick())
p.drawString("Ticker = true", 500,500);/*
if(turn.getNum()==0)
p.drawString("Number = 0", 500,550);
if(turn.getNum()==0&&turn.getTick()){
bank.subBank();
p.drawString("Both are =", 500, 600);
}*/
//System.out.println("X: "+mouse.getX()+" Y: "+mouse.getY());
}
}
Turn_Ticker:
package game;
public class Turn_Ticker {
long before,after,difference;
boolean checkTime=true;
int seconds=0;
boolean ticker=false;
int turn=1;
int num=0;
public Turn_Ticker(){
if (checkTime == true)
before=System.currentTimeMillis();
checkTime=false;
}
public int getSecond() {
after=System.currentTimeMillis();
difference= after-before;
if(difference >= 1000) {
before=System.currentTimeMillis();
if(seconds<=0) {
seconds=30;
ticker=true;
num=0;
}
else {
seconds-=1;
num=1;
ticker=false;
}
}
return seconds;
}
public boolean getTick() {
if(ticker&&num==0) {
turn++;
}
return ticker;
}
public int getNum(){
return num;
}
public int getTurn() {
return turn;
}
public boolean getTickVar(){
return ticker;
}
}
Bank:
package game;
public class Bank {
Turn_Ticker turn = new Turn_Ticker();
int bank=5, enemy_Bank=5;
int baseRein=3, reinforcements,num=0;
public Bank(){
if(turn.getTick()==false)
num=0;
}
public int getBank(){
return bank;
}
public int getEnemy_Bank(){
return enemy_Bank;
}
public void subBank(){
if(turn.getNum()==0&&turn.getTick())
bank--;
}
public void subEn_Bank(){
enemy_Bank-=1;
}
}
Frame:
package game;
import javax.swing.*;
import java.awt.Font;
public class Frame {
public Frame() {
JFrame frame = new JFrame();
frame.add(new Board());
frame.setTitle("WSMD");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024,768);
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args){
new Frame();
}
}
My problem is that I can not, for the life of me, figure out why it won't subtract -1(bank.subBank()) from the bank. I've printed out the code and went through it step by step.

How can i add time limitation in a Maze Game using java

I am making a maze game in Java. I have made a maze board, A start point and a end point. When I reach the end point then it exit and show a winning message. But I can not add a time limitation. Suppose player have to reach the end point with 30 seconds otherwise he lose the game. Please help me.
Here is my code i have done so far.......
Maze.java
package Maze;
import javax.swing.JFrame;
public class Maze {
public static void main(String args[])
{
new Maze();
}
public Maze()
{
JFrame f= new JFrame();
f.setTitle("Maze Game");
f.add(new Board());
f.setSize(460,480);
f.setLocationRelativeTo(f);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Board.java
package Maze;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// #SuppressWarnings("serial")
#SuppressWarnings("serial")
public class Board extends JPanel implements ActionListener
{
private Timer timer;
private Map m;
private Player p;
private boolean win=false;
long startTime = System.currentTimeMillis();
long elapsedTime;
//private String Message="";
//private Font font=new Font("Serif",Font.BOLD,50);
public Board()
{
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime=elapsedTime/1000;
m= new Map();
p= new Player();
addKeyListener(new Al());
setFocusable(true);
timer=new Timer(25, this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
if(m.getMap(p.getTileX(), p.getTileY()).equals("f"))
{
//Message="WINNER";
win=true;
}
if(elapsedTime>=5)
win=true;
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
if(!win)
{
for(int y=0;y<14;y++)
{
for(int x=0;x<14;x++)
{
if(m.getMap(x,y).equals("f"))
g.drawImage(m.getFinish(), x*32, y*32, null);
if(m.getMap(x, y).equals("w"))
g.drawImage(m.getWall(), x*32, y*32, null);
if(m.getMap(x, y).equals("g"))
g.drawImage(m.getGrass(), x*32, y*32, null);
}
}
g.drawImage(p.getPlayer(), p.getTileX()*32, p.getTileY()*32,null);
}
if(win)
{
g.drawImage(m.getWinn(), 32, 32, null);
// g.setColor(Color.ORANGE);
//g.setFont(font);
//g.drawString(Message, 150, 200);
}
}
public class Al extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keycode= e.getKeyCode();
if(keycode==KeyEvent.VK_UP ){
if(!m.getMap(p.getTileX(),p.getTileY()-1).equals("w")){
p.move( 0, -1);
}
}
if(keycode==KeyEvent.VK_DOWN ){
if(!m.getMap(p.getTileX(),p.getTileY()+1).equals("w")){
p.move( 0, 1);
}
}
if(keycode==KeyEvent.VK_LEFT ){
if(!m.getMap(p.getTileX()-1,p.getTileY()).equals("w")){
p.move( -1, 0);
}
}
if(keycode==KeyEvent.VK_RIGHT ){
if(!m.getMap(p.getTileX()+1,p.getTileY()).equals("w")){
p.move( 1, 0 );
}
}
}
/* public void keyRealeased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}*/
}
}
Map.java
package Maze;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.ImageIcon;
public class Map {
private Scanner m;
private String Map[]=new String[14];
private Image grass,wall,finish,winn;
public Map(){
ImageIcon img = new ImageIcon("C://project//7.jpg");
grass = img.getImage();
img = new ImageIcon("C://project//2.jpg");
wall = img.getImage();
img=new ImageIcon("C://project//hell.gif");
finish=img.getImage();
img=new ImageIcon("C://project//12.jpg");
winn=img.getImage();
openfile();
readfile();
closefile();
}
public Image getGrass()
{
return grass;
}
public Image getWall()
{
return wall;
}
public Image getFinish()
{
return finish;
}
public Image getWinn()
{
return winn;
}
public String getMap(int x, int y){
String index=Map[y].substring(x, x+1);
return index;
}
public void openfile(){
try {
m = new Scanner(new File("C://project//Map.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("Error loading file.");
}
}
public void readfile(){
while(m.hasNext()){
for(int i=0;i<14;i++){
Map[i]=m.next();
}
}
}
public void closefile(){
m.close();
}
}
Player.java
package Maze;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Player {
private int tilex,tiley;
private Image player;
public Player(){
ImageIcon img=new ImageIcon("C://project//5990.gif");
player=img.getImage();
tilex=1;
tiley=1;
}
public Image getPlayer(){
return player;
}
public int getTileX(){
return tilex;
}
public int getTileY(){
return tiley;
}
public void move(int dx, int dy ){
tilex += dx;
tiley += dy;
}
}
and here is the .txt file
Map.txt
wwwwwwwwwwwwww
wggggggwgggggw
wggwwggwgwwggw
wwgggwwwggwggw
wgwgggggggwwgw
wgggwggwwwgggw
wgggwgggwggwww
wggwggwwwggggw
wgwwgggggwwggw
wgggggwwwgwggw
wggwggggwgwwgw
wwwwgwwwwggwgw
wggggwgfgggggw
wwwwwwwwwwwwww
You can do a work around ,Add a timer class which will execute at x seconds and keep on calculating the total seconds in a variable and when the limit is crossed you can stop your program.

Graphics not appearing in JFrame (SSCCE included)

I am making a game (see my previous threads) and have encountered a lot of problems on the way. All I know is that he code compiles, runs, but nothing appears in the window, it's just grey. At Andrew Thompson's suggestion, I am posting the entire compilable version here. Sorry for the length but it is ALL the code in the program. And a lot of things will probably not make sense (unused ActionPerformed to name one), partially because I implemented code in the event that I would need it but mostly because I have never done this before.
Also, so far I have no multithreading, because once again, I am new to this, so ideally I would like to keep it that way, if only for the sake of my sanity.
EDIT: Forgot to mention I have 4 PNGs in there representing the 4 different objects that appear. My code is flexible enough for you to supply your own. Here is the image I am using for ships and here is the one for bullets just make copies, put them the source file and name them "Enemy-ship" "ship2" "Ebullet" and "PBullet"
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.JFrame;
public class GameController extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -3599196025204169130L;
private static GameView window;
private static Timer time;
public GameController()
{
setTitle("Space Shooter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
//window = new GameView(800,600);
//window.setVisible(true);
//
}
//TODO spawn
/*public static void main(String args[])
{
//GameController c = new GameController();
window = new GameView(800,600);
window.setVisible(true);
time = new Timer(40, this);
time.schedule( new TimerTask(){
public void run(){GameState.update();
window.paintComponents(null);}
},0, 40);
}*/
public void display() {
add(new GameView(800,600));
pack();
setMinimumSize(getSize());// enforces the minimum size of both frame and component
setVisible(true);
}
public static void main(String[] args) {
GameController main = new GameController();
main.display();
time = new Timer(40, main);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e instanceof EndEvent)//TODO fix this
{
}
else
{
repaint();
}
}
}
package Game;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GameView extends JComponent implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -2869672245901003704L;
private static final Graphics Graphics = null;
private boolean liveGame;//used so that buttons cannot be clicked after game is complete
private GameState gs;
private Player p;
private int w, h;
public GameView(int width, int height)
{
liveGame = true;
gs = new GameState();
GameState.init(width, height);
p = new Player(width/2,(height*7)/8);
this.setBackground(Color.BLACK);
paintComponents(Graphics);
w = width;
h = height;
}
#Override
public Dimension getMinimumSize() {
return new Dimension(w, h);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(w, h);
}
#Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.black);
GameState.update();
for(Bullet j : GameState.getEnBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Enemy j : GameState.getEnemies()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Bullet j : GameState.getPlayBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
public void paintComponents (Graphics g)
{
for(Bullet j : GameState.getEnBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Enemy j : GameState.getEnemies()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Bullet j : GameState.getPlayBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
this.paint(g);
}
public void refreshImage()
{
this.removeAll();
paintComponents(Graphics);
}
public void actionPerformed(ActionEvent e) {
}
}
package Game;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
public class GameState {
private static ArrayList<Bullet> playBullets;
public static ArrayList<Bullet> getPlayBullets() {
return playBullets;
}
public static ArrayList<Bullet> getEnBullets() {
return enBullets;
}
public static ArrayList<Enemy> getEnemies() {
return enemies;
}
public static Player getP() {
return p;
}
private static ArrayList<Bullet> enBullets;
private static ArrayList<Enemy> enemies;
private static int X, Y;//for limit of screen so nothing can go outside of screen
private static Player p;
private static int score;
public GameState(){
}
public static void init(int x, int y)
{
playBullets = new ArrayList<Bullet>();
enBullets = new ArrayList<Bullet>();
enemies = new ArrayList<Enemy>();
X=x;
Y=y;
p = null;
score =0;
}
public static int xLimit(){return X;}
public static int yLimit(){return Y;}
public static int getScore(){return score;}
public static void add (Location e)
{
if(e instanceof Bullet)
{
if(((Bullet) e).getOwner() instanceof Enemy){
enBullets.add((Bullet) e);
}
else
playBullets.add((Bullet) e);
}
else if(e instanceof Enemy){enemies.add((Enemy)e);}
else
p=(Player)e;
}
public static void spawn()
{
Enemy e = new Enemy(((int)(Math.random()*(X-56))+28), 0, 1);
}
public static void playerCD()//detects if player has collided with anything, removes whatever collided with it, and causes the player to take damage
{
if(enemies.size()>0){
for(int i =0; i < enemies.size(); i++)
{
if (p.getLocation().intersects(enemies.get(i).getLocation()))
{
p.takeDamage(enemies.get(i).getDamage());
enemies.get(i).takeDamage(p.getDamage());
}
}
if(enBullets.size()>0)
for(int i =0; i < enBullets.size(); i++)
{
if (p.getLocation().intersects(enBullets.get(i).getLocation()))
{
p.takeDamage(enBullets.get(i).getDamage());
enBullets.remove(i);
i--;
}
}
}
}
public static void enemyCD()
{
for(int i =0; i < enemies.size(); i++)
{
for(int n =0; n < playBullets.size(); n++)
{
if (playBullets.get(n).getLocation().intersects(enemies.get(i).getLocation()))
{
enemies.get(i).takeDamage(playBullets.get(i).getDamage());
playBullets.remove(n);
n--;
score+=50;
}
}
}
}
public static void checkForDead()//clears away dead and things gone offscreen
{
for(int i =0; i < enemies.size(); i++)
{
if(enemies.get(i).getY()>Y)
{
enemies.remove(i);
i--;
}
}
for(int i =0; i < enBullets.size(); i++)
{
if(enBullets.get(i).getY()>Y)
{
enBullets.remove(i);
i--;
}
}
for(int i =0; i < enemies.size(); i++)
{
if(enemies.get(i).getHealth()>0)
{
enemies.remove(i);
i--;
score+=200;
}
}
if(p.getHealth()<=0)
{
ActionEvent e = new EndEvent(null, 0, "end");
}
}
public static void update()
{
move();
playerCD();
enemyCD();
checkForDead();
}
public static void move()
{
p.move();
for(int i =0; i < enemies.size(); i++){enemies.get(i).move();}
for(int i =0; i < enBullets.size(); i++){enBullets.get(i).move();}
for(int i =0; i < playBullets.size(); i++){playBullets.get(i).move();}
}
}
package Game;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
public abstract class Fights extends Location implements ActionListener {
public Fights(Rectangle location) {
super(location);
// TODO Auto-generated constructor stub
}
public Fights(){}
protected int health;
protected int maxHealth;//in the event that I want to have healing items
protected int shotCooldown;//in milliseconds
protected int shotDmg;
protected long currentCool; //cooldown tracker, represents time that shot will be cooled down by (System time # last shot + shotCooldown
protected int xVel, yVel;
public abstract boolean shoot();
public abstract int takeDamage(int damage);//returns remaining health
protected boolean shoots;//determines whether thing can shoot. possible implementation in some enemy class
public boolean move;
public int getHealth(){return health;}
public abstract boolean move();
public int getDamage(){return shotDmg;}
public boolean isDead()
{
return health<=0;
}
}
package Game;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
public class Location {
protected Rectangle loc;
protected Image image;
public Location(){};
public Location (Rectangle location)
{
loc = location;
}
public Rectangle getLocation()
{
return loc;
}
public void setLocation(Rectangle l)
{
loc = l;
}
public void updateLocation(int x, int y)
{
loc.setLocation(x, y);
}
public Image getImage()
{
return image;
}
public int getX()
{
return (int)loc.getX();
}
public int getY()
{
return (int)loc.getY();
}
}
package Game;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Player extends Fights implements KeyListener{
int speed = 4;
public Player(Rectangle location) {
super(location);
GameState.add(this);
image = null;
try{
image = ImageIO.read(new File("ship2.png"));
}catch(IOException e){}
}
public Player(int x, int y) {
maxHealth = 1;
health = maxHealth;
image = null;
try{
image = ImageIO.read(new File("ship2.png"));
}catch(IOException e){}
this.setLocation(new Rectangle(x, y, image.getWidth(null), image.getHeight(null)));
GameState.add(this);
}
public void resetVelocity()
{
xVel = 0;
yVel = 0;
}
#Override
public boolean shoot() {
if(currentCool - System.currentTimeMillis() >0){return false;}
else
{
new Bullet(this);
currentCool = System.currentTimeMillis() + shotCooldown;
}//spawns bullet in the center and slightly in front of player
return true;
}
#Override
public int takeDamage(int damage) {
return health-=damage;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean move() {//moves in a direction only if it won't exceed screen boundary, boolean just in case i need it later
int newX = this.getX(), newY=this.getY();
if((xVel+ this.getX()+this.getLocation().width)<GameState.xLimit()&& this.getX()+xVel>=0)
{
newX +=xVel;
}
if((yVel+ this.getY()+this.getLocation().height)<GameState.yLimit()&& this.getY()+yVel>=0)
{
newY +=yVel;
}
this.updateLocation(newX, newY);
this.resetVelocity();
return true;
}
#Override
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode()== KeyEvent.VK_LEFT)
{
xVel -= speed;
}
if (arg0.getKeyCode()== KeyEvent.VK_RIGHT)
{
xVel += speed;
}
if (arg0.getKeyCode()== KeyEvent.VK_UP)
{
yVel -= speed;
}
if (arg0.getKeyCode()== KeyEvent.VK_DOWN)
{
yVel += speed;
}
if(arg0.getKeyCode()==KeyEvent.VK_SPACE)
{
this.shoot();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
package Game;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Enemy extends Fights {
public Enemy(Rectangle location) {
super(location);
GameState.add(this);
image = null;
try{
image = ImageIO.read(new File("Enemy-Ship.png"));
}catch(IOException e){}
}
public Enemy(int x, int y, int d) {
image = null;
try{
image = ImageIO.read(new File("Enemy-Ship.png"));
}catch(IOException e){}
this.setLocation(new Rectangle(x, y, image.getWidth(null), image.getHeight(null)));
GameState.add(this);
shotCooldown =(int)(Math.random()*2000);
xVel = (int)((Math.pow(-1, (int)(Math.random())))*((int)(Math.random()*6))+2);
yVel = (int)(Math.random()*3+1);
shotDmg =d;
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean shoot() {
if(currentCool - System.currentTimeMillis() >0){return false;}
else
{
new Bullet(this);
currentCool = System.currentTimeMillis() + shotCooldown;
}//spawns bullet in the center and slightly in front of player
return true;
}
#Override
public int takeDamage(int damage)//returns remaining health
{
health = health-damage;
return health;
}
#Override
public boolean move() {
int newX = this.getX(), newY=this.getY();
if((xVel+ this.getX()+this.getLocation().width)<GameState.xLimit()&& this.getX()+xVel>=0)
{
xVel=-xVel;
newX +=xVel;
}
if(this.getY()+yVel>=0)
{
newY +=yVel;
}
this.updateLocation(newX, newY);
return true;
}
}
package Game;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Bullet extends Location{
private Fights bulletOwner;
private int damage;
private int velocity;
public Bullet(Fights owner)//eventually change to singleton pattern for efficiency
{
bulletOwner = owner;
damage = owner.getDamage();
image = null;
if(owner instanceof Enemy)
{
try{
image = ImageIO.read(new File("Ebullet.png"));
}catch(IOException e){}
this.setLocation(new Rectangle(owner.getX(), owner.getY()+((int)(owner.getLocation().getHeight()/2)), image.getWidth(null), image.getHeight(null)));
velocity = 5;
}
else
{
try{
image = ImageIO.read(new File("Pbullet.png"));
}catch(IOException e){}
this.setLocation(new Rectangle(owner.getX(), owner.getY()-((int)(owner.getLocation().getHeight()/2)), image.getWidth(null), image.getHeight(null)));
velocity = -15;
}
GameState.add(this);
}
public Fights getOwner(){return bulletOwner;}
public int getDamage(){return damage;}
public int getVelocity(){return velocity;}
public boolean move()
{
this.updateLocation(this.getX(), this.getY()+velocity);
return true;
}
}
I can't believe your write 700 lines of code without doing any testing along the way. Its time you go back to the beginning and start with something simple. That is the whole point of a SSCCE. Start with painting a couple of compononents. Once you get that working you add some movement. Once that is working you add collision logic.
The only thing I noticed with a quick broswe is that you override paintComponents(). There is no need to do that custom painting is done in the pantComponent() method.
If you can't produce a smaller sized SSCCE, then all I can do is wish you good luck.
Ok, so I think I have figured most of it out.
You have a couple problems.
First, you should only see a grey screen with a black rectangle in the middle since you have nothing in your Bullet and Enemy Arrays. This is what I got when I ran your code (after removing references to endEvent cuz it couldn't find it). So to fix this, just give it something to draw
The second problem is apparent once you give it something to draw. I manually put in a line of code to draw the Player, for which I used one of my own pngs. When you do this it will fail to compile with a null pointer exception. The reason is because in your GameView class, you have your Graphics object called "graphics" set to null, but then you proceed to call paintComponents(graphics). As mentioned before, this only compiled before because you never actually drew anything. To fix this, you can just remove
public void paintComponents (Graphics g)
{
for(Bullet j : GameState.getEnBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Enemy j : GameState.getEnemies()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Bullet j : GameState.getPlayBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
this.paint(g);
}
and let the overridden paintComponent(Graphics g) method above it do all the work. Additionally, instead of the paintComponents(graphics) calls, use repaint(). Also you can get rid of the first call to paintComponents(graphics) in the constructor as it will paint the first time by default. If you really want to use your own method then you have to create a Graphics object and pass that in.
Lastly, in the overridden paintComponents(Graphics g) method, you have the last line being to draw the giant black box. This will then cover up anything you've drawn before. So you should have that as the first line and draw everything else in order such that the thing you want to be on top should be drawn last. I was able to get my test image to show up with the following code for that class. I don't think I changed anything else.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GameView extends JComponent implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -2869672245901003704L;
private boolean liveGame;//used so that buttons cannot be clicked after game is complete
private GameState gs;
private Player p;
private int w, h;
public GameView(int width, int height)
{
liveGame = true;
gs = new GameState();
GameState.init(width, height);
p = new Player(width/2,(height*7)/8);
this.setBackground(Color.BLACK);
w = width;
h = height;
}
#Override
public Dimension getMinimumSize() {
return new Dimension(w, h);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(w, h);
}
#Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.black);
GameState.update();
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
for(Bullet j : GameState.getEnBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Enemy j : GameState.getEnemies()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
for(Bullet j : GameState.getPlayBullets()){
g.drawImage(j.getImage(),j.getX(), j.getY(), null);}
g.drawImage(p.getImage(),p.getX(),p.getY(),null);
}
public void refreshImage()
{
this.removeAll();
repaint();
}
public void actionPerformed(ActionEvent e) {
}
}
The other thing is in some of your other classes you have #Override over the actionPerformed method. My IDE doesn't like that, although it does compile. It says "#Override is not allowed when implementing interface methods."
Hopefully this works for you.
try adding repaint(); after you make a change to a content pane. I dont think concurrency is going to be a problem unless you clog up your EDT.

Categories

Resources