java text based world moving elements around - java

I have a project that i cannot for the life of me figure out the moving pattern, whether some object is in the same place as another, or how to interact with each project, here is the first class:
public class AnimalKingdom {
public static final int WORLD_ROWS = 4;
public static final int WORLD_COLUMNS = 4;
public static final int ROUNDS = 10;
public static void main(String[] args) {
Animal[] animals = new Animal[10];
animals[0] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[1] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[2] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[3] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[4] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[5] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[6] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[7] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[8] = new Wolf(WORLD_ROWS, WORLD_COLUMNS);
animals[9] = new Wolf(WORLD_ROWS, WORLD_COLUMNS);
for (int i = 1; i < ROUNDS; i++) {
showWorld(animals);
doEating(animals);
doMoving(animals);
}
}
public static void showWorld(Animal[] animals) {
System.out.println();
System.out.println("The World");
/* The world is made of rows and columns.
Each location must be big enough to list all the animals
(in case they all show up at that spot at once). So we print
the single character string for each animal, then later add in enough
blanks to ensure that the lines between locations are neatly
drawn. */
for (int r = 0; r < WORLD_ROWS; r++) {
for (int c = 0; c < WORLD_COLUMNS; c++) {
int localAnimals = 0;
for (int a = 0; a < animals.length; a++) {
if (animals[a] != null) { // as animals die, nulls will be left in the array
int ar = animals[a].getRow();
int ac = animals[a].getCol();
if (r == ar && c == ac) { // this animal is local to this location
localAnimals++;
System.out.print(animals[a]); // draw the animal
}
}
}
// create enough blanks to fill out the location
for (int i = 0; i < animals.length-localAnimals; i++) {
System.out.print(" ");
}
System.out.print("|");
}
System.out.println();
}
System.out.println();
}
public static void doEating(Animal[] animals) {
// This needs to be filled in
}
public static void doMoving(Animal[] animals) {
// This needs to be filled in
}
}
And here is the second part of my coding:
import java.util.Random;
public class Animal {
private Random rand = new Random();
private int worldWidth;
private int worldHeight;
private int row;
private int col;
public Animal(int worldHeight, int worldWidth) {
this.worldHeight = worldHeight;
this.worldWidth = worldWidth;
row = rand.nextInt(worldHeight);
col = rand.nextInt(worldWidth);
}
public boolean willEat(Animal anim) {
return false;
}
public void move() {
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public void setRow(int r) {
row = r;
}
public void setCol(int c) {
col = c;
}
public String toString() {
return "";
}
public int getWorldWidth(){
return worldWidth;
}
public int getWorldHeight(){
return worldHeight;
}
public boolean isInSamePlaceAs(Animal other) {
return false; // code needs to be replaced
}
}
Each subclass is named Worm, Bird, and Wolf. Each subclass toString is represented in the form of one char. 'B' for Bird, '.' for Worm, and 'W' for Wolf. The worms can move left and right, remembering the direction they are going in and reverse if they hit a wall or end/beginning of array. The Bird moves diagonally in the world. The Wolf is allowed to move in any direction.
I just need help with starting to make movements in the doMoving(), help identify isInSamePlaceAs() and help doEating(). Birds eat worms, Wolves eat Birds, and worms do nothing.

Related

Java. Array, save previous values

Cant figure out how to do this thing. I need to store and count number of "jumps" and direction of "jump" in array.
Console has to display something like this:
: Jump 1, direction Left
: Jump 2, direction Right
In my code below, when I print array elements, int jump always equals to 0;
I tried many variations, sometimes I got (for example):
jump();
jump();
jump();
jump();
And it prints: {0,0,0,4} , instead of {1,2,3,4};
public class Jump {
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;
public void jump() {
jump++;
if (jump > 50) {
System.out.println("need a rest");
return;
} else {
for (int i = 0; i < jumpArray.length; i++) {
jumpArray[i] = new Jump();
}
}
jumpArray[jump].storeJump = jump;
jumpArray[jump].storeDirection = direction;
}
public static void main(String[] args) {
Jump jumper = new Jump();
jumper.jump();
jumper.jump();
for (int i = 0; i < jumper.jump; i++) {
System.out.println(jumper.jumpArray[i].jump);
}
}
}
I think the code below will solve your problem, but I think You should improve your code.
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;
public void jumping() {
jump++;
if (jump > 50) {
System.out.println("need a rest");
return;
} else {
jumpArray[jump] = new Jump();
}
jumpArray[jump].storeJump = jump;
jumpArray[jump].storeDirection = direction;
}
public static void main(String[] args) {
Jump jumper = new Jump();
jumper.jumping();
jumper.jumping();
Set<Jump> mySet = new HashSet<Jump>(Arrays.asList(jumper.jumpArray));
for (int i = 1; i < mySet.size(); i++) {
System.out.println(jumper.jumpArray[i].storeJump);
}
}
I think it would make more sense to move the jumpArray into main():
public class Jump {
String direction;
//int storeJump; Not sure what this is for
//String storeDirection; Or this
#Override
public String toString() {
return direction;
}
// Static function that creates an initializes a Jump object
public static Jump jump(String direction) {
Jump jump = new Jump();
jump.direction = direction;
return jump;
}
public static void main (String[] args)
{
Jump[] jumpArray = new Jump[100];
int numJumps = 0;
// A list of directions for testing
String [] path = new String[]{"north", "south", "east", "west"};
// Create a bunch of jumps
for (String dir : path) {
if (numJumps > 50) {
System.out.println("need a rest");
break;
}
// Create a new jump and add to the array
jumpArray[numJumps++] = Jump.jump(dir);
}
// Print the jumps
for (int i = 0; i < numJumps; i++) {
System.out.println(i + " " + jumpArray[i]);
}
}
}

Beginner: How to return user input?

I'm new to Java and I'm having trouble with this bit of code:
import java.util.Scanner;
public class BattleshipLogic {
private final int rows;
private final int cols;
private final boolean[][] hits;
private final boolean[][] ships;
public BattleshipLogic(int numRows, int numCols) {
this.rows = numRows;
this.cols = numCols;
this.hits = new boolean[rows][cols];
this.ships = new boolean[rows][cols];
}
public void startGame() {
placeShips();
boolean gameOver = false;
// draw field for the first time
drawUI();
while (!gameOver) {
Target target = askForTarget();
processTarget(target);
drawUI();
}
}
private Target askForTarget() {
Target t = new Target();
Scanner input = new Scanner(System.in);
System.out.print("Please enter your target:");
t = input.nextInt();
return t;
}
/*
* This is just an example. You have to draw the ships by yourself.
* If you don't like the way the UI is drawn, make your own stuff!
*/
private void drawUI() {
// draw the ui, see blatt01/oberfläche.txt for an example
System.out.println("Schiffeversenken");
System.out.println("================");
System.out.println();
// columns
System.out.print(" ");
for (int col = 0; col < this.cols; col++) {
System.out.print(col + " ");
}
System.out.println();
System.out.print(" _");
for (int col = 0; col < this.cols; col++) {
System.out.print("__");
}
System.out.println();
for (int row = 0; row < this.rows; row++) {
System.out.print(Character.toChars(3 + row));
System.out.print(" |");
System.out.println();
}
}
private void placeShips() {
// do useful stuff to place the ships here
// see Blatt01 for rules
}
private void processTarget(Target target) {
}
/**
* This class only holds the position
* of a target.
*/
private class Target {
public int row;
public int col;
}
}
Everytime I try to compile this error comes up:
error: incompatible types: int cannot be converted to BattleshipLogic.Target
I know that the types are different, but what kind of a type is Target? How can I get the user input to be assigned to t?
Thanks so much in advance!
I think you want to do this.
private Target askForTarget() {
Target t = new Target();
Scanner input = new Scanner(System.in);
System.out.print("Please enter your target:");
t.row = input.nextInt();
t.col = input.nextInt();
return t;
}
to assign the int value to
t of type Target
you need a
getter and setter method
on your t
e.g.
public class Target
{
private int myValue;
public void setMyValue(int myValue)
{
this.myValue=myValue;
}
public int getMyValue()
{
return myValue;
}
}
then in your askForTarget() method
t.setMyValue(input.nextInt());
return t;
if you ever want to use the int in t in other calling method you can use the t method
t.getMyValue();

Simple prisoner's dilemma genetic algorithm

I have used an existing genetic algorithm from
here
and reworked it I but don't know what I'm doing wrong
This is the error that I get
Exception in thread "main" java.lang.NullPointerException at
simpleGa.Algorithm.crossover(Algorithm.java:69) at
simpleGa.Algorithm.evolvePopulation(Algorithm.java:34) at
simpleGa.GAprisonerdilemma.main(GAprisonerdilemma.java:41)
I can't figure out exactly where the mistake is. Read a lot about NullPointerException but couldn't figure it out
package simpleGa;
public class Population {
public static Individual[] individuals;
/*
* Constructors
*/
// Create a population
public Population(int populationSize, boolean initialise) {
individuals = new Individual[populationSize];
// Initialise population
if (initialise) {
// Loop and create individuals
for (int i = 0; i < size(); i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
for(int i=0;i<size();i++)
{
if(i%2==1){Individual individual1=individuals[i-1];
Individual individual2=individuals[i];
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+1;
individuals[i].fitness=individual2.fitness+1;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+2;
individuals[i].fitness=individual2.fitness+2;
}
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+3;
individuals[i].fitness=individual2.fitness+0;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+0;
individuals[i].fitness=individual2.fitness+3;
}
}}}
}
/* Getters */
public Individual getIndividual(int index) {
return individuals[index];
}
public Individual getFittest() {
Individual fittest = individuals[0];
// Loop through individuals to find fittest
for (int i = 1; i < size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
/* Public methods */
// Get population size
public int size() {
return individuals.length;
}
// Save individual
public void saveIndividual(int index, Individual indiv) {
individuals[index] = indiv;
}
}
package simpleGa;
public class Individual {
static int defaultGeneLength = 1000;
private long[] genes =new long [defaultGeneLength];
// Cache
public static int fitness = 0;
// Create a random individual
public void generateIndividual() {
for (int i = 0; i < size(); i++) {
long gene = Math.round(Math.random());
genes[i] = gene;
}
}
/* Getters and setters */
// Use this if you want to create individuals with different gene lengths
public static void setDefaultGeneLength(int length) {
defaultGeneLength = length;
}
public long getGene(int i) {
return genes[i];
}
public void setGene(int index, long value) {
genes[index] = value;
fitness = 0;
}
/* Public methods */
public int size() {
return genes.length;
}
public static int getFitness() {
return fitness;
}
public void setFitness(int i) {
fitness=i;
}
#Override
public String toString() {
String geneString = "";
for (int i = 0; i < size(); i++) {
geneString += getGene(i);
}
return geneString;
}
}
package simpleGa;
public class Algorithm {
/* GA parameters */
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.015;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
/* Public methods */
// Evolve a population
public static Population evolvePopulation(Population pop) {
Population newPopulation = new Population(pop.size(), false);
// Keep our best individual
if (elitism) {
newPopulation.saveIndividual(0, pop.getFittest());
}
// Crossover population
int elitismOffset;
if (elitism) {
elitismOffset = 1;
} else {
elitismOffset = 0;
}
// Loop over the population size and create new individuals with
// crossover
for (int i = elitismOffset; i < pop.size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.saveIndividual(i, newIndiv);
}
// Mutate population
for (int i = elitismOffset; i < newPopulation.size(); i++) {
mutate(newPopulation.getIndividual(i));
}
for(int i=0;i<pop.size();i++)
{for(int j=0;j<pop.getIndividual(i).size();j++)
{if(i%2==1){Individual individual1=Population.individuals[i-1];
Individual individual2=Population.individuals[i];
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+1;
Population.individuals[i].fitness=individual2.fitness+1;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+2;
Population.individuals[i].fitness=individual2.fitness+2;
}
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+3;
Population.individuals[i].fitness=individual2.fitness+0;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+0;
Population.individuals[i].fitness=individual2.fitness+3;
} }}}``
return newPopulation;
}
// Crossover individuals
private static Individual crossover(Individual indiv1, Individual indiv2) {
Individual newSol = new Individual();
// Loop through genes
for (int i = 0; i < indiv1.size(); i++) {
// Crossover
if (Math.random() <= uniformRate) {
newSol.setGene(i, indiv1.getGene(i));
} else {
newSol.setGene(i, indiv2.getGene(i));
}
}
return newSol;
}
// Mutate an individual
private static void mutate(Individual indiv) {
// Loop through genes
for (int i = 0; i < indiv.size(); i++) {
if (Math.random() <= mutationRate) {
// Create random gene
long gene = Math.round(Math.random());
indiv.setGene(i, gene);
}
}
}
// Select individuals for crossover
private static Individual tournamentSelection(Population pop) {
// Create a tournament population
Population tournament = new Population(tournamentSize, false);
// For each place in the tournament get a random individual
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.size());
tournament.saveIndividual(i, pop.getIndividual(randomId));
}
// Get the fittest
Individual fittest = tournament.getFittest();
return fittest;
}
package simpleGa;
public class FitnessCalc {
/* Public methods */
// Set a candidate solution as a byte array
// To make it easier we can use this method to set our candidate solution
// with string of 0s and 1s
// Calculate inidividuals fittness by comparing it to our candidate solution
static int getFitness(Individual individual) {
int fitness = 0;
// Loop through our individuals genes and compare them to our cadidates
fitness=Individual.fitness;
return fitness;
}
}
// Get optimum fitness
}
package simpleGa;
import java.util.Scanner;
public class GAprisonerdilemma {
public static void main(String[] args) {
// Set a candidate solution
Scanner keyboard = new Scanner(System.in);
System.out.println("Input number of games!");
int k = keyboard.nextInt();
Individual.setDefaultGeneLength(k);
// Create an initial population
System.out.println("Input number of individuals in the population!");
int p = keyboard.nextInt();
Population myPop = new Population(p, true);
System.out.println("Input acceptable number of generations!");
int l = keyboard.nextInt();
// Evolve our population until we reach an optimum solution
int generationCount = 0;
int j=l+1;
System.out.println("Input requiered fitness value !");
int f = keyboard.nextInt();
int h=0;
// Evolve our population until we reach an optimum solution
for(int i=0;i<j;i++)
{
if(i==0){}
else{
if(myPop.getFittest().getFitness()>=f){if(h==0){h++;}
else{ System.out.println("Solution found!");
System.out.println("Generation: " + generationCount);
System.out.println( "Fitness(Points): " + myPop.getFittest().getFitness());
break;}
}else {myPop = Algorithm.evolvePopulation(myPop);
generationCount++;
System.out.println("Generation: " + generationCount + " Fittest: " + myPop.getFittest().getFitness());
}
if(i==j-1){ if(myPop.getFittest().getFitness()>=f)System.out.println("Solution found !");
else System.out.println("Solution not found closest solution is!");
System.out.println("Generation: " + generationCount);
System.out.println( " Fitness(Points): " + myPop.getFittest().getFitness());}
}
}
System.out.println("0 for betrays in that turn 1 for cooperates!");
System.out.println("Turns:");
System.out.println(myPop.getFittest());
}
}

How to load/create a level/room from a text file in java?

Basically each room has a size of 10 by 10, the "W" represents the Walls, and the blank spaces -" " represent the Floor, and the numbers are Doors.I figured the best way to create the room is to create a method that receives a file and reads it and put its "information" into a String[10][10], and then create another method(or just do it in my Main) that receives the String[10][10] created and creates the room(adds the images to the room), but i am having some difficulties reading the file so if you guys could help me with that part i would be thankful.
Here is the type of text files from which i want to create my room:
WWWW0WWWWW
W W
W W
W W
W W
W WW
W WW
W WW
W W1
WWWWWWWWWW
Here are the Door, Wall and Floor classes:
public class Door implements ImageTile {
private Position position;
public Door(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Door";
}
#Override
public Position getPosition() {
return position;
}
}
public class Floor implements ImageTile {
private Position position;
public Floor(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Floor";
}
#Override
public Position getPosition() {
return position;
}
}
public class Wall implements ImageTile {
private Position position;
public Wall(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Wall";
}
#Override
public Position getPosition() {
return position;
}
}
And this is my method for adding images to my frame:
public void newImages(final List<ImageTile> newImages) {
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);
frame.repaint();
}
If you guys could help me i would appreciate it very much, thanks guys.Her is what i have now:
public class Room {
private String[][]room;
public Room(){
room = new String[10][10]; }
public static Room fromFile(File file){
if(file.exists()){
Scanner sc = null;
Room room = new Room();
try {
sc = new Scanner(file);
while(sc.hasNextLine()){
if(sc.nextLine().startsWith("#"))
sc.nextLine();
else{
String[] s0 = sc.nextLine().split("");
//Here is where my trouble is, i dont know how to add the content of this String s0 to the String s
if(s0.length==10){
for(int x = 0; x < 10; x++){
for(int y = 0; y < 10; y++){
String[x][y] s= String[x] s0;
}
}
} catch (FileNotFoundException e) {
System.out.println("Ficheiro "+file.getAbsolutePath()+
" não existe. "); }
finally{
if(sc!=null)sc.close();
}
}
else
System.out.println("Ficheiro "+file.getAbsolutePath()+
" não existe. ");
return null;
}
Each call to sc.nextLine() is reading another line from your file. You need to save the line into a temporary variable, and then refer to that temporary.
Maintain a counter of lines you've processed, so you can fill in the appropriate line in your s[][] matrix.
You only need to allocate storage for the 10 rows, since splitting the line you read in will result in an array of strings (the columns in one row) being allocated for you.
int row = 0;
String[][] s = new String[10][];
while(sc.hasNextLine() && i < 10) {
String line = sc.nextLine();
if( !line.startsWith("#")) {
String[] s0 = sc.line.split("");
s[row] = s0;
row++;
}
}
BTW, Use String[][] is overkill; since each string will only hold one character. Perhaps you could consider using char[][]. And line.toCharArray() would split the line into a char[] for you.
EDIT: (Due to edit of your question's code)
Instead of:
if(s0.length==10){
for(int x = 0; x < 10; x++){
for(int y = 0; y < 10; y++){
String[x][y] s= String[x] s0;
}
}
}
you want:
if(s0.length==10){
for(int y = 0; y < 10; y++){
s[row][y] = s0[y];
}
row++;
}
With row being the row counter in my above code.

ArrayList replacing everything before when new element is added?

I'm attempting to add elements into an arraylist (also append an arraylist to the other), however it seems to rewrite everything else already present in that arraylist too - so I'm left with an arraylist filled with the last element added.
Here's the method concerned:
private static ArrayList<Move> checkX(int r, int c) {
ArrayList<Move> moves = new ArrayList<Move>();
if (jumps()) { // if jumps are found && this piece can jump
for (int i = 0; i <= 1; i+=2) {
if (Character.isLowerCase(board[r-1][c+i]) && board[r-2][c+2*i] == ' ') {
}
}
} else { // if no jumps are found then move normally
for (int i = -1; i <= 1; i+=2) {
try {
if (board[r-1][c+i] == ' ') {
Move tempMove = new Move(r, c);
tempMove.addDestination((r-1), (c+i));
moves.add(tempMove);
}
} catch (Exception e) {}
}
}
for (int i = 0; i < moves.size(); i++) {
System.out.println(moves.get(i).toString());
}
return moves;
}
Move class:
public class Move {
private static ArrayList<int[]> destinations;
// private static char[][] tmpboard;
public Move(int r, int c) {
destinations = new ArrayList<int[]>();
int[] initSquare = {r, c};
destinations.add(initSquare);
}
public void addDestination(int r, int c) {
int[] destinationSquare = {r, c};
destinations.add(destinationSquare);
}
public ArrayList<int[]> getMove() {
return destinations;
}
public String toString() {
String returnStr = "";
for (int i = 0; i < destinations.size(); i++) {
returnStr += Arrays.toString(destinations.get(i));
}
return returnStr;
}
}
Every time I attempt to print out everything stored in an instance of 'moves' it seems to only print out the last element added to the list n times.
private static ArrayList<int[]> destinations;
Here's your issue. Try removing the static modifier.
What static here means that the latest additions of destinations will affect all Move instances, which makes them identical.
It's possible you were thinking of final there instead, which would make more sense.

Categories

Resources