How to move magic tile by tile on a game? - java

I have a 2D tile game and my hero can use magic(in this case fire), and the goal is to make the fireball move tile by tile until it finds either a wall or an enemy and to make the game stop while the fire is moving. I already have the fire moving and stopping if there is a wall or an enemy(and damaging the enemy). The problem is i can't seem to make the game show the fireball change from tile to tile, which means when i launch the fireball the game automatically shows me the fireball in its last position before collision, and then it disappears from the tiles. Anyone got any ideas as to what I am doing wrong or what i should do to make the game update the fire tile by tile? (Btw i thought it might have something to do with my observer but I've tried thread.sleep and wait() and it isn't quite working, maybe I am doing it the wrong way).Thank you for your help and if you guys need any code just ask.
public class ImageMatrixGUI extends Observable {
private static final ImageMatrixGUI INSTANCE = new ImageMatrixGUI();
private final String IMAGE_DIR = "images";
private final int SQUARE_SIZE;
private final int N_SQUARES_WIDTH;
private final int N_SQUARES_HEIGHT;
private JFrame frame;
private JPanel panel;
private JPanel info;
private Map<String, ImageIcon> imageDB = new HashMap<String, ImageIcon>();
private List<ImageTile> images = new ArrayList<ImageTile>();
private List<ImageTile> statusImages = new ArrayList<ImageTile>();
private int lastKeyPressed;
private boolean keyPressed;
private ImageMatrixGUI() {
SQUARE_SIZE = 48;
N_SQUARES_WIDTH = 10;
N_SQUARES_HEIGHT = 10;
init();
}
public static ImageMatrixGUI getInstance() {
return INSTANCE;
}
public void setName(final String name) {
frame.setTitle(name);
}
private void init() {
frame = new JFrame();
panel = new RogueWindow();
info = new InfoWindow();
panel.setPreferredSize(new Dimension(N_SQUARES_WIDTH * SQUARE_SIZE, N_SQUARES_HEIGHT * SQUARE_SIZE));
info.setPreferredSize(new Dimension(N_SQUARES_WIDTH * SQUARE_SIZE, SQUARE_SIZE));
info.setBackground(Color.BLACK);
frame.add(panel);
frame.add(info, BorderLayout.NORTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initImages();
new KeyWatcher().start();
frame.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
lastKeyPressed = e.getKeyCode();
keyPressed = true;
releaseObserver();
}
});
}
synchronized void releaseObserver() {
notify();
}
synchronized void waitForKey() throws InterruptedException {
while (!keyPressed) {
wait();
}
setChanged();
notifyObservers(lastKeyPressed);
keyPressed = false;
}
private void initImages() {
File dir = new File(IMAGE_DIR);
for (File f : dir.listFiles()) {
assert (f.getName().lastIndexOf('.') != -1);
imageDB.put(f.getName().substring(0, f.getName().lastIndexOf('.')),
new ImageIcon(IMAGE_DIR + "/" + f.getName()));
}
}
public void go() {
frame.setVisible(true);
}
public void newImages(final List<ImageTile> newImages) {
synchronized (images) { // Added 16-Mar-2016
if (newImages == null)
return;
if (newImages.size() == 0)
return;
for (ImageTile i : newImages) {
if (!imageDB.containsKey(i.getName())) {
throw new IllegalArgumentException("No such image in DB " + i.getName());
}
}
images.addAll(newImages);
}
}
public void removeImage(final ImageTile image) {
synchronized (images) {
images.remove(image);
}
}
public void addImage(final ImageTile image) {
synchronized (images) {
images.add(image);
}
}
public void clearImages() {
synchronized (images) {
images.clear();
}
public void newStatusImages(final List<ImageTile> newImages) {
synchronized (statusImages) {
if (newImages == null)
return;
if (newImages.size() == 0)
return;
for (ImageTile i : newImages) {
if (!imageDB.containsKey(i.getName())) {
throw new IllegalArgumentException("No such image in DB " + i.getName());
}
}
statusImages.addAll(newImages);
}
}
public void removeStatusImage(final ImageTile image) {
synchronized (statusImages) {
statusImages.remove(image);
}
public void addStatusImage(final ImageTile image) {
synchronized (statusImages) {
statusImages.add(image);
}
}
public void clearStatus() {
synchronized (statusImages) {
statusImages.clear();
}
}
#SuppressWarnings("serial")
private class RogueWindow extends JPanel {
#Override
public void paintComponent(Graphics g) {
// System.out.println("Thread " + Thread.currentThread() + "
// repainting");
synchronized (images) {
for (ImageTile i : images) {
g.drawImage(imageDB.get(i.getName()).getImage(), i.getPosition().getX() * SQUARE_SIZE,
i.getPosition().getY() * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE, frame);
}
}
}
}
#SuppressWarnings("serial")
private class InfoWindow extends JPanel {
#Override
public void paintComponent(Graphics g) {
synchronized (statusImages) {
for (ImageTile i : statusImages)
g.drawImage(imageDB.get(i.getName()).getImage(), i.getPosition().getX() * SQUARE_SIZE, 0,
SQUARE_SIZE, SQUARE_SIZE, frame);
}
}
}
private class KeyWatcher extends Thread {
public void run() {
try {
while (true)
waitForKey();
} catch (InterruptedException e) {
}
}
}
public void update() {
frame.repaint();
}
public void dispose() {
images.clear();
statusImages.clear();
imageDB.clear();
frame.dispose();
}
public Dimension getGridDimension() {
return new Dimension(N_SQUARES_WIDTH, N_SQUARES_HEIGHT);
}
public void update(Observable arg0, Object arg1) {
Integer keycode = (Integer) arg1;
if (keycode == KeyEvent.VK_DOWN || keycode == KeyEvent.VK_UP || keycode == KeyEvent.VK_LEFT
|| keycode == KeyEvent.VK_RIGHT){
moveTheHero(keycode);
}
if(keycode == KeyEvent.VK_1 || keycode == KeyEvent.VK_2 || keycode == KeyEvent.VK_3){
System.out.println("Key pressed " + KeyEvent.getKeyText(keycode));
dropItem(keycode);
}
if(keycode == KeyEvent.VK_SPACE){
System.out.println("Key pressed " + KeyEvent.getKeyText(keycode));
launchMagic();
}
}
public void launchMagic(){
if(hero.getMagic()!=0){
hero.removeStatus(hero.getMagic()-1);
hero.loseMagic();
Fire fire = new Fire(hero.getPosition());
fire.changeInGame();
Direction direction = fire.closestEnemyDirection(currentRoom);
currentRoom.getTiles().add(fire);
while(fire.getInGame()){
fire.move(currentRoom, direction);
}
currentRoom.removeTiles(fire.getName(), fire.getPosition());
manageEnemies();
gui.newStatusImages(hero.getStatus());
gui.newImages(currentRoom.getTiles());
}else System.out.println("You don't have any magic");
}

Related

Java Swing MVC based Snake game. Issue switching difficulty level

I am writing a game for a snake in Java Swing using the MVC pattern.
The code of Controller and View are shown below. I am trying to implement a button that will help player choose a difficulty level.
The difficulty level is controlled by a timer in the Controller class. I am beginner in Java and help is appreciated.
Code of Controller class:
public class Controller implements KeyListener, ActionListener{
private Renderer renderer;
private Timer mainTimer;
private Snake snake;
public Controller() {
snake = new Snake();
renderer = new Renderer(this);
this.renderer.addKeyListener(this);
this.mainTimer = new Timer(150, this);
mainTimer.start();
}
public void stopGame(){
mainTimer.stop();
}
public void startGame(){
mainTimer.start();
}
public void keyPressed(KeyEvent e) {
snake.onMove(e.getKeyCode());
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void actionPerformed(ActionEvent arg0) {
renderer.moveForward();
}
public Snake getSnake(){
return snake;
}
View class:
class Renderer extends JFrame {
private final int WIDTH = 500;
private final int HEIGHT = 300;
private Snake snake;
public int LevelConst;
private Controller controller;
public JPanel pamel1, panel2;
public JButton[] ButtonBody = new JButton[200];
public JButton bonusfood;
public JTextArea textArea;
public Fruit fruit;
public int score;
public Random random = new Random();
public JMenuBar mybar;
public JMenu game, help, levels;
public void initializeValues() {
score = 0;
}
Renderer(Controller controller) {
super("Snake: Demo");
this.controller = controller;
snake = controller.getSnake();
fruit = new Fruit();
setBounds(200, 200, 506, 380);
creatbar();
initializeValues();
// GUI
pamel1 = new JPanel();
panel2 = new JPanel();
// Scoreboard
setResizable(false);
textArea = new JTextArea("Счет : " + score);
textArea.setEnabled(false);
textArea.setBounds(400, 400, 100, 100);
textArea.setBackground(Color.GRAY);
// Eating and growing up
bonusfood = new JButton();
bonusfood.setEnabled(false);
//
createFirstSnake();
pamel1.setLayout(null);
panel2.setLayout(new GridLayout(0, 1));
pamel1.setBounds(0, 0, WIDTH, HEIGHT);
pamel1.setBackground(Color.GRAY);
panel2.setBounds(0, HEIGHT, WIDTH, 30);
panel2.setBackground(Color.black);
panel2.add(textArea); // will contain score board
// end of UI design
getContentPane().setLayout(null);
getContentPane().add(pamel1);
getContentPane().add(panel2);
show();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void createFirstSnake() {
for (int i = 0; i < 3; i++) {
ButtonBody[i] = new JButton(" " + i);
ButtonBody[i].setEnabled(false);
pamel1.add(ButtonBody[i]);
ButtonBody[i].setBounds(snake.x[i], snake.y[i], 10, 10);
snake.x[i + 1] = snake.x[i] - 10;
snake.y[i + 1] = snake.y[i];
}
}
// Creating of menu bar
public void creatbar() {
mybar = new JMenuBar();
game = new JMenu("Game");
JMenuItem newgame = new JMenuItem("New Game");
JMenuItem exit = new JMenuItem("Exit");
newgame.addActionListener(e -> reset());
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
game.add(newgame);
game.addSeparator();
game.add(exit);
mybar.add(game);
levels = new JMenu("Level");
JMenuItem easy = new JMenuItem("Easy");
easy.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
LevelConst = 0;
}
});
JMenuItem middle = new JMenuItem("Medium");
middle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
LevelConst = 1;
}
});
JMenuItem hard = new JMenuItem("Hard");
hard.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
LevelConst = 2;
}
});
levels.add(easy);
levels.addSeparator();
levels.add(middle);
levels.addSeparator();
levels.add(hard);
mybar.add(levels);
help = new JMenu("Help");
JMenuItem creator = new JMenuItem("There must be a button");
creator.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(pamel1, "Random text");
}
});
help.add(creator);
mybar.add(help);
setJMenuBar(mybar);
}
void reset() {
initializeValues();
pamel1.removeAll();
controller.stopGame();
createFirstSnake();
textArea.setText("Score: " + score);
controller.startGame();
}
void growup() {
ButtonBody[snake.getLength()] = new JButton(" " + snake.getLength());
ButtonBody[snake.getLength()].setEnabled(false);
pamel1.add(ButtonBody[snake.getLength()]);
ButtonBody[snake.getLength()].setBounds(snake.getPointBody()[snake.getLength() - 1].x, snake.getPointBody()[snake.getLength() - 1].y, 10, 10);
snake.setLength(snake.getLength() + 1);
}
void moveForward() {
for (int i = 0; i < snake.getLength(); i++) {
snake.getPointBody()[i] = ButtonBody[i].getLocation();
}
snake.x[0] += snake.getDirectionX();
snake.y[0] += snake.getDirectionY();
ButtonBody[0].setBounds(snake.x[0], snake.y[0], 10, 10);
for (int i = 1; i < snake.getLength(); i++) {
ButtonBody[i].setLocation(snake.getPointBody()[i - 1]);
}
if (snake.x[0] == WIDTH) {
controller.stopGame();
} else if (snake.x[0] == 0) {
controller.stopGame();
} else if (snake.y[0] == HEIGHT) {
controller.stopGame();
} else if (snake.y[0] == 0) {
controller.stopGame();
}
createFruit();
collisionFruit();
pamel1.repaint();
}
private void collisionFruit() {
if (fruit.isFood()) {
if (fruit.getPoint().x == snake.x[0] && fruit.getPoint().y == snake.y[0]) {
pamel1.remove(bonusfood);
score += 1;
growup();
textArea.setText("Score: " + score);
fruit.setFood(false);
}
}
}
private void createFruit() {
if (!fruit.isFood()) {
pamel1.add(bonusfood);
bonusfood.setBounds((10 * random.nextInt(50)), (10 * random.nextInt(25)), 10,
10);
fruit.setPoint(bonusfood.getLocation());
fruit.setFood(true);
}
}
Class Model: Fruit:
public class Fruit {
private Point point;
private boolean food;
public Fruit() {
point = new Point();
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
public boolean isFood() {
return food;
}
public void setFood(boolean food) {
this.food = food;
}
Class Model: Snake:
public class Snake {
private Point[] pointBody = new Point[300];
private int length;
private boolean isLeft;
private boolean isRight;
private boolean isUp;
private boolean isDown;
private int directionX;
private int directionY;
public int[] x = new int[300];
public int[] y = new int[300];
public Snake() {
isLeft = false;
isRight = true;
isUp = true;
isDown = true;
setDirectionX(10);
setDirectionY(0);
length = 3;
y[0] = 100;
x[0] = 150;
}
public void onMove(int side) {
switch (side) {
case KeyEvent.VK_LEFT:
if (isLeft) {
setDirectionX(-10);
setDirectionY(0);
isRight = false;
isUp = true;
isDown = true;
}
break;
case KeyEvent.VK_UP:
if (isUp) {
setDirectionX(0);
setDirectionY(-10);
isDown = false;
isRight = true;
isLeft = true;
}
break;
case KeyEvent.VK_DOWN:
if (isDown) {
setDirectionX(0);
setDirectionY(+10);
isUp = false;
isRight = true;
isLeft = true;
}
break;
case KeyEvent.VK_RIGHT:
if (isRight) {
setDirectionX(+10);
setDirectionY(0);
isLeft = false;
isUp = true;
isDown = true;
}
break;
default:
break;
}
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public Point[] getPointBody() {
return pointBody;
}
public void setPointBody(Point[] pointBody) {
this.pointBody = pointBody;
}
public int getDirectionX() {
return directionX;
}
public void setDirectionX(int directionX) {
this.directionX = directionX;
}
public int getDirectionY() {
return directionY;
}
public void setDirectionY(int directionY) {
this.directionY = directionY;
}
Main:
public class Main {
public static void main(String[] args) {
new Controller();
}
}
Make a property change listener in Controller:
public PropertyChangeListener getViewListener() {
return new ViewListener();
}
private class ViewListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("Level is "+ evt.getNewValue());
//use level
}
}
Invoke createbar by: creatbar(controller.getViewListener());
And use listener :
public void creatbar(PropertyChangeListener listener) {
mybar = new JMenuBar();
mybar.addPropertyChangeListener(listener);//add listener to menu bar
game = new JMenu("Game");
JMenuItem newgame = new JMenuItem("New Game");
JMenuItem exit = new JMenuItem("Exit");
newgame.addActionListener(e -> reset());
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
game.add(newgame);
game.addSeparator();
game.add(exit);
mybar.add(game);
levels = new JMenu("Level");
JMenuItem easy = new JMenuItem("Easy");
easy.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mybar.firePropertyChange("Level", LevelConst, 0); //use listener
LevelConst = 0;
}
});
JMenuItem middle = new JMenuItem("Medium");
middle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mybar.firePropertyChange("Level", LevelConst, 1);
LevelConst = 1;
}
});
JMenuItem hard = new JMenuItem("Hard");
hard.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mybar.firePropertyChange("Level", LevelConst, 2);
LevelConst = 2;
}
});
levels.add(easy);
levels.addSeparator();
levels.add(middle);
levels.addSeparator();
levels.add(hard);
mybar.add(levels);
help = new JMenu("Help");
JMenuItem creator = new JMenuItem("There must be a button");
creator.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(pamel1, "Random text");
}
});
help.add(creator);
mybar.add(help);
setJMenuBar(mybar);
}

