Это задание, поэтому большая часть конструкции прописана. У нас есть пакет с двумя классами, один Car
и один City
. В методе main
от Город, cars
были настроены, чтобы работать друг с другом в 9,0. Мы должны закодировать так, чтобы программа обнаруживала, когда автомобиль падает. Я смотрю на петлю вложенного цикла в Город и не могу понять, как заставить его работать.for loop in simple java car game
Класс автомобиля:
public class Car {
private int x ,y;
private int facing;
/*
* where 0 = north, 1 = east, 2 = south, 3 = west.
*/
private int distance;
public Car(int x, int y, int facing){
//"this" only has to be used because
//the variable names are identical
//"this" indicates that the variable
//declared at the top is being referenced.
//the x on the right-hand side is the local
//variable in the method
this.x = x;
this.y = y;
this.facing = facing;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getFacing() {
return facing;
}
public void setFacing(int facing) {
this.facing = facing;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public void turnLeft() {
if (facing == 0) {
facing = 3;
}
else {
facing -= 1;
}
}
public void turnRight() {
if (facing == 3) {
facing = 0;
}
else {
facing += 1;
}
}
public void move (int distance) {
if (facing == 0) {
distance = distance + y;
y = distance;
}
else if (facing == 1) {
distance = distance + x;
x = distance;
}
else if (facing == 2) {
distance = y - distance;
y = distance;
}
else {
distance = x - distance;
x = distance;
}
}
}
Город Класс:
import java.util.*;
public class City {
private List<Car> cars = new ArrayList<Car>();
private int sizeX;
private int sizeY;
public City (int sizeX, int sizeY) {
}
public void addCar(Car car) {
cars.add(car);
}
public void moveCar(Car car, int distance) {
for (int n = 0; n<distance; n++) {
car.move(1);
for (int i = 0; i<cars.size(); i++) {
Car otherCar = cars.get(i);
if (car != otherCar) {
////this is where I'm getting stuck
//trying to figure out how to use this
//to detect when cars run into each other
}
}
}
System.out.print("Car is at "+ "" + car.getX() + ","+ car.getY() +"\n");
}
public int getSizeX() {
return sizeX;
}
public void setSizeX(int sizeX) {
this.sizeX = sizeX;
}
public int getSizeY() {
return sizeY;
}
public void setSizeY(int sizeY) {
this.sizeY = sizeY;
}
public static void main(String[] args) {
City city = new City(10,10);
Car c1 = new Car(0,0,1);
Car c2 = new Car(9,9,2);
city.addCar(c1);
city.addCar(c2);
city.moveCar(c1,9);
city.moveCar(c2,9);
}
}
Это как вся часть задания! Сначала попробуйте сами – Idos
поиск, как сравнивать объекты равенства в java – haifzhan
Автомобили пробегают друг друга, когда их положение (X и Y) равны. – MaxZoom