Car is not moving right? - java

Car is moving but as it reaches column 5 it stops there and does not move.
Car has the move() method, in which Car instances drive forwards with the amount of cells equivalent to speed in each time step (from left to right).
Car shall accelerate its speed by 1 after each time step and the speed for the next time step will be higher
public class Car extends Actor {
public final int MAXSPEED= 5;
private int speed = 3;
public void move() {
Grid<Actor> gr = this.getGrid();
if (gr != null) {
Location loc = this.getLocation();
Location next = new Location(0,this.speed);
if (gr.isValid(next)) {
this.moveTo(next);
} else {
this.removeSelfFromGrid();
}
}
}
public void accelerate(){
if (this.speed <5) {
// move();
this.speed++;
} else {
this.speed = MAXSPEED;
}
}
public void dawdle(){
if(Math.random() <= 0.3){
this.speed= speed--;
}else{
this.speed=speed;
}
}
public Car(){
if (speed==1){
this.setColor(Color.red);
}
else if (speed==5){
this.setColor(Color.green);
}
}
#Override
public void act(){
this.move();
this.accelerate();
this.dawdle();
}
}

Your accelerate function allows the car to have a maximum speed of 5.
Together with your move function, which contains
Location next = new Location(0,this.speed);
the car will never go beyond position 5. I think you know what needs to be changed:
newlocation = currentLocation + speed
I do not see anything like this in your code.

To move the car i needed the car current position so speed can be added into the current position to move the car.
Location next = new Location(loc.getRow(),loc.getCol()+this.speed);

Related

How does one set a number of spaces based on user input?

The assignment is asking me to create a class named Vehicle that stimulates a car moving along a 40 block stretch of road.
Here's more information:
Your class will build a vehicle and keep track of its location on the road. Location values may range from -20 to 20. A location value of 0 represents block 0, a location value of 1 represents block 1, a location value of 2 represents block 2, etc. If the user tries to move the vehicle beyond block +20 or -20, set the location to +/- 20 respectively.(I dont understand how to do this part)
Variable
int location - An integer that holds the current block location of the car on the road, with possible values ranging from -20 to 20.
Methods
Vehicle () - Sets location to 0.
Vehicle (int loc) - If loc is between -20 and 20 inclusive, sets location to loc. Otherwise, sets location to 0.
void forward () - Increments the vehicle forward one block. Do not let the user move past block 20.
void backward () - Increments the vehicle backward one block. Do not let the user move past block -20.
int getLocation () - Returns an integer representing the block location of the car.
String toString () - Returns a String representation showing the vehicle as an # character, with spaces to show its location. When the vehicle is at location -20 the # character appears at the start of the String. When the vehicle is at a higher position, one space for each number from -20 to the car's current location appears before the #. For example if the car is at block -10, the method will return " #" (10 spaces then the '#'). If the car is at block 5 the method will return " #" (25 spaces then the '#').
Here's my code so far(this is in my Vehicle.java file) :
public class Vehicle
{
private int location;
public Vehicle(int loc)
{
return location;
}
public void forward()
{
if (location>=-20 && location <=20)
{
location++;
}
}
public void backward()
{
if (location>=-20 && location <=20)
{
location--;
}
}
public int getLocation()
{
return location;
}
public String toString()
{
return "";
}
}
Here is the runner file:
import java.util.Scanner;
public class runner_Vehicle
{
public static void main (String str[]){
Scanner scan = new Scanner(System.in);
Vehicle v = new Vehicle ();
String instruction = "";
while(!instruction.equals("q")){
System.out.println(v);
System.out.println("Location: " + v.getLocation());
System.out.println("Type \"f\" to move forwards, \"b\" to move backwards, \"n\" for new vehicle, \"q\" to quit.");
instruction = scan.nextLine();
if(instruction.equals("f")){
v.forward();
}
else if(instruction.equals("b")){
v.backward();
}
else if(instruction.equals("n")){
System.out.println("Starting location for new vehicle?");
int start = scan.nextInt();
v = new Vehicle(start);
scan.nextLine();
}
else if(!instruction.equals("q")){
System.out.println("Instruction not recognized.");
}
}
}
}
If the user tries to move the vehicle beyond block +20 or -20, set the location to +/- 20 respectively. (I dont understand how to do this part)
Simply check it and cap the value
public void forward()
{
location++;
if (location > 20) location = 20;
}
public void backward()
{
location--;
if (location < 20) location = -20;
}
Regarding the toString method - Look at the StringBuilder class
StringBuilder sb = new StringBuilder();
for (int i = -20; i <= 20; i++) {
if (i == getLocation()) {
sb.append("#");
}
else sb.append(" ");
}
return sb.toString();
First time answering a question, but hope I can be of some help:
I've tried to explain what each thing does in places I thought you might have been confused. If you are going to hand this in, please remove the comments.
class Vehicle {
private int location;
public Vehicle() {
// Known as the constructor.
// Creates an instance of the class, meaning it creates the vehicle object when you say
// Vehicle car = new Vehicle();
location = 0;
}
public Vehicle(int loc) {
// known as a parameterized constructor, which is just a constructor but you give it some default values.
// It does not return a value, all it does it make the object in question.
// In this case, it would be a Vehicle object.
if (loc >= -20 && loc <= 20) {
location = loc;
}
}
public void forward() {
location++;
if (location >= 21) {
location = -20;
}
}
public void backward() {
location--;
if (location <= -21) {
location = 20;
}
}
public int getLocation() {
return location;
}
public String toString() {
String output = "";
for (int i = -20; i < location; i++) {
output += ' ';
}
return output + '#';
}
}
Hopefully that helps!