Random number generator generates same number until recompilation

Basically, I'm making a "scary" maze game and want the game over picture to change to a different picture every time you fail without having to recompile. Currently, the 'game over' picture stays the same every time you lose until you recompile.
public class MazeGame extends JComponent implements MouseMotionListener, MouseListener
{
private Random generator = new Random();
BufferedImage intro;
BufferedImage level1;
BufferedImage level2;
BufferedImage level3;
BufferedImage pic1;
BufferedImage pic2;
BufferedImage pic3;
BufferedImage pic4;
BufferedImage pic5;
BufferedImage gameOver;
BufferedImage currentLevel;
AudioClip spooky = JApplet.newAudioClip(getClass().getResource("gr/spooky.aiff"));
public MazeGame() throws IOException
{
intro = ImageIO.read(getClass().getResource("gr/start.png"));
level1 = ImageIO.read(getClass().getResource("gr/level1.png"));
level2 = ImageIO.read(getClass().getResource("gr/level2.png"));
level3 = ImageIO.read(getClass().getResource("gr/level3.png"));
pic1 = ImageIO.read(getClass().getResource("gr/pic1.jpg"));
pic2 = ImageIO.read(getClass().getResource("gr/pic2.jpg"));
pic3 = ImageIO.read(getClass().getResource("gr/pic3.jpg"));
pic4 = ImageIO.read(getClass().getResource("gr/pic4.jpg"));
pic5 = ImageIO.read(getClass().getResource("gr/pic5.jpg"));
int number = 1 + generator.nextInt( 5 );
gameOver = ImageIO.read(getClass().getResource( "gr/pic" + number + ".jpg" ));
currentLevel = intro;
}
public static void main(String args[]) throws IOException
{
JFrame window = new JFrame("Totally Not Scary Maze Game");
MazeGame game = new MazeGame();
window.add(game);
window.pack();
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setVisible(true);
game.addMouseMotionListener(game);
game.addMouseListener(game);
}
public Dimension getPreferredSize() {
return new Dimension(800, 800);
}
protected void paintComponent(Graphics g) {
g.setColor(Color.RED);
g.fillRect(0, 0, 800, 800);
g.drawImage(currentLevel, 0, 0, null);
}
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
int color = currentLevel.getRGB(x, y);
System.out.println(color);
int level1WallColor = -13939918;
int level2WallColor = -10340732;
int level3WallColor = -4640206;
int goalColor = -14532251;
if(color == goalColor)
{
if(currentLevel == intro)
{
currentLevel = level1;
}
else if(currentLevel == level1)
{
currentLevel = level2;
}
else if(currentLevel == level2)
{
currentLevel = level3;
}
else if(currentLevel == level3)
{
showGameOver();
}
}
if(color == level1WallColor)
{
showGameOver();
}
if(color == level2WallColor)
{
currentLevel = intro;
}
if(color == level3WallColor)
{
showGameOver();
}
repaint();
}
private void showGameOver()
{
currentLevel = gameOver;
spooky.play();
}
public void mouseClicked(MouseEvent e)
{
if(currentLevel == gameOver)
{
currentLevel = intro;
}
repaint();
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
}
}
That is because you are always setting cuurentLevel as Intro at the the end Mazegame(). Comment this line and try.
currentLevel = intro;
Also I read your code superficially.. Not sure I see where exactly the switching of the picture will happen. You will call your changePic(i.e your mazegame()) right after where the fail is evaluated. so Everytime the evaluation happens failed user will get a changed pic.

