libgdx creating multiple objects in different places - java

I want to spawn my item (Sword1) in random places. When i spawn it, first of all it only creates 1 of it, then it moves randomly everywhere. Should I create and array for the object? How?
public class Sword1 {
public static TextureRegion sprite;
public static int x;
public static int y;
public static int size;
public static boolean created;
public Sword1(){
created=true;
Random r = new Random();
x = (r.nextInt(5)+1)*GameRender.tilesize;
y = (r.nextInt(5)+1)*GameRender.tilesize;
size = GameRender.tilesize;
sprite = AssetLoader.s1;
createMe();
}
public static void createMe() {
GameRender.batch.draw(sprite, x, y, size, size);
}
}
I render it in batch:
while(number<4){
number++;
Items.createSwords();
}
I also tried to use Items class that would hold all the Items when there would be more
public class Items {
public Items(){}
public static void createSwords() {
Object sword = (Sword1) new Sword1();
}
}

You can clean up and rename a bit the Sword1 class [I also changed the static variables to private] otherwise they will be shared across the various class instances see: Static Variables — What Are They?.
public class Sword {
private TextureRegion sprite;
private int x;
private int y;
private int size;
public Sword() {
Random r = new Random();
x = (r.nextInt(5)+1)*GameRender.tilesize;
y = (r.nextInt(5)+1)*GameRender.tilesize;
size = GameRender.tilesize;
sprite = AssetLoader.s1;
}
public void createMe() {
GameRender.batch.draw(sprite, x, y, size, size);
}
}
Then to have multiple swords you can use and an ArrayList of Swords the class that is using the Sword object GameRender as given in comment:
private List<Sword> swords = new ArrayList<Sword>();
for more info on Array see the Oracle documentation
Now you would have a List of Swords objects. This list will be used to store the newly create Sword objects and to render them later.
create swords
//create 10 swords
for (int i = 0; i<10 ; i++ ) {
swords.add(new Sword());
}
render swords , call the create method in each object
for (Sword sword : swords) {
sword.createMe();
}
for example a minimal example in the GameRender Class
public class GameRender() {
private List<Sword> swords = new ArrayList<Sword>();
public GameRender(){
// create the swords
for (int i = 0; i<10 ; i++ ) {
swords.add(new Sword());
}
// render the swords
public void render() {
for (Sword sword : swords) {
sword.createMe();
}
}
}

Related

Why can't I instantiate new objects using a for loop, to fill an array?

I'm trying to make a tile map for a text based game, for my first Java project. When I try to use a for loop to add new objects(tiles) to each spot in the map, I get the error Type mismatch: cannot convert from Tile to Array. Where am I going wrong here?
public class helloworld {
public static void main(String args[]) {
world x = new world();
Tile y = new Tile();
System.out.println(y);
for(int i = 0; i < x.tileGrid.length; i++) {
for(int j = 0; j < x.tileGrid[i].length; j++) {
x.tileGrid[i][j] = new Tile();
}
}
}
}
import java.lang.reflect.Array;
public class world{
Array tileGrid[][] = new Array[10][20];
public static void createWorld() {
}
}
public class Tile {
String tileType = "Grass";
Boolean passable = true;
#Override
public String toString() {
return tileType;
}
}
You created array of arrays.
It should be like this
public class world{
Tile tileGrid[][] = new Tile[10][20];
public static void createWorld() {
}
}
Please do not name classes with small letter. They should always start with capital letter.

How to check if a ship sank in battleship game java

I start to create battleship game in java. I have 5 ships with length 5,4,3,3,2 and an array int gameBoard[][] = new int[10][10]; where i put the ships. I also create an array boolean BoardHits[][]= new boolean[10][10]; where i check the hits of the player.
Now i want to create a method boolean getBoardStrike(int[] hit) which takes as parameter a position and adds a hit at BoardHits array if this position has not been hitted again. If we hit a ship the we must check if all ship positions hitted(ship sank). Are there any efficient way to implement this?
(When i put a ship in the array gameBoard i put the ship id, so if i a ship with length 5 in the board i have 5 cells with the number 5).
public boolean getBoardStrike(int[] hit) {
boolean flag = true;
if (boardHits[hit[0]][hit[1]] = false) {
hits[hit[0]][hit[1]] = true;
//check if the whole ship is hitted
return true;
}
else {
return false;
}
}
I would try more object oriented approach since Java is object-oriented language:
public interface Battleship {
public void hit(Point shot);
public List<Point> getCoordinates();
public boolean isSinked();
}
public class BattleshipPart {
private boolean hit;
private Point coordinate;
// getters and setters
}
public abstract class AbstractBattleship implements Battleship {
// these are for direction in constructors
public static int NORTH = 1;
public static int EAST = 2;
public static int SOUTH = 3;
public static int WEST = 4;
protected List<BattleshipPart> parts;
public void hit(Point shot) {
return parts.stream()
.findFirst(part -> part.coordinate.equals(shot))
.ifPresent(part -> part.setHit(true));
}
public List<Point> getCoordinates() {
return parts.stream()
.map(part -> part.getCoordinate())
.collect(Collectors.toList());
}
public boolean isSinked() {
return parts.stream()
.allMatch(BattleshipPart::isHit);
}
}
public final class SmallBattleship extends AbstractBattleship {
public SmallBattleship(Point start, int direction) {
// create parts or throw exception if parameters weren't valid
}
}
New ship types are created just by extending AbstractBattleship and just creating new parts in constructor.

Getting ArrayStoreException error when trying to add a subclass object to super class array

I am making a checkers game and have the following classes.
Abstract class piece:
public abstract class Piece {
protected Position position;
private CheckersColor color;
public Piece(CheckersColor color, Position position) {
this.position = position;
this.color = color;
}
with some more methods.
The sub class Checker:
public class Checker extends Piece {
public Checker(CheckersColor color, Position position) {
super(color, position);
}
with also some more methods, and another sub class king:
public class King extends Piece {
public King(CheckersColor color, Position position) {
super(color, position);
}
public King(Piece checker) {
super(checker.getColor(), checker.position);
}
The checkers are stored in an array of type Piece
private Piece[] whiteCheckers;
and inserted by :
whiteCheckers[counter] = new Checker(Constants.COLOR_WHITE, tempPosition);
So far everything works, but when I try to change one of the checkers into a king I get an error:
Exception in thread "main" java.lang.ArrayStoreException: King
The code that causes the error:
whiteCheckers[i] = new King(piece);
I have tried a few different ways to store it, with casting, removing the checker and adding the king in the same spot and more with no luck.
That's really weird to me because the checkers were stored with no problem and king causes the error while they are both sub classes of Piece.
Thanks a lot!
EDIT:
public class Board {
private int size;
private Piece[] blackCheckers;
private Piece[] whiteCheckers;
private Piece[][] board;
public Board(int size) {
....(Some other code)
for (int k = 0; k < whiteCheckers.length; k++) {
board[whiteCheckers[k].position.getRow()][whiteCheckers[k].position.getColumn()] = whiteCheckers[k];
board[blackCheckers[k].position.getRow()][blackCheckers[k].position.getColumn()] = blackCheckers[k];
}
} else {
throw new RuntimeException("The size is either smaller than 4 or is not even");
}
}
....(Some more methods)
public void verifyCrown(Piece piece) {
if ((piece.getColor().equals(Constants.COLOR_WHITE) && piece.position.getRow() == 0)
|| piece.getColor().equals(Constants.COLOR_BLACK) && piece.position.getRow() == size - 1) {
if (piece.getColor().equals(Constants.COLOR_WHITE)) {
for (int i = 0; i < whiteCheckers.length; i++) {
if (whiteCheckers[i].equals(piece)) {
whiteCheckers[i] = new King(piece);
}
}
}
if (piece.getColor().equals(Constants.COLOR_BLACK)) {
for (int i = 0; i < blackCheckers.length; i++) {
if (blackCheckers[i].equals(piece)) {
blackCheckers[i] = new King(piece);
}
}
}
....
}
}
}
Can you please show us how the array is initialized?
The cause could be that you initialize the array as follows:
Piece[] whiteCheckers = new Checker[n];
instead of
Piece[] whiteCheckers = new Piece[n];
which would not allow you to add objects of type King to it.
But again without seeing how the array was initialized, this may not be the case.

How to get name of the object's from a different class in Java

I am using Greenfoot IDE and i have a World Class and a Boat class and a Exit class
Inside the Boat class i have a constructor which defines the boat (what kinda boat it is & which picture).
Boat Code:
public class Boat extends Actor
{
private int size;
private int speed;
private int slow = 1;
private boolean leeg = false;
private int id;
private int time;
public void act() {
MoveBoat();
MoveMouse();
ExitHarbor(time);
Dock();
Colission();
}
public Boat(int newSize, int i, int t) {
size = newSize;
id = i;
time = t;
setImage(id);
}
public void setImage(int i) {
if (!leeg) {
setImage(new GreenfootImage("Boat"+i+".png"));
}
else {
setImage(new GreenfootImage("Boatleeg"+i+".png"));
}
}
}
Inside the Exit class I have a constructor which defines the different Exit's
Exit:
public class Exit extends Actor
{
private String color;
private int points;
/**
* Act - do whatever the Exit wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public Exit(String kleur) {
color = kleur;
setImage(kleur);
}
public void setImage(String kleur) {
//Game1 game = getWorld().getObjects(Boat.class);
setImage(new GreenfootImage("exit"+kleur+".png"));
}
public String getColor()
{
return color;
}
}
In the World class i added 3 different boats & 3 different exits to the so called "World" of greenfoot with different parameters. Now i have 3 different boats & 3 different Exits.
World:
public class Game1 extends World
{
/**
* Constructor for objects of class Game1.
*
*/
public Game1()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(900, 900, 1);
prepare();
}
public void prepare()
{
Exit exit1 = new Exit("paars");
addObject(exit1, 885, 615);
Exit exit2 = new Exit("groen");
addObject(exit2, 885, 472);
Exit exit3 = new Exit("geel");
addObject(exit3, 885, 340);
Boat boat1 = new Boat(10,1,700);
addObject(boat1, 500,61);
Boat boat2 = new Boat(20,2,500);
addObject(boat2, 800,61);
Boat boat3 = new Boat(30,3,300);
addObject(boat3, 650,61);
}
}
The problem I'm having at the moment is that i wan't to specify 1 boat to 1 exit. To clear it more i wan't that boat 1 can only interact with the "geel" Exit (or exit1).
I already tried some code but i can't get it to work.
Tried code:
if (id == 1 && "geel".equals(exit.getColor()))
I think i can make it work with this if but for that i need to retrieve the objects from the World class or from the Boat class, I don't know how to do it? i tried
Actor boat = (Actor)getWorld().getObjects(Boat.class).get(0);
But that doesn't return the 3 different Boats (including their object(variable) names)
Anyone any suggestions?
p.s It is more code but i only showed the code which is necesarry for this problem
after The reactions i tried some but I'm stuck again`
public void ExitBoat(Exit exit, int size) {
this.exit = exit;
System.out.println(exit);
/* if(exit == exit1 && size == 10) {
System.out.println("jdjdf");
}*/
}
public Boat(Exit uitgang, int newSize, int i, int t) {
exit = uitgang;
size = newSize;
id = i;
time = t;
setImage(id);
}
now I'm stuck again i dont know how to call the method with the right parameters in my public void act.
You could add Exit as a field in the Boat class
private Exit exit;
add the exit to Boats constructor so you can create the Boat instances like this.
Boat boat1 = new Boat(exit1, 10,1,700);

A new object seems to change the fields of previous objects

I'm writing a game which contains elevators as an obstacle. An elevator spawns either left or right of the screen and has a random chance to be an ascending elevator or a descending elevator. It looks like this:
public class Elevator extends WorldObject {
public static boolean ascending;
public Elevator(int screenHeight, int xPos) {
super(xPos, screenHeight, 0, 0);
ascending = new Random().nextBoolean();
}
static public boolean isAscending(){
return ascending;
}
}
WorldObject from which it extends looks like this:
public class WorldObject {
protected float posX;
protected float posY;
protected float velX, velY;
public float getPosX() {
return posX;
}
public void setPosX(float posX) {
this.posX = posX;
}
public float getPosY() {
return posY;
}
public void setPosY(float posY) {
this.posY = posY;
}
public float getVelX() {
return velX;
}
public void setVelX(float velX) {
this.velX = velX;
}
public float getVelY() {
return velY;
}
public void setVelY(float velY) {
this.velY = velY;
}
public WorldObject(float posX, float posY, float velX, float velY) {
this.posX = posX;
this.posY = posY;
this.velX = velX;
this.velY = velY;
}
}
Every 5 seconds an elevator will be created and added to an ArrayList of Elevators like so:
if (timeToElevator > 5.0f) {
timeToElevator = 0;
Elevator elevator = new Elevator((int) screenHeight, (int) generateElevatorXPos());
Sprite eSprite = new Sprite(elevatorTexture);
eSprite.setOrigin(0, 0);
elevators.add(elevator);
elevatorSprites.add(eSprite);
}
I then check for collisions in each elevator with the player, remove it if it goes out of bounds and if neither of these happen I update the position of the elevator object:
public static void calculateElevatorCollisions() {
int counter = 0;
for (Iterator<Elevator> i = elevators.iterator(); i.hasNext(); ) {
Elevator item = i.next();
if (item.getPosY() < -100) {
//remove elevator
} else if (..collision..) {
//collision
} else {
item.setVelY(item.isAscending() ? -5 : 5);
item.setPosY(item.getVelY() + item.getPosY());
elevatorSprites.get(counter).setPosition(item.getPosX(),
item.getPosY());
counter++;
}
My issue is whenever a new Elevator is created all current Elevators change their direction to the direction of the new Elevator. So suppose I have two ascending elevators being drawn, whenever my third elevator is created to be descending, the other two previously ascending elevators now ascend!
What's causing this?
This is your problem:
public static boolean ascending;
^^^^^^
static means "This is a class field that is shared by all objects". So if you changed the field from one object, it will be noticed across all objects of that type.
Removing it to make ascending an instance field means that each instance of Elevator will have its own copy which it can modify by itself without changing other instances' copy.
Change
public static boolean ascending;
To
public boolean ascending;
When you set a variable as static it is a class variable, not an instance variable. Class variables are variables that are shared across all instances of an object, whereas instance variables are specific to that instance of the object.
As I can't comment yet (rep), I want to make another note:
You are practicing encapsulation using the getter for ascending, isAscending(); however, the field you are encapsulating is public, making it accessible from all scopes.
It's good practice to keep encapsulated fields private.
Also, it seems as if everyone is only stating that the field be changed to a non-static variable; however, the method is still static, even though it is actually an instance method as well!
Resulting changes needed:
public static boolean ascending;
becomes
private boolean ascending;
...and...
static public boolean isAscending()
becomes
public boolean isAscending()

Categories