Greenfoot - isKeyDown() seems to hold its value

This is a sprinting function for a game, if the player has greater then 0% spring left then he can sprint, if it is at 0% the player cannot sprint. If the player is not sprinting then the sprint % will start to regenerate.
The problem:
When the player hits 0% sprint the player is still able to sprint.
public class User extends Characters
{
private int walk = 3;
private int run = 10;
private int speed = walk;
private boolean isRunning = false;
private int runDuration = 100;
private int baseRunDuration = 100;
private int runCoolDown = 300;
public void act()
{
playerMove();
}
//Contains movement inputs as well as run imputs
void playerMove(){
getWorld().showText("Run Duration: " + runDuration, 100, 100);
if(Greenfoot.isKeyDown("w") ){
setLocation(getX(), getY()-speed);
}
if(Greenfoot.isKeyDown("a")){
move(-speed);
}
if(Greenfoot.isKeyDown("s")){
setLocation(getX(), getY()+speed);
}
if(Greenfoot.isKeyDown("d")){
move(+speed);
}
if(Greenfoot.isKeyDown("shift") && runDuration > 0){
if(runDuration > 0){
isRunning = true;
speed = run;
runDuration--;
}
}
else{
speed = walk;
isRunning = false;
}
if(isRunning == false){
if(runDuration < baseRunDuration){
runDuration++;
}
}
}
}
Obicere is right that you are either sprinting, or you're alternately sprinting and not sprinting, giving a half-speed sprint. There's various ways to fix this. I'd suggest only recharging your sprint when you're not moving. You can do this using a boolean to keep track of whether you've moved this frame, or simply by using else-if to change your middle block of code to:
if(Greenfoot.isKeyDown("w") ){
setLocation(getX(), getY()-speed);
}
else if(Greenfoot.isKeyDown("a")){
move(-speed);
}
else if(Greenfoot.isKeyDown("s")){
setLocation(getX(), getY()+speed);
}
else if(Greenfoot.isKeyDown("d")){
move(+speed);
}
else if(runDuration < baseRunDuration){
runDuration++;
}
Note the new elses, and the final clause on the end which is moved up from the bottom of your code.

Make an image change on hero direction, Simple 2D game

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.

pattern when using Math.random

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.

Smooth movement in Java

I'm making a simulation in a 3D environment. So far, I have the movements of all the creatures, but it is not "smooth". I've tried quite a few things but was horribly wrong. Now I just have no idea what to do. I was thinking of implementing a vector (not vector class) but don't really know how.
import env3d.EnvObject;
import java.util.ArrayList;
abstract public class Creature extends EnvObject
{
/**
* Constructor for objects of class Creature
*/
public Creature(double x, double y, double z)
{
setX(x);
setY(y);
setZ(z);
setScale(1);
}
public void move(ArrayList<Creature> creatures, ArrayList<Creature> dead_creatures)
{
double rand = Math.random();
if (rand < 0.25) {
setX(getX()+getScale());
setRotateY(90);
} else if (rand < 0.5) {
setX(getX()-getScale());
setRotateY(270);
} else if (rand < 0.75) {
setZ(getZ()+getScale());
setRotateY(0);
} else if (rand < 1) {
setZ(getZ()-getScale());
setRotateY(180);
}
if (getX() < getScale()) setX(getScale());
if (getX() > 50-getScale()) setX(50 - getScale());
if (getZ() < getScale()) setZ(getScale());
if (getZ() > 50-getScale()) setZ(50 - getScale());
// collision detection
if (this instanceof Fox) {
for (Creature c : creatures) {
if (c.distance(this) < c.getScale()+this.getScale() && c instanceof Tux) {
dead_creatures.add(c);
}
}
}
}
}
import env3d.Env;
import java.util.ArrayList;
/**
* A predator and prey simulation. Fox is the predator and Tux is the prey.
*/
public class Game
{
private Env env;
private boolean finished;
private ArrayList<Creature> creatures;
/**
* Constructor for the Game class. It sets up the foxes and tuxes.
*/
public Game()
{
// we use a separate ArrayList to keep track of each animal.
// our room is 50 x 50.
creatures = new ArrayList<Creature>();
for (int i = 0; i < 55; i++) {
if (i < 5) {
creatures.add(new Fox((int)(Math.random()*48)+1, 1, (int)(Math.random()*48)+1));
} else {
creatures.add(new Tux((int)(Math.random()*48)+1, 1, (int)(Math.random()*48)+1));
}
}
}
/**
* Play the game
*/
public void play()
{
finished = false;
// Create the new environment. Must be done in the same
// method as the game loop
env = new Env();
// Make the room 50 x 50.
env.setRoom(new Room());
// Add all the animals into to the environment for display
for (Creature c : creatures) {
env.addObject(c);
}
// Sets up the camera
env.setCameraXYZ(25, 50, 55);
env.setCameraPitch(-63);
// Turn off the default controls
env.setDefaultControl(false);
// A list to keep track of dead tuxes.
ArrayList<Creature> dead_creatures = new ArrayList<Creature>();
// The main game loop
while (!finished) {
if (env.getKey() == 1) {
finished = true;
}
// Move each fox and tux.
for (Creature c : creatures) {
c.move(creatures, dead_creatures);
}
// Clean up of the dead tuxes.
for (Creature c : dead_creatures) {
env.removeObject(c);
creatures.remove(c);
}
// we clear the ArrayList for the next loop. We could create a new one
// every loop but that would be very inefficient.
dead_creatures.clear();
// Update display
env.advanceOneFrame();
}
// Just a little clean up
env.exit();
}
/**
* Main method to launch the program.
*/
public static void main(String args[]) {
(new Game()).play();
}
}
You haven't shown enough of your program. Basically, if you want animation to be smooth, and you want to do it yourself (as opposed to using JavaFX or something), then you need to do lots of inter-frames. So rather than advancing an entire timer tick, advance a 10th of a timer tick, move everything on a screen a tiny bit, and then advance again. You should have the background redraw happening every 10th of a second for smooth animation.
As vy32 mentioned, we need to see more of your code. But it looks like you are missing timing code.
What you probably want to do is check the time each iteration of your game loop and then sleep for a certain amount of time to achieve some desired frame rate. Otherwise your game loop will run hundreds of thousands of times a second.
Alternatively, you should be advancing your creatures by a distance that is proportional to the amount of time that has elapsed since the previous frame.
Here is an example of a very simple regulated loop ("fps" is the desired framerate):
private long frameLength = 1000000000 / fps;
public void run() {
long ns = System.nanoTime();
while (!finished) {
//Do one frame of work
step();
//Wait until the time for this frame has elapsed
try {
ns += frameLength;
Thread.sleep(Math.max(0, (ns - System.nanoTime())/10000000));
} catch (InterruptedException e) {
break;
}
}
}
It should be very easy to retrofit this into your game loop.

Categories

Resources