Drawing on JPanel and broadcast it to multiple client

I have Multi-user Chat-room with shared whiteboard application where I used a Jpanel to draw in a specific client and then broadcast over server to other clients(through Java Socket Programming).
My issue is that I wanted to make the function of draw work real-time as in as soon as a drawing is done on one client's JPanel it should be visible to the other clients. I wrote the function on mouseReleased event of JPanel, but it is visible to the other clients only after a mouseReleased event is fired on that client's JPanel.
Can anyone suggest something by which I can make the action better(real-time)?
#Override
public void mouseReleased(MouseEvent e) {
lineObject = new LineMessage();
lineObject.setImageMessage(DrawPanel.linelist);
ChatApplication_Client.Action_Paint(lineObject);
}
ChatApplication_Client.java
public void run(){
System.out.println("Listening for messages from server . . . ");
try{
while(!receivingdone){
object = myInputStream.readObject();
if(object instanceof LineMessage)
{
lineObject = (LineMessage) object;
WhiteBoardMessageReceive(lineObject);
}
}
}
// This method responsible for re-painting and broadcasting at client's end
private void WhiteBoardMessageReceive(LineMessage lineObject)
{
ArrayList<Line> linelist = (ArrayList)
lineObject.getImageMessage();
ChatClient_GUI.TA_ChatWindow.append(lineObject.Name+": "
+lineObject.Text + "\n" + "At ["
+DateUtils.now()+ "] " + "\n");
drawPanel.drawit(linelist);
}
//The Following method is called from the gui on mouseReleased event
public static void Action_Paint(LineMessage lineObject)
{
try
{
myOutputStream.reset();
myOutputStream.writeObject(lineObject);
myOutputStream.flush();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
LineMessage.java
class LineMessage implements Serializable
{
ArrayList<Line> message;
Line line = new Line();
String Name =line.getName() ;
String Text ;
public void setImageMessage(Object message) {
this.message = (ArrayList) message;
}
public Object getImageMessage() {
return message;
}
}
class Line extends ChatMessage implements Serializable {
int startx, starty, endx, endy;
public Line() {
}
public Line(int sx, int sy, int ex, int ey)
{
setStartX(sx);
setStartY(sy);
setEndX(ex);
setEndY(ey);
}
public void setStartX(int sx) {
startx = sx;
}
public void setStartY(int sy) {
starty = sy;
}
public void setEndX(int ex) {
endx = ex;
}
public void setEndY(int ey) {
endy = ey;
}
public int getStartX() {
return startx;
}
public int getStartY() {
return starty;
}
public int getEndX() {
return endx;
}
public int getEndY() {
return endy;
}
}
List<Point> pointList = new ArrayList<>();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 500);
JPanel panel = new JPanel(){
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
Point l = null;
for(Point p : pointList){
if(l != null && p != null)
g.drawLine(l.x, l.y, p.x, p.y);
l = p;
}
}
};
frame.setContentPane(panel);
panel.addMouseMotionListener(new MouseMotionListener() {
boolean isDrawing = false;
#Override
public void mouseDragged(MouseEvent e) {
pointList.add(e.getPoint());
isDrawing = true;
panel.repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
if(isDrawing)
pointList.add(null); //null is a placeholder to mean line is finished
isDrawing = false;
}
});
frame.setVisible(true);

Game in Java is not displaying

Hello everyone I am trying to make a game where the user plays as some kind of character, and trys to collect coins while avoiding monsters that spawn. My program compiles with no error, but nothing is showing up when I run the applet. This could be because of the order of extension I have everything in but I am not sure. Any help would be greatly appreciated (this is for a final school project for my intro to Java class). Here is the code, I know it is long but it all pertains to the question at hand:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Sprite extends JApplet
{
Image image;
int x, y;
boolean isVisible;
public Sprite()
{
isVisible = false;
image = null;
}
public Sprite(Image i)
{
isVisible = true;
image = i;
x = 10;
y = 10;
}
public void setImage(Image img)
{
image = img;
isVisible = true;
}
public void setLocation(int _x, int _y)
{
x = _x;
y = _y;
}
public Rectangle getDimensions()
{
return new Rectangle(x, y, image.getWidth(null), image.getHeight(null));
}
public boolean intersects(Sprite s)
{
return getDimensions().intersects(s.getDimensions());
}
public void setVisible(boolean vis)
{
isVisible = vis;
}
public void paintComponent(Graphics g)
{
if(isVisible)
{
g.drawImage(image, x, y, null);
}
}
}
class Coins extends Sprite
{
int amount;
public Coins(int amt)
{
amount = amt;
}
public int getAmount()
{
return amount;
}
public void setAmount(int amt)
{
amount = amt;
}
}
class AnimateSprite extends Sprite
{
int speed = 5;
int directionX = 1, directionY = 1;
int healthPoints = 100;
final boolean DEAD = false;
final boolean ALIVE = true;
public void moveUp()
{
y -= speed;
}
public void moveDown()
{
y += speed;
}
public void moveLeft()
{
x -= speed;
}
public void moveRight()
{
x += speed;
}
public int getHealthPoints()
{
return healthPoints;
}
public void setHealthPoints(int hp)
{
healthPoints = hp;
}
public boolean hit(int amt)
{
healthPoints -= amt;
if(healthPoints < 0)
return DEAD;
else
return ALIVE;
}
}
class Game extends AnimateSprite implements Runnable, KeyListener
{
AnimateSprite user;
AnimateSprite monster, troll;
Coins ten, twenty;
Thread thread;
Random r;
public void init()
{
r = new Random();
user = new AnimateSprite();
user.setImage(getImage(getCodeBase(), "player.gif"));
monster = new AnimateSprite();
monster.setImage(getImage(getCodeBase(), "monster.gif"));
troll = new AnimateSprite();
troll.setImage(getImage(getCodeBase(), "monster.gif"));
troll.setLocation(350, 350);
setupCoins();
setFocusable(true);
addKeyListener(this);
thread = new Thread(this);
thread.start();
}
public void setupCoins()
{
ten = new Coins(10);
twenty = new Coins(20);
ten.setLocation(400, 350);
twenty.setLocation(450, 50);
ten.setImage(getImage(getCodeBase(), "coins.gif"));
twenty.setImage(getImage(getCodeBase(), "coins.gif"));
}
public void keyPressed(KeyEvent ke) //Event handling
{
int key = ke.getKeyCode();
if(key == KeyEvent.VK_UP)
user.moveUp();
else if(key == KeyEvent.VK_DOWN)
user.moveDown();
else if(key == KeyEvent.VK_LEFT)
user.moveLeft();
else if(key == KeyEvent.VK_RIGHT)
user.moveRight();
}
public void keyReleased(KeyEvent ke) {}
public void keyTyped(KeyEvent ke) {}
public void update(Graphics g) {paint(g);}
public void paint(Graphics g)
{
g.clearRect(0, 0, this.getWidth(), this.getHeight());
ten.paintComponent(g);
twenty.paintComponent(g);
monster.setLocation(r.nextInt(10) - 5 + monster.x, r.nextInt(10 - 5 + monster.y));
monster.paintComponent(g);
user.paintComponent(g);
if(user.intersects(monster))
{
g.setFont(new Font("Serif", Font.BOLD, 26));
g.drawString("YOU HAVE DIED, YOU LOSE!", 20, 100); //Prints this when you lose
thread.interrupt(); //Stopping the thread if you die
}
}
public void run()
{
try //Try catch
{
while(true) //Only does this while when the boolean is true
{
repaint();
Thread.sleep(10); //Thread sleeps
}
} catch(Exception e) {} //Exception handling
}
}
Your order of inheritance seems odd, but its not whats causing the problem. Take a look at this website: http://www.dreamincode.net/forums/topic/28410-application-to-japplet-and-reverse/
Java Applets need to have init(), start(), stop(), and destroy(). You will need to put these methods in your Sprite class for the Applet to function.

How do you restart a Java applet?

I'm making a game for a school project and have been stuck on this part for a few days. How would I go about restarting the following applet? I have tried to make a restart() method, but lack the necessary skills.
package main;
import game.framework.Animation;
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.lang.Thread.State;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JPanel;
//add speedboost
public class Main extends Applet implements Runnable, KeyListener{
enum GameState {
Running, Dead
}
static GameState state = GameState.Running;
private Background bg2, bg1;
private boolean restart = false;
private Player player;
private SpeedBoost sb1;
private Image image;
private Image backsprite1, backsprite2;
private Image player1, dad1, dad2, dad3;
private Image player2;
private Image player3;
private Image back1;
private Image back2, endscreen;
private Image back3, coin, bigcoin;
private Image back4, sbimg;
public Image tilebase, platform;
private Block block1, block2, block3, block4;
private Coin coin1, coin2, coin3, coin4, coin5;
private LargeCoin bc1;
//use for the base...
private Dad dad;
private Graphics second;
private Animation playwalk, dadwalk;
private URL base;
private Platform plat1, plat2, plat3, plat4, plat5, plat6, plat7;
public static int score = 1, coinsint = 1;
public static String score2, coins = "1";
public static int scorespeed = 1;
public int hs1, hs2, hs3, hs4, hs5, totcoins;
public String hs1s, hs2s, hs3s, hs4s, hs5s, totcoinss;
public Ends ends;
#Override
public void init() {
setSize(800, 480);
setBackground(Color.WHITE);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Game v1.2.2");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}
endscreen = getImage(base, "data/endscreen.png");
coin = getImage(base, "data/coin.png");
bigcoin = getImage(base, "data/bigcoin.png");
tilebase = getImage(base, "data/tilebase.png");
platform = getImage(base, "data/blocksmall.png");
back1 = getImage(base, "data/back1.png");
back2 = getImage(base, "data/back2.png");
back3 = getImage(base, "data/back3.png");
back4 = getImage(base, "data/back4.png");`enter code here`
sbimg = getImage(base, "data/speedboost.png");
player1 = getImage(base, "data/player1.png");
player2 = getImage(base, "data/player2.png");
player3 = getImage(base, "data/player3.png");
dad1 = getImage(base, "data/dad1.png");
dad2 = getImage(base, "data/dad2.png");
dad3 = getImage(base, "data/dad3.png");
backsprite1 = back1;
backsprite2 = back2;
playwalk = new Animation();
playwalk.addFrame(player1, 80);
playwalk.addFrame(player2, 80);
playwalk.addFrame(player3, 80);
dadwalk = new Animation();
dadwalk.addFrame(dad1, 80);
dadwalk.addFrame(dad2, 80);
dadwalk.addFrame(dad3, 80);
}
public void animate() {
playwalk.update(15);
dadwalk.update(15);
}
#Override
public void start() {
state = state.Running;
ends = new Ends(-3, 0);
//create objects at positions
coin1 = new Coin(-100, -10);
coin2 = new Coin(-10, -10);
coin3 = new Coin(-10, -10);
coin4 = new Coin(-10, -10);
coin5 = new Coin(-10, -10);
player = new Player();
dad = new Dad();
bg1 = new Background(1, 0);
bg2 = new Background(2099, 0);
plat1 = new Platform(0,0);
plat2 = new Platform(-100,0);
plat3 = new Platform(-200,0);
plat4 = new Platform(-300,0);
plat5 = new Platform(-400,0);
plat6 = new Platform(-500,0);
plat7 = new Platform(-600,0);
sb1 = new SpeedBoost(-100, 0);
bc1 = new LargeCoin(-99, 0);
block1 = new Block(0, 0);
block2 = new Block(0, 0);
block3 = new Block(0, 0);
block4 = new Block(0, 0);
Thread thread = new Thread(this);
thread.start();
}
#Override
public void stop() {
// TODO Auto-generated method stub
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void run() {
if (state == GameState.Running) {
while (true) {
//selecting sprites for the background
//updates go here
if(bg1.getBgX() < -2100){
bg1.setBgX(2100);
}
if(bg2.getBgX() < -2100){
bg2.setBgX(2100);
}
//backgrounds arent working
if(bg1.getBgX() > 2000){
Random rand = new Random();
int nel = rand.nextInt(4) + 1;
if(nel == 1){
backsprite1 = back1;
}if(nel == 2){
backsprite1 = back2;
}if(nel == 3){
backsprite1 = back3;
}if(nel == 4){
backsprite1 = back4;
}
}
if(bg2.getBgX() > 2000){
Random rand = new Random();
int n1 = rand.nextInt(4) + 1;
if(n1 == 1){
backsprite2 = back1;
}if(n1 == 2){
backsprite2 = back2;
}if(n1 == 3){
backsprite2 = back3;
}if(n1 == 4){
backsprite2 = back4;
}
}
block4.update();
block3.update();
block2.update();
block1.update();
sb1.update();
bc1.update();
player.update();
dad.update();
bg1.update();
bg2.update();
coin1.update();
coin2.update();
coin3.update();
coin4.update();
coin5.update();
plat1.update();
plat2.update();
plat3.update();
plat4.update();
plat5.update();
plat6.update();
plat7.update();
if(Block.lives < 0){
state = GameState.Dead;
}
animate();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
#Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}
//other updates go here
block1.update();
block2.update();
block3.update();
block4.update();
sb1.update();
bc1.update();
coin1.update();
coin2.update();
coin3.update();
coin4.update();
coin5.update();
plat1.update();
plat2.update();
plat3.update();
plat4.update();
plat5.update();
plat6.update();
plat7.update();
bg1.update();
bg2.update();
player.update();
dad.update();
second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);
g.drawImage(image, 0, 0, this);
}
#Override
public void paint(Graphics g) {
if (state == GameState.Running) {
//main graphics identifyers here
// first are drawn below last
//need to make the platform lower down, see class for explanation
g.drawImage(backsprite1, bg1.getBgX(), bg1.getBgY(), this);
g.drawImage(backsprite2, bg2.getBgX(), bg2.getBgY(), this);
g.drawImage(playwalk.getImage(), player.getCenterX(), player.getCenterY(), this);
g.drawImage(platform, plat1.getCenterX(), plat1.getCenterY(), this);
g.drawImage(platform, plat2.getCenterX(), plat2.getCenterY(), this);
g.drawImage(platform, plat3.getCenterX(), plat3.getCenterY(), this);
g.drawImage(platform, plat4.getCenterX(), plat4.getCenterY(), this);
g.drawImage(platform, plat5.getCenterX(), plat5.getCenterY(), this);
g.drawImage(platform, plat6.getCenterX(), plat6.getCenterY(), this);
g.drawImage(platform, plat7.getCenterX(), plat7.getCenterY(), this);
g.drawImage(sbimg, sb1.getCenterX(), sb1.getCenterY(), this);
g.drawImage(bigcoin, bc1.centerX, bc1.centerY, this);
g.drawImage(dadwalk.getImage(), dad.centerX, dad.centerY, this);
g.drawImage(tilebase, block1.getCenterX(), block1.getCenterY(), this);
g.drawImage(tilebase, block2.getCenterX(), block2.getCenterY(), this);
g.drawImage(tilebase, block3.getCenterX(), block3.getCenterY(), this);
g.drawImage(tilebase, block4.getCenterX(), block4.getCenterY(), this);
g.drawImage(coin, coin1.getCenterX(), coin1.getCenterY(), this);
g.drawImage(coin, coin2.getCenterX(), coin2.getCenterY(), this);
g.drawImage(coin, coin3.getCenterX(), coin3.getCenterY(), this);
g.drawImage(coin, coin4.getCenterX(), coin4.getCenterY(), this);
g.drawImage(coin, coin5.getCenterX(), coin5.getCenterY(), this);
g.setColor(Color.MAGENTA);
g.drawString(score2, 700, 25);
Font font = new Font("Serif", Font.PLAIN, 36);
g.setFont(font);
g.drawString(coins, 20, 25);
}else if (state == GameState.Dead) {
totcoins += coinsint;
coinsint = 0;
hs1s = String.valueOf(hs1);
hs2s = String.valueOf(hs2);
hs3s = String.valueOf(hs3);
hs4s = String.valueOf(hs4);
hs5s = String.valueOf(hs5);
totcoinss = String.valueOf(totcoins);
if(score > hs1){
hs1 = score;
}else if(score > hs2){
hs2 = score;
}else if(score > hs3){
hs3 = score;
}else if(score > hs4){
hs4 = score;
}else if(score > hs5){
hs5 = score;
}
scorespeed = 0;
//format this shit up in here
//when restart is init, then this will be tested
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 480);
g.setColor(Color.WHITE);
g.drawString(hs1s, 230, 220);
g.drawString(hs2s, 230, 250);
g.drawString(hs3s, 230, 280);
g.drawString(hs4s, 230, 310);
g.drawString(hs5s, 230, 340);
g.drawString(totcoinss, 700, 100);
g.drawImage(endscreen, ends.cornX, ends.cornY, this);
}
}
//fix the android stuff
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
player.jump();
Player.jumps += 1;
break;
}
switch (e.getKeyCode()) {
case KeyEvent.VK_SPACE:
if(state == state.Dead){
}
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
break;
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public Background getBg1() {
return bg1;
}
public void setBg1(Background bg1) {
this.bg1 = bg1;
}
public Background getBg2() {
return bg2;
}
public void setBg2(Background bg2) {
this.bg2 = bg2;
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public Image getBacksprite() {
return backsprite1;
}
public void setBacksprite(Image backsprite) {
this.backsprite1 = backsprite;
}
public Image getBacksprite1() {
return backsprite1;
}
public void setBacksprite1(Image backsprite1) {
this.backsprite1 = backsprite1;
}
public Image getBacksprite2() {
return backsprite2;
}
public void setBacksprite2(Image backsprite2) {
this.backsprite2 = backsprite2;
}
public Image getPlayer1() {
return player1;
}
public void setPlayer1(Image player1) {
this.player1 = player1;
}
public Image getPlayer2() {
return player2;
}
public void setPlayer2(Image player2) {
this.player2 = player2;
}
public Image getPlayer3() {
return player3;
}
public void setPlayer3(Image player3) {
this.player3 = player3;
}
public Image getBack1() {
return back1;
}
public void setBack1(Image back1) {
this.back1 = back1;
}
public Image getBack2() {
return back2;
}
public void setBack2(Image back2) {
this.back2 = back2;
}
public Image getBack3() {
return back3;
}
public void setBack3(Image back3) {
this.back3 = back3;
}
public Image getBack4() {
return back4;
}
public void setBack4(Image back4) {
this.back4 = back4;
}
public Graphics getSecond() {
return second;
}
public void setSecond(Graphics second) {
this.second = second;
}
public Animation getPlaywalk() {
return playwalk;
}
public void setPlaywalk(Animation playwalk) {
this.playwalk = playwalk;
}
public URL getBase() {
return base;
}
public void setBase(URL base) {
this.base = base;
}
public static Image getTilebase() {
// TODO Auto-generated method stub
return null;
}
public GameState getState() {
return state;
}
public void setState(GameState state) {
this.state = state;
}
public SpeedBoost getSb1() {
return sb1;
}
public void setSb1(SpeedBoost sb1) {
this.sb1 = sb1;
}
public Image getCoin() {
return coin;
}
public void setCoin(Image coin) {
this.coin = coin;
}
public Image getSbimg() {
return sbimg;
}
public void setSbimg(Image sbimg) {
this.sbimg = sbimg;
}
public Image getPlatform() {
return platform;
}
public void setPlatform(Image platform) {
this.platform = platform;
}
public Block getBlock1() {
return block1;
}
public void setBlock1(Block block1) {
this.block1 = block1;
}
public Block getBlock2() {
return block2;
}
public void setBlock2(Block block2) {
this.block2 = block2;
}
public Block getBlock3() {
return block3;
}
public void setBlock3(Block block3) {
this.block3 = block3;
}
public Block getBlock4() {
return block4;
}
public void setBlock4(Block block4) {
this.block4 = block4;
}
public Coin getCoin1() {
return coin1;
}
public void setCoin1(Coin coin1) {
this.coin1 = coin1;
}
public Coin getCoin2() {
return coin2;
}
public void setCoin2(Coin coin2) {
this.coin2 = coin2;
}
public Coin getCoin3() {
return coin3;
}
public void setCoin3(Coin coin3) {
this.coin3 = coin3;
}
public Coin getCoin4() {
return coin4;
}
public void setCoin4(Coin coin4) {
this.coin4 = coin4;
}
public Coin getCoin5() {
return coin5;
}
public void setCoin5(Coin coin5) {
this.coin5 = coin5;
}
public Platform getPlat1() {
return plat1;
}
public void setPlat1(Platform plat1) {
this.plat1 = plat1;
}
public Platform getPlat2() {
return plat2;
}
public void setPlat2(Platform plat2) {
this.plat2 = plat2;
}
public Platform getPlat3() {
return plat3;
}
public void setPlat3(Platform plat3) {
this.plat3 = plat3;
}
public Platform getPlat4() {
return plat4;
}
public void setPlat4(Platform plat4) {
this.plat4 = plat4;
}
public Platform getPlat5() {
return plat5;
}
public void setPlat5(Platform plat5) {
this.plat5 = plat5;
}
public Platform getPlat6() {
return plat6;
}
public void setPlat6(Platform plat6) {
this.plat6 = plat6;
}
public Platform getPlat7() {
return plat7;
}
public void setPlat7(Platform plat7) {
this.plat7 = plat7;
}
public static int getScore() {
return score;
}
public static void setScore(int score) {
Main.score = score;
}
public static int getCoinsint() {
return coinsint;
}
public static void setCoinsint(int coinsint) {
Main.coinsint = coinsint;
}
public static String getScore2() {
return score2;
}
public static void setScore2(String score2) {
Main.score2 = score2;
}
public static String getCoins() {
return coins;
}
public static void setCoins(String coins) {
Main.coins = coins;
}
public static int getScorespeed() {
return scorespeed;
}
public static void setScorespeed(int scorespeed) {
Main.scorespeed = scorespeed;
}
public void setTilebase(Image tilebase) {
this.tilebase = tilebase;
}
}
A good approach might be to use the methods like this:
init (should be called once, and by the browser only). Set up any common GUI elements and call the startNewGame() method.
start (called when the user restores the browser). Un-pause the action (paused in stop) and continue the game.
stop pause the current game.
startNewGame() set the initial lives, layout of pieces/characters, score etc.
When the user wants to start a new game, also call startNewGame().
I know this is an old question.
but the format of the applet above seems to be the issue. I would use something basic that would allow more control of the applet.
"Namely using a while(true) is never a good option in my opinion"
public class TestAppletCycle extends JApplet implements Runnable {
private Thread thread;
private boolean running;
#Override
public void init() {
// Init Game
}
#Override
public void start() {
if(!running) {
running = true;
thread = new Thread(this);
thread.start();
}
}
#Override
public void run() {
while(running) {
// Game Loop
}
}
#Override
public void stop() {
logger.log(Level.INFO, "TestAppletCycle.stop();");
if(running) {
running = false;
try {
thread.join();
} catch(Exception e) {
}
}
}
#Override
public void destroy() {
// Clean Up Game
}
}
Now to restart the applet you only need to stop and start the applet.

Categories

Resources