So heres some code to begin. I first created a class called Bullet. This is where the image should be loaded.
package gameLibrary;
import java.awt.*;
import javax.swing.ImageIcon;
public class Bullet {
int x,y;
Image img;
boolean visible;
public Bullet(int startX, int startY) {
x = startX;
y = startY;
ImageIcon newBullet = new ImageIcon("/resources/bullet.png");
img = newBullet.getImage();
System.out.println("constructor Bullet is called");
visible = true;
}
public void move(){
x = x + 1;
if(x > 854){
System.out.println("Bullet is moving at X = " + x);
visible = false;
}
}
public int getX(){
return x;
}
public int getY() {
return y;
}
public boolean getVisible(){
return visible;
}
public Image getImage(){
return img;
}
}
when the space bar is pressed it calls a method called fire() where a new Bullet(X, Y); is called and then stores it in an ArrayList.
public void fire(){
if(ammo > 0) {
Bullet z = new Bullet(left + 60, y + 70);
bullets.add(z);
ammo--;
}
}
public static ArrayList getBullets(){
return bullets;
}
This code moves the bullet across the screen.
ArrayList bullets = Character.getBullets();
for(int i = 0; i < bullets.size(); i++){
Bullet m = (Bullet) bullets.get(i);
if(m.getVisible() == true){
m.move();
}if(m.getVisible() == false) {
bullets.remove(i);
}
}
And Finally code for the print method.
ArrayList bullets = Character.getBullets();
for(int i = 0; i < bullets.size(); i++){
Bullet m = (Bullet) bullets.get(0);
g2d.drawImage(m.getImage(),m.getX(),m.getY(), null);
}
I cant find where I went wrong. the functioning of the bullet is all working as far as I can tell its just the printing of the image on the screenAny suggestions is much appreciated.
Normally resources are loaded with Class.getResource
ImageIcon newBullet = new ImageIcon(Bullet.class.getResource("resources/bullet.png"));
Of course the resources folder should be in the same package (i.e. in the same folder) as your Bullet class.
That code should always work whether your game is in a jar or not.
I think your resource path is not in the good format.
ImageIcon icon = new ImageIcon("gameLibrary.resources.bullet.png");
if this doesn't work try this code to get your png path:
import java.io.File;
public class GetPath
{
public static void main(String[] args)
{
System.out.println("The user directory: " + System.getProperty("user.dir"));
File fubar = new File("Fubar.txt");
System.out.println("Where Java thinks file is located: " + fubar.getAbsolutePath());
}
}
Tell me what happens.
Related
I'm making a chess program for a school project using swing. this is my first time using swing however I've had a lot of experience with tkinter in python which feels similar. I've gotten the pieces loaded onto board and can load in FEN strings.
The basic board when loaded in
Now I've been trying to move on to allowing the player to capture other pieces. currently I'm not worried about the rules of how pieces can move and I'm just trying to allow them to capture anything.
A little bit of extra knowledge that may be useful is that I have two 2d arrays for the board. one contains a 2d array of 64 buttons (one for each square). the other contains a 2d int array and contains the numerical value of each piece in each square.
the following code is my code for attempting to capture pieces. My thinking behind this implementation is to first find when we select a piece that we want to move. when we click on this piece we store it in selected and set isSelecting equal to true. then the next piece we click on we should capture. The way I've been trying to tackle this is by finding the square we want to capture and changing the piece icon to the icon of the piece we stored in selected. then setting the selected pieces icon to a empty icon. then doing the same for the int array.
public boolean isSelecting;
public JButton selected;
public int[] findSpot(JButton but){
for (int i = 0 ; i < board.length; i++)
for (int j = 0 ; j < board.length; j++)
{
if ( board[i][j] == but)
{
return new int[]{i,j};
}
}
return new int[]{-1,-1};
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println(1);
System.out.println(isSelecting);
if (!isSelecting) {
System.out.println(2);
selected = (JButton) e.getSource();
System.out.println(e.getSource());
} else {
System.out.println(3);
int[] temp = findSpot(selected);
ImageIcon i = new ImageIcon(pieceFiles.get(intBoard[temp[0]][temp[1]]));
Image img = i.getImage() ;
Image newimg = img.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH ) ;
i = new ImageIcon( newimg );
((JButton) e.getSource()).setIcon(i);
int[]temp2 = findSpot(((JButton) e.getSource()));
intBoard[temp[0]][temp[1]] = intBoard[temp2[0]][temp2[1]];
selected.setIcon(new ImageIcon());
intBoard[temp[0]][temp[1]] = none;
selected = null;
}
isSelecting = !isSelecting;
}
This code, however, isn't working and I can't figure out why. The specific problem is the isSelecting variable on becomes false when you click the same piece twice. Clicking two separate pieces does nothing however clicking the same piece twice removes said piece.
The output after clicking the first three pawns
The output after clicking those three pawns for a second time
I'm going to leave my full code here. I'm not sure if I should since it's long but I hope it can give you a better scope of the project.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Hashtable;
import javax.swing.*;
public class Chess implements MouseListener {
static int none = 0;
static int king = 1;
static int pawn = 2;
static int knight = 3;
static int bishop = 4;
static int rook = 5;
static int queen = 6;
static int black = 8;
static int white = 16;
public boolean isSelecting;
public JButton selected;
static JButton[][] board = new JButton[8][8];
static int[][] intBoard = new int[8][8];
static JFrame frame = new JFrame("Big Willy's Chess");
static Hashtable<Integer, String> pieceFiles = new Hashtable<>();
public static void cTable() {
String folder = "C:\\Users\\bookr\\IdeaProjects\\CSA\\src\\pieces";
pieceFiles.put(king + black, folder + "\\Chess_kdt60.png");
pieceFiles.put(king + white, folder + "\\Chess_klt60.png");
pieceFiles.put(pawn + black, folder + "\\Chess_pdt60.png");
pieceFiles.put(pawn + white, folder + "\\Chess_plt60.png");
pieceFiles.put(knight + black, folder + "\\Chess_ndt60.png");
pieceFiles.put(knight + white, folder + "\\Chess_nlt60.png");
pieceFiles.put(bishop + black, folder + "\\Chess_bdt60.png");
pieceFiles.put(bishop + white, folder + "\\Chess_blt60.png");
pieceFiles.put(rook + black, folder + "\\Chess_rdt60.png");
pieceFiles.put(rook + white, folder + "\\Chess_rlt60.png");
pieceFiles.put(queen + black, folder + "\\Chess_qdt60.png");
pieceFiles.put(queen + white, folder + "\\Chess_qlt60.png");
}
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e) {
return false;
}
}
public static void loadFenPos(String fen){
Hashtable<String, Integer> pieceNumbs = new Hashtable<>();
pieceNumbs.put("k", king);
pieceNumbs.put("p", pawn);
pieceNumbs.put("n", knight);
pieceNumbs.put("b", bishop);
pieceNumbs.put("r", rook);
pieceNumbs.put("q", queen);
int rank = 0;
int file = 0;
for (String symbol:fen.split("")) {
if (symbol.equals("/")) {
file = 0;
rank++;
}
else {
if (!isNumeric(symbol)) {
int pieceColor = Character.isUpperCase(symbol.charAt(0)) ? white : black;
int pieceType = pieceNumbs.get(symbol.toLowerCase());
ImageIcon i = new ImageIcon(pieceFiles.get(pieceType+pieceColor));
Image img = i.getImage();
Image newimg = img.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH);
i = new ImageIcon(newimg);
intBoard[rank][file] = pieceType+pieceColor;
board[rank][file].setIcon(i);
file++;
} else {
file += Integer.parseInt(symbol);
}
}
}
}
public void start (){
cTable();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 8));
Color lightSquareColor = new Color(240, 240, 240);
Color darkSquareColor = new Color(128, 128, 128);
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
JButton button = new JButton();
button.setOpaque(true);
button.setBorderPainted(false);
button.setFocusPainted(false);
if ((row + col) % 2 == 0) {
button.setBackground(lightSquareColor);
} else {
button.setBackground(darkSquareColor);
}
button.addMouseListener(new Chess());
panel.add(button);
board[row][col] = button;
}
}
// ImageIcon i = new ImageIcon("C:\\Users\\bookr\\IdeaProjects\\CSA\\src\\pawn.png");
//
//
// Image img = i.getImage() ;
// Image newimg = img.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH ) ;
// i = new ImageIcon( newimg );
// board[6][7].setIcon(i);
loadFenPos("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR");
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(600, 600);
frame.setVisible(true);
}
public static void main(String[] args) {
Chess game = new Chess();
game.start();
}
public int[] findSpot(JButton but) {
for (int i = 0 ; i < board.length; i++)
for(int j = 0 ; j < board.length; j++)
{
if ( board[i][j] == but)
{
return new int[]{i,j};
}
}
return new int[]{-1,-1};
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println(1);
System.out.println(isSelecting);
if (!isSelecting) {
System.out.println(2);
selected = (JButton) e.getSource();
} else {
System.out.println(3);
int[] temp = findSpot(selected);
ImageIcon i = new ImageIcon(pieceFiles.get(intBoard[temp[0]][temp[1]]));
Image img = i.getImage() ;
Image newimg = img.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH ) ;
i = new ImageIcon( newimg );
((JButton) e.getSource()).setIcon(i);
int[]temp2 = findSpot(((JButton) e.getSource()));
intBoard[temp[0]][temp[1]] = intBoard[temp2[0]][temp2[1]];
selected.setIcon(new ImageIcon());
intBoard[temp[0]][temp[1]] = none;
selected = null;
}
isSelecting = !isSelecting;
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
I've tried messing changing around the isSelecting variable, how I assign the selected variable, and how I update the 2d arrays.
Click here to see the questionRobot Race
How can I make multiple robots run simultaneously. I have created run method that keeps track of x and y co-ordinates for each action
import java.util.LinkedList;
import java.util.Queue;
public class Robot implements Runnable {
private int delay;
private String actions;
private String name;
int x = 0;
int y = 0;
// 2d array for 4 direction on cartesian grid
int[][] move = {{0,1}, {1,0}, {-1,0}, {0,-1}};
int dir = 0;
int time = 1;
Queue<Character> queue = new LinkedList<>();
public Robot(int delay, String actions, String name) {
this.delay = delay;
this.actions = actions;
this.name = name;
}
#Override
public void run() {
for (char ch: actions.toCharArray()) {
if (ch == 'F') {
x += move[dir][0];
y += move[dir][1];
} else if (ch == 'L') {
dir++;
} else if (ch == 'R') {
dir--;
}
// to avoid overflow
dir = (dir + 4) % 4;
System.out.println(time+ "s " +name+ ": Moves " +ch);
time++;
try {
Thread.sleep(delay * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Robot(3, "FFFLRFRLFF", "Joe").run();
new Robot(1, "FFFFFLF", "Bill").run();
}
}
`
How can I make multiple robots run simultaneously.
You need to start a separate Thread for each Robot.
The reason your class implements Runnable is so it can be used as a Thread.
So to start a Thread for each Robot the basic code would be:
//new Robot(3, "FFFLRFRLFF", "Joe").run();
Robot robot1 = new Robot(3, "FFFLRFRLFF", "Joe")
new Thread(robot1).start();
When the Thread starts it will invoke the run() method.
So for my final in Java class, we are making an Asteroid game (except a simpler version that the official one, because not enough time).
The problem is when our ship fires a shot (SPACE bar) we add(shot, x, y), but then when we click SPACE bar again it just takes that shot and puts it back to original x, y. So right now we can only fire off one shot at a time to be on the screen. We would like to be able to be able to fire off multiple shots and have them all be visible and stuff.
Not sure how to do that though. Any help is welcome thank you.
P.S. if needed i will add our code.
P.S.S. sorry for posting this again i thought i could edit the post later, thats why i didn't include the code but apparently not.
package week7Homework;
import acm.program.GraphicsProgram;
import java.util.*;
import java.awt.event.*;
import acm.graphics.*;
import java.awt.Color;
import java.awt.Image;
public class space8bit extends GraphicsProgram
{
/* Initialize everything that is needed */
final int WIN_HEIGHT = 800;
final int WIN_WIDTH = 1900;
GImage space = new GImage("/College/IT219/Week7/src/week7Homework/outerspace.png");
GImage ship = new GImage("/College/IT219/Week7/src/week7Homework/ship.png");
GImage explosion = new GImage("/College/IT219/Week7/src/week7Homework/explosion.png");
GImage [] ast = new GImage[6];
Random rand = new Random();
pewpew shots = new pewpew();
int shipx;
int shipy;
public void init()
{
setSize(WIN_WIDTH, WIN_HEIGHT);
add(space);
ship.setLocation(50,330);
ship.scale(.8);
add(ship);
addKeyListeners( );
//scale explosion
explosion.scale(.5);
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode( );
if (key == KeyEvent.VK_UP)
{ ship.move(0, -15); }
/*else if (key == KeyEvent.VK_SPACE)
{ xMove = MV_AMT; }*/
else if (key == KeyEvent.VK_DOWN)
{ ship.move(0, 15); }
else if (key == KeyEvent.VK_SPACE)
{shipx = (int)ship.getX()+195;
shipy = (int)ship.getY() + 80;
add(shots,shipx,shipy);
}
}
public void asteriods()
{
GImage ast1 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1300,100);
GImage ast2 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1750,250);
GImage ast3 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1650,350);
GImage ast4 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1550,650);
GImage ast5 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1450,600);
GImage ast6 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1350,750);
ast [0] = ast1;
ast [1] = ast2;
ast [2] = ast3;
ast [3] = ast4;
ast [4] = ast5;
ast [5] = ast6;
add(ast[0]);
add(ast[1]);
add(ast[2]);
add(ast[3]);
add(ast[4]);
add(ast[5]);
}
public void run()
{
asteriods();
while(true)
{
pause(120);
int random1x = rand.nextInt(-1+1+6)-9;
int random2x = rand.nextInt(-1+1+6)-15;
int random3x = rand.nextInt(-1+1+6)-25;
int random4x = rand.nextInt(-1+1+6)-16;
int random5x = rand.nextInt(-1+1+6)-8;
int random6x = rand.nextInt(-1+1+6)-13;
ast[0].move(random1x, 0);
ast[1].move(random2x, 0);
ast[2].move(random3x, 0);
ast[3].move(random4x, 0);
ast[4].move(random5x, 0);
ast[5].move(random6x, 0);
shots.move(50, 0);
for (int i = 0; i < ast.length; i++)
{
//integer that gets bounds of all rectangles and ovals in the arrays.
GRectangle asteroidBounds = ast[i].getBounds();
//check for collision with other objects
if (shots.getBounds().intersects(asteroidBounds))
{
int shotX = (int)shots.getX();
int shotY = (int)shots.getY();
pause(10);
remove(ast[i]);
add(explosion, shotX-100, shotY - 50);
remove(shots);
pause(25);
remove(explosion);
}
else if (ship.getY() <= 0)
{
ship.move(0, 15);
}
else if (ship.getY() >= WIN_HEIGHT - 168)
{
ship.move(0, -15);
}
}
}
}
}
ALSO HERE IS A SAMPLE CODE, much shorter but does the same thing. Just press SPACEBAR and you will see what im talking about.
package week7Homework;
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
import java.awt.event.*;
public class collisionTry extends GraphicsProgram
{
final int WIN_WIDTH = 500;
final int WIN_HEIGHT = 500;
GOval ship = new GOval(100, 250, 50, 50);
GImage bullet = new GImage("/College/IT219/Week7/src/week7Homework/bullet.gif", 50, 50);
GImage bullet2;
boolean bulletFired;
public void init()
{
setSize(WIN_WIDTH, WIN_HEIGHT);
addKeyListeners();
}
public void run()
{
GRect rect = new GRect(400, 200, 50, 150);
add(rect);
rect.setColor(Color.BLACK);
rect.setFilled(true);
add(ship);
ship.setColor(Color.BLACK);
ship.setFilled(true);
while (true)
{
pause(50);
rect.move(-1, 0);
//bullet.move(5, 0);
if (bulletFired == true)
{
bullet.move(5, 0);
}
if (bullet.getBounds().intersects(rect.getBounds()))
{
remove(rect);
remove(bullet);
}
}
}//run
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_SPACE)
{
int shipX = (int)ship.getX();
int shipY = (int)ship.getY();
add(bullet, shipX+50, shipY+25);
bulletFired = true;
}
else if (key == KeyEvent.VK_UP){
ship.move(0, -5);
}
}
}
It's 'cause you only have 1 bullet in the entire game
if (bulletFired == true) {
bullet.move(5, 0);
}
You're telling that one bullet to go back to (5, 0)
You need to find some way of making a new bullet object each time you press space:
if (key == KeyEvent.VK_SPACE) {
int shipX = (int)ship.getX();
int shipY = (int)ship.getY();
Bullet firedBullet = new Bullet(/* params if any, x? y? */);
add(firedBullet, shipX+50, shipY+25);
bulletFired = true;
}
Though this is my vision of how I'd do things, which probably won't work with your game (I don't know what classes you have, their roles etc). But hopefully you can see what I'm getting at and adapt it.
Now because you have multiple bullets, you also have to take care of their lifetimes. You fired 1000 bullets at the start of the game, they go off-screen. You don't want to waste time drawing them for the rest of the game. So whatever list/array you're using to keep track of objects to draw, you gotta periodically find and remove the ones that have gone off-screen.
Hi every one i am having a bit of trouble with my java game, it is very simply made as i am new to java. and the game works fine well as good as i can achieve. But i am stuck on how i can change the images in real time. I am trying to figure out how to make my Monsters face me "the hero frylark" when they chase me. i have made 2 simple methods in my monster class. left and right How could i apply these methods to make the image change from image = getImage("/Game/images/police-right.png"); to image = getImage("/Game/images/police-left.png");.
Oh and in my project library is golden_0_2_3.jar which contains some game engine stuff.
Please.
Many thanks from edwin.
import com.golden.gamedev.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.awt.event.KeyEvent;
public class MyGame extends Game {
// set the values
public Random random;
private Hero frylark;
private Monster[] monsters = new Monster[3];
private Token coin;
private GameBackGround grass;
private BufferedImage image;
public void initResources() {
// set a new random number
random = new Random();
// get the background image.
image = getImage("/Game/images/background.png");
// set the name "grass" to background and given the image from the image set above.
grass = new GameBackGround("grass", image);
// get the monsters image.
image = getImage("/Game/images/police.png");
// give the monsters their names "" and set them their image from the image set above.
monsters[0] = new Monster("Monster", image);
monsters[1] = new Monster("Monster2", image);
monsters[2] = new Monster("Monster3", image);
// get the tokens image.
image = getImage("/Game/images/donut.png");
// set the name "coin" for the token, then its x and y position, and set the image from the image set above.
coin = new Token("coin", 400, 300, image);
// get the heros image.
image = getImage("/Game/images/snake.png");
// set the name "frylark" for the hero, then his score "0" and lives "5".
frylark = new Hero("Frylark", 0, 5);
//set the monsters random x and y positions.
monsters[0].setX(random.nextInt(750));
monsters[0].setY(random.nextInt(550));
monsters[1].setX(random.nextInt(750));
monsters[1].setY(random.nextInt(550));
monsters[2].setX(random.nextInt(750));
monsters[2].setY(random.nextInt(550));
}
// update method
public void update(long elapsedTime) {
// Pause the hero "frylark" on hold of the space bar.
if (!keyDown(KeyEvent.VK_SPACE)){
// if dead stop frylark moving on the 5 second game over sequence, being displays details and playing the game over sound.
if (Hero.dead(frylark)){
if(keyDown(KeyEvent.VK_LEFT))
{
// Move left
frylark.moveLeft();
}
if (keyDown(KeyEvent.VK_RIGHT))
{
// Move right
frylark.moveRight();
}
if (keyDown(KeyEvent.VK_UP))
{
// Move up on press of up key
frylark.moveUp();
}
if (keyDown(KeyEvent.VK_DOWN))
{
// Move down on press of down key
frylark.moveDown();
}
}
if (keyDown(KeyEvent.VK_ESCAPE))
{
// Exit game on press of esc key.
System.exit(0);
}
}
if (!keyDown(KeyEvent.VK_SPACE))
{
// Pause the monsters on hold of the space bar
monsters[0].chase(frylark);
monsters[1].chase(frylark);
monsters[2].chase(frylark);
}
// if monster 0 has eaten frylark move to a random position and lose a life, plus play the lose life sound.
if (monsters[0].eaten(frylark)) {
monsters[0].setX(random.nextInt(750));
monsters[0].setY(random.nextInt(550));
frylark.loseLife();
playSound("/Game/sounds/lost_a_life.wav");
}
// if monster 1 has eaten frylark move to a random position and lose a life, plus play the lose life sound.
if (monsters[1].eaten(frylark)) {
monsters[1].setX(random.nextInt(750));
monsters[1].setY(random.nextInt(550));
frylark.loseLife();
playSound("/Game/sounds/lost_a_life.wav");
}
// if monster 2 has eaten frylark move to a random position and lose a life, plus play the lose life sound.
if (monsters[2].eaten(frylark)) {
monsters[2].setX(random.nextInt(750));
monsters[2].setY(random.nextInt(550));
frylark.loseLife();
playSound("/Game/sounds/lost_a_life.wav");
}
// if coin is collected increase score and move to a random position, and play the coin collect sound.
if (coin.collected(frylark)) {
coin.setX (random.nextInt(750));
coin.setY (random.nextInt(550));
frylark.increaseScore();
playSound("/Game/sounds/coin.wav");
}
}
public void render(Graphics2D g) {
// draw all the monsters, hero, and coin and background.
g.drawImage(grass.getImage(),grass.getX(),grass.getY(),null);
g.drawImage(monsters[0].getImage(), monsters[0].GetX(), monsters[0].GetY(), null);
g.drawImage(monsters[1].getImage(), monsters[1].GetX(), monsters[1].GetY(), null);
g.drawImage(monsters[2].getImage(), monsters[2].GetX(), monsters[2].GetY(), null);
g.drawImage(image,frylark.getX(),frylark.getY(),null);
g.drawImage(coin.getImage(),coin.getX(),coin.getY(),null);
// if monster 0 overlaps another monster mover him back
if (monsters[0].overlap(monsters)){
monsters[0].x -=20;
monsters[0].y -=70;
}
// if monster 1 overlaps another monster mover him back
if (monsters[1].overlap(monsters)){
monsters[1].x -=21;
monsters[1].y -=70;
}
// if monster 2 overlaps another monster mover him back
if (monsters[2].overlap(monsters)){
monsters[2].x -=22;
monsters[2].y -=70;
}
// draw the lives bar, and set the font colour and size
g.setColor(Color.RED);
g.setFont(new Font("default", Font.BOLD, 18));
for (int i = 0; i < frylark.getLives(); i++) {
g.fillRect( (i + 1) * 15, 10, 10, 10);
}
// draw the score
g.setColor(Color.GREEN);
g.drawString("Score: " + frylark.getScore(), 10, 50);
// draw the level
g.setColor(Color.YELLOW);
g.drawString("level: " + frylark.getScoreNum(), 10, 80);
// game over sequence, changes the font to size 40 and displays game over, as well as the payers score and level reached plus the game over sound.
if (frylark.getLives() ==0){
g.setColor(Color.RED);
g.setFont(new Font("override", Font.BOLD, 40));
g.drawString("Game over !", 280, 290);
playSound("/Game/sounds/game_over.wav");
g.drawString("You reached Level " + frylark.getScoreNum() + " Your Score: " + frylark.getScore(), 60, 330);
}
}
// main method which after all classes have been read and checked, "Game development environment OK! " will be printed to the console.
// then a new game is created and given dimensions and launched.
public static void main(String args[]) {
System.out.println("Game development environment OK! ");
GameLoader gameLoader = new GameLoader();
MyGame myGame = new MyGame();
gameLoader.setup(myGame,new Dimension(800,600),false);
gameLoader.start();
}
}
and my Monster class
import java.util.Random;
import java.awt.image.BufferedImage;
public class Monster {
private String name;
int x;
int y;
private BufferedImage image;
Random rand;
public Monster (String nameIn, BufferedImage imageIn)
{
name = nameIn;
x = 0;
y = 0;
image = imageIn;
}
public void chase(Hero hero) {
if (hero.getX() < x) { // if hero is to the left
x--;
}
if (hero.getX() > x) { // if hero is to the right
x++ ;
}
if (hero.getY() < y) { // if hero is to the above
y--;
}
if (hero.getY() > y) { // if hero is to the below
y++;
}
}
public boolean overlap(Monster monsters[]){
if (monsters[0].x == monsters[1].x && monsters[0].y == monsters[1].y || monsters[0].x == monsters[2].x && monsters[0].y == monsters[2].y ||
monsters[1].x == monsters[0].x && monsters[1].y == monsters[0].y || monsters[1].x == monsters[2].x && monsters[1].y == monsters[2].y ||
monsters[2].x == monsters[0].x && monsters[2].y == monsters[0].y || monsters[2].x == monsters[1].x && monsters[2].y == monsters[1].y) {
return true;
}
else{
return false;
}
}
public boolean eaten(Hero hero) {
if (hero.getX() == x && hero.getY() == y) {
return true;
}
else {
return false;
}
}
public BufferedImage getImage() {
return image;
}
public int GetX(){
return x;
}
public int GetY(){
return y;
}
public String getName()
{
return this.name;
}
public void setX(int xIn) {
x = xIn;
}
public void setY(int yIn) {
y = yIn;
}
public boolean left(Hero hero) {
if (hero.getX() < x) {
return true;
}
else {
return false;
}
}
public boolean right(Hero hero) {
if (hero.getX() > x) {
return true;
}
else {
return false;
}
}
}
I would modify your Monster constructor to accept both images. Then modify Monster.getImage() to call left() and return the correct one based on the result. You probably don't need to call right() as well, since if the monster is not facing left then you know it needs to face right. Unless you want to get more sophisticated and also add a view facing straight forward or backward.
I am trying to have a mouse go through rooms to a target room. I am using a graph-like system with an x and y axis. I have a problem where the computer doesn't seem to want to add or subtract from an already existing variable.
Console:
The mouse is in room (5,4)
The mouse is in room (5,6)
The mouse is in room (6,5)
The mouse is in room (5,4)
The mouse is in room (5,6)
The mouse is in room (5,6)
Code for mouse:
package mouse_maze;
public class Mouse {
private int xCord = 5;
private int yCord = 5;
//position of the mouse when it starts
public int getXCord() {
return this.xCord;
}
public int getYCord() {
return this.yCord;
}
public void move() {
//method for the movement of the mouse
boolean verticalMove = Math.random() < .5;
boolean horizontalMove;
if (verticalMove == true)
horizontalMove = false;
else
horizontalMove = true;
int moveBy = 1;
if (Math.random() < .5)
moveBy = -1;
if (verticalMove) {
int test = this.yCord + moveBy;
if(test < 1 || test > 9) return;
this.yCord += moveBy;
}
if (horizontalMove) {
int test = this.xCord + moveBy;
if(test < 1 || test > 9) return;
this.xCord += moveBy;
}
System.out.println("The mouse is in room (" + xCord + "," + yCord + ")");
}
}
Code for maze:
package mouse_maze;
public class Maze {
private boolean onGoing = false;
private int tarX;
private int tarY;
//creates the target for the mouse.
public static void main(String[] args) {
new Maze(6, 8).init();
}
public Maze(int tarX, int tarY) {
this.tarX = tarX;
this.tarY = tarY;
}
public void init() {
this.onGoing = true;
while(this.onGoing)
this.iterate();
}
public void iterate() {
Mouse m = new Mouse();
m.move();
if (m.getXCord() == tarX && m.getYCord() == tarY) {
this.onGoing = false;
System.out.println("The mouse has beat the maze!");
//checks if the mouse has gotten to the target room.
}
}
}
First, learn to use a debugger, or at least learn to debug by whatever means. It is meaningless to always "assume" the problem without actually proving it.
Your whole problem has nothing to do with random etc.
In your iterate() method, you are creating a new mouse every time, instead of having the same mouse keep on moving.