Compare commits

..

9 Commits

Author SHA1 Message Date
a135ec80ec Improved error checks for Map 2018-02-28 23:57:45 +01:00
a16a07846b Added wall width to map. 2017-11-30 18:50:26 +01:00
22a1b5a0d7 Merge branch 'WorldNavigation' of https://github.com/EpicKnarvik97/pokemon-cmd into WorldNavigation 2017-11-30 18:41:40 +01:00
9a3a01c082 Added more stuff in test.
We are still missing the actual function to place a structure on the map, but we are quite close.
2017-11-30 18:40:13 +01:00
9d949f3926
Delete Run.bat 2017-11-29 16:15:47 +01:00
99dd30975b
Delete Compile.bat 2017-11-29 16:15:40 +01:00
18664c9b17 Updated .gitignore 2017-11-29 16:07:49 +01:00
fc74f55c85 Added more object types.
Added Map and Structure. Created a working map int Test.java, but Structures are still not implemented.
2017-11-29 15:50:43 +01:00
ad09ee4b1d Added a proposal of the new Tile object.
This is just a proposal of the new Tile object, an may be changed at any time.
Allowing it to return an integer on onWalk lets us easier do tasks like looking for wild pokemon, from anywhere in the program.
It cannot be used as it is now, but it can be used once we are finished with the other necessary classes.
2017-11-29 10:50:15 +01:00
34 changed files with 1173 additions and 1393 deletions

6
.gitignore vendored
View File

@ -28,6 +28,6 @@ hs_err_pid*
*.bat
*.sh
# IDE files
*.iml
.idea
#IDEA files
*.xml
*.iml

24
Jenkinsfile vendored
View File

@ -1,24 +0,0 @@
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building...'
sh 'mvn clean & mvn validate & mvn compile'
}
}
stage('Test') {
steps {
echo 'Testing...'
sh 'mvn clean & mvn test'
}
}
stage('Deploy') {
steps {
echo 'Deploying...'
sh 'mvn clean & mvn compile & mvn package & mvn verify & mvn install'
archiveArtifacts artifacts: '**/target/*.jar', fingerprint: true
}
}
}
}

View File

@ -2,4 +2,4 @@
A commandline pokemon clone written in java.
This started as an assignment in computer science, but since it became quite advanced in just one week, I want to see where it might go.
This project has no clear goal, except mimicking the original pokemon games in a commandline interface. It would be interesting if people used this project as a base for custom games. There is still a lot to implement, but if it reaches a near complete stage, it should be possible to create custom types, moves pokemon, trainers, gyms, badges and maps.
This project has no clear goal, except mimicking the original pokemon games in a commandline interface. It would be interestig if people used this project as a base for custom games. There is still a lot to implement, but if it reaches a near complete stage, it should be possible to create custom types, moves pokemon, trainers, gyms, badges and maps.

21
Test/MapTest.java Normal file
View File

@ -0,0 +1,21 @@
class MapTest {
public static void main(String[] args) {
Tile rock = new Tile('■', true, "NONE");
Tile empty = new Tile(' ', false, "NONE");
Map map = new Map(10, 10, 5, 5, empty, rock);
Tile wallTopRight = new Tile('╗', true, "NONE");
Tile wallTopLeft = new Tile('╔', true, "NONE");
Tile wallBottomRight = new Tile('╝', true, "NONE");
Tile wallBottomLeft = new Tile('╚', true, "NONE");
Tile wallSide = new Tile('║', true, "NONE");
Tile wallLying = new Tile('═', true, "NONE");
Tile roof = new Tile(' ', true, "NONE");
Tile door = new Tile('╼', false, "TELEPORT", 10, 10);
Tile player = new Tile('P', false, "NONE");
Tile[][] tiles = {{wallTopLeft, wallSide, wallBottomLeft}, {wallLying, roof, door}, {wallTopRight, wallSide, wallBottomRight}};
new Structure("House", tiles);
map.generateStructure("House", 4, 2);
map.placeTile(player, 8, 8);
System.out.println(map);
}
}

View File

@ -4,4 +4,4 @@
### Steps to reproduce the behavior
### Information about java version, environment, project branch etc.
### Information about java version, enviroment, project branch etc.

3
java/Direction.java Normal file
View File

@ -0,0 +1,3 @@
public enum Direction {
NORTH, SOUTH, EAST, WEST;
}

373
java/Game.java Normal file
View File

@ -0,0 +1,373 @@
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.NumberFormatException;
import java.text.NumberFormat;
import java.util.Locale;
import java.text.ParseException;
/** Simulates the game Pokémon. */
public class Game {
private static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
ArrayList<Pokemon> pokemon = readPokemon();
int initialPokemon = pokemon.size();
System.out.println("What is your name?");
String name = in.nextLine();
Trainer player = new Trainer(name, randomTeam(), createInventory());
boolean done = false;
Pokemon opponentPokemon;
Pokemon trainersPokemon = null;
Pokeball currentPokeball;
Potion currentPotion;
boolean fleeSuccess;
Pokemon pokemonToHeal;
opponentPokemon = randomPokemon(pokemon);
System.out.printf("A wild %s appeared.%n", opponentPokemon.getName());
while (!done) {
if (opponentPokemon == null) {
System.out.printf("You have brutally murdered %d pokemon.%n"
+ "The only ones left are the ones in your posession.%n"
+ "There really is nothing more to do here.%n", initialPokemon);
return;
}
if (player.getConsciousPokemon().size() < 1) {
System.out.println("All your pokemon have fainted. Your journey ends here.");
return;
}
while (trainersPokemon == null || !trainersPokemon.isConscious()) {
player.availablePokemon(true);
trainersPokemon = player.choosePokemon(true);
}
System.out.printf("Opponent: %s%nWhat will you do?%n", opponentPokemon);
System.out.printf("b: battle"
+ "%nh: heal or revive"
+ "%nt: throw pokeball"
+ "%nc: change pokemon"
+ "%nf: flee"
+ "%nv: view my pokemon"
+ "%ns: save"
+ "%nl: load"
+ "%nq: quit%n>");
char command = in.next().toLowerCase().charAt(0);
switch (command) {
case 'b':
if (opponentPokemon.isConscious() && trainersPokemon.isConscious()) {
trainersPokemon.attack(opponentPokemon);
if (opponentPokemon.isConscious()) {
opponentPokemon.attack(trainersPokemon);
if (!trainersPokemon.isConscious()) {
System.out.println("Your pokemon fainted.");
}
} else {
pokemonFainted(pokemon, opponentPokemon);
System.out.println("The opponent pokemon fainted.");
opponentPokemon = randomPokemon(pokemon);
}
}
break;
case 'h':
if (player.getInventory().getPotions().size() > 0) {
player.getInventory().availablePotions();
currentPotion = player.getInventory().chosenPotion();
if (currentPotion == null) {
in.nextLine();
System.out.println("Invalid potion.");
} else {
if (currentPotion.needsAlive()) {
player.availablePokemon(true);
pokemonToHeal = player.choosePokemon(true);
} else {
player.availablePokemon(false);
pokemonToHeal = player.choosePokemon(false);
}
if (pokemonToHeal == null) {
System.out.println("That is not a valid pokemon");
} else {
if (currentPotion.use(pokemonToHeal)) {
opponentPokemon.attack(trainersPokemon);
}
}
}
} else {
System.out.println("You have used all your healing items.");
}
break;
case 't':
if (player.getInventory().getPokeballs().size() > 0) {
player.getInventory().availablePokeballs();
currentPokeball = player.getInventory().chosenPokeball();
if (currentPokeball == null) {
in.nextLine();
System.out.println("Invalid pokeball.");
} else {
if (currentPokeball.getType() == Pokeball.Pokeballs.MASTERBALL) {
currentPokeball.use(opponentPokemon, pokemon, player);
opponentPokemon = randomPokemon(pokemon);
System.out.printf("A wild %s appeared.%n", opponentPokemon.getName());
} else {
boolean captured = currentPokeball.use(opponentPokemon, pokemon, player);
if (captured) {
opponentPokemon = randomPokemon(pokemon);
System.out.printf("A wild %s appeared.%n", opponentPokemon.getName());
} else {
opponentPokemon.attack(trainersPokemon);
}
}
}
} else {
System.out.println("You have used all your pokeballs.");
}
break;
case 'c':
player.availablePokemon(true);
trainersPokemon = player.choosePokemon(true);
while (trainersPokemon == null) {
player.availablePokemon(true);
trainersPokemon = player.choosePokemon(true);
}
opponentPokemon.attack(trainersPokemon);
break;
case 's':
savePokemon(pokemon, "pokemon.save");
savePokemon(player.getPokemon(), "user.save");
saveInventory(player.getInventory(), "inventory.save");
break;
case 'l':
ArrayList<Pokemon> loadedPokemon = loadPokemon("pokemon.save");
ArrayList<Pokemon> loadedUsersPokemon = loadPokemon("user.save");
Inventory loadedInventory = loadInventory("inventory.save");
if (loadedPokemon == null || loadedUsersPokemon == null || loadedInventory == null) {
System.out.println("One or more savefiles seem corrupt or missing. Please delete, create or fix the affected file(s).");
} else {
pokemon = loadedPokemon;
player.setPokemon(loadedUsersPokemon);
player.setInventory(loadedInventory);
if (pokemon.size() > 0 && player.getPokemon().size() > 0) {
do {
player.availablePokemon(true);
trainersPokemon = player.choosePokemon(true);
} while (trainersPokemon == null || !trainersPokemon.isConscious());
opponentPokemon = randomPokemon(pokemon);
}
}
break;
case 'f':
fleeSuccess = trainersPokemon.flee(opponentPokemon);
if (fleeSuccess) {
System.out.println("You fled the battle.");
opponentPokemon = randomPokemon(pokemon);
System.out.printf("A wild %s appeared.%n", opponentPokemon.getName());
} else {
System.out.printf("Failed to flee from %s.%n", opponentPokemon.getName());
opponentPokemon.attack(trainersPokemon);
}
break;
case 'v':
player.printPokemon();
break;
case 'q':
done = true;
break;
default:
System.out.println("[Invalid command]");
}
}
}
/**
* Prevents wild fainted pokemon from ever being encountered again.
* @param pokemonList List of pokemon to search.
* @param target The pokemon to remove.
*/
private static void pokemonFainted(ArrayList<Pokemon> pokemonList, Pokemon target) {
for (int i = 0; i < pokemonList.size(); i++) {
if (pokemonList.get(i).equals(target)) {
pokemonList.remove(i);
}
}
}
/**
* Gives a trainer necessary starting items.
* @return A list of items.
*/
private static Inventory createInventory() {
Inventory inventory = new Inventory();
inventory.addPokeball("Poke Ball", "A device for catching wild Pokémon. It's thrown like a ball at a Pokémon, comfortably encapsulating its target.", 15);
inventory.addPokeball("Great ball", "A good, high-performance Poké Ball that provides a higher Pokémon catch rate than a standard Poké Ball.", 10);
inventory.addPokeball("Ultra ball", "An ultra-high-performance Poké Ball that provides a higher success rate for catching Pokémon than a Great Ball.", 5);
inventory.addPokeball("Master ball", "The best Poké Ball with the ultimate level of performance. With it, you will catch any wild Pokémon without fail.", 1);
inventory.addPotion("Potion", "Heals a pokemon for 20 HP.", 20, true);
inventory.addPotion("Super Potion", "Heals a pokemon for 50 HP.", 10, true);
inventory.addPotion("Hyper Potion", "Heals a pokemon for 200 HP.", 5, true);
inventory.addPotion("Max Potion", "Fully heals a pokemon.", 1, true);
inventory.addPotion("Revive", "Revives a fainted pokemon.", 2, false);
return inventory;
}
/**
* Chooses a random pokemon from a list.
* @param pokemon The list to choose from.
* @return A Pokemon object, or null if the list is empty.
*/
private static Pokemon randomPokemon(ArrayList<Pokemon> pokemon) {
if (pokemon.size() > 0) {
return pokemon.get((int)(Math.random() * pokemon.size()));
} else {
return null;
}
}
/**
* Reads pokemon from Pokemon.txt to an ArrayList.
* @return An ArrayList of pokemon objects.
*/
private static ArrayList<Pokemon> readPokemon() {
ArrayList<Pokemon> pokemon = new ArrayList<>();
try (Scanner file = new Scanner(new File("config/Pokemon.txt"))) {
while (file.hasNextLine()) {
pokemon.add(new Pokemon(file.nextLine()));
}
} catch (FileNotFoundException e) {
/* If the file is compiled as jar, this will prevent an empty list. */
try (Scanner file = new Scanner(Game.class.getResourceAsStream("/config/Pokemon.txt"))) {
while (file.hasNextLine()) {
pokemon.add(new Pokemon(file.nextLine()));
}
}
}
return pokemon;
}
/**
* Picks a random pokemon from a list.
* @param pokemon A list of pokemon objects.
* @return A pokemon object.
*/
private static Pokemon pick(ArrayList<Pokemon> pokemon) {
int index = (int)(Math.random() * (pokemon.size()));
Pokemon randomPokemon = pokemon.get(index);
pokemon.remove(index);
return randomPokemon;
}
/**
* Saves all pokemon in a list with stats to a text file.
* @param pokemonList List of Pokemon objects to save.
* @param savefile The file to write to.
*/
private static void savePokemon(ArrayList<Pokemon> pokemonList, String savefile) {
try (PrintWriter file = new PrintWriter(savefile)) {
for (Pokemon pokemon : pokemonList) {
file.println(pokemon.saveString());
}
System.out.println("Successfully saved pokemon.");
} catch (FileNotFoundException e) {
System.out.println("The savefile could not be written.");
}
}
/**
* Saves all items in a list to a text file.
* @param inventory The items of a player
* @param savefile The file to write to.
*/
private static void saveInventory(Inventory inventory, String savefile) {
try (PrintWriter file = new PrintWriter(savefile)) {
for (Pokeball pokeball : inventory.getPokeballs()) {
file.println(pokeball.saveString());
}
file.println(":NEXTLIST:");
for (Potion potion : inventory.getPotions()) {
file.println(potion.saveString());
}
System.out.println("Successfully saved inventory.");
} catch (FileNotFoundException e) {
System.out.println("The savefile could not be written.");
}
}
/**
* Loads pokemon from a text file.
* @param savefile The file to write to.
* @return A list of pokemon or null on failiure.
*/
private static ArrayList<Pokemon> loadPokemon(String savefile) {
ArrayList<Pokemon> pokemon = new ArrayList<>();
try (Scanner file = new Scanner(new File(savefile))) {
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
while (file.hasNextLine()) {
String[] data = file.nextLine().split(";");
try {
pokemon.add(new Pokemon(data[0], Integer.parseInt(data[1]), Integer.parseInt(data[2]), Integer.parseInt(data[3]), format.parse(data[4]).doubleValue(), Integer.parseInt(data[5]), Integer.parseInt(data[6]), Integer.parseInt(data[7])));
} catch (NumberFormatException | ParseException e) {
System.out.println("Malformed number " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid savefile: " + savefile);
return null;
}
}
System.out.println("Successfully loaded pokemon.");
} catch (FileNotFoundException e) {
System.out.println("Missing savefile " + savefile);
return null;
}
return pokemon;
}
/**
* Loads items from a text file.
* @param savefile The file to write to.
* @return A list of items or null on failiure.
*/
private static Inventory loadInventory(String savefile) {
ArrayList<Pokeball> pokeballs = new ArrayList<>();
ArrayList<Potion> potions = new ArrayList<>();
try (Scanner file = new Scanner(new File(savefile))) {
String next = "";
while (file.hasNextLine() && !next.equals(":NEXTLIST:")) {
try {
next = file.nextLine();
if (!next.equals(":NEXTLIST:")) {
String[] data = next.split(";");
pokeballs.add(new Pokeball(data[0], data[1], Integer.parseInt(data[2]), Pokeball.Pokeballs.valueOf(data[0].toUpperCase().replace(" ", ""))));
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid savefile: " + savefile);
return null;
}
}
while (file.hasNextLine()) {
try {
String[] data = file.nextLine().split(";");
potions.add(new Potion(data[0], data[1], Integer.parseInt(data[2]), Potion.Potions.valueOf(data[0].toUpperCase().replace(" ", ""))));
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid savefile: " + savefile);
return null;
}
}
System.out.println("Successfully loaded items.");
} catch (FileNotFoundException e) {
System.out.println("Missing savefile " + savefile);
return null;
}
return new Inventory(pokeballs, potions);
}
private static ArrayList<Pokemon> randomTeam() {
ArrayList<Pokemon> temporary = readPokemon();
ArrayList<Pokemon> pokemon = new ArrayList<>();
for (int i = 1; i <= 6; i++) {
pokemon.add(pick(temporary));
}
return pokemon;
}
}

93
java/Inventory.java Normal file
View File

@ -0,0 +1,93 @@
import java.util.ArrayList;
import java.util.Scanner;
public class Inventory {
private static final Scanner in = new Scanner(System.in);
private final ArrayList<Pokeball> pokeballs;
private final ArrayList<Potion> potions;
public Inventory() {
this.pokeballs = new ArrayList<>();
this.potions = new ArrayList<>();
}
public Inventory(ArrayList<Pokeball> pokeballs, ArrayList<Potion> potions) {
this.pokeballs = pokeballs;
this.potions = potions;
}
public void addPokeball(String name, String description, int amount) {
Pokeball pokeball = new Pokeball(name, description, amount, Pokeball.Pokeballs.valueOf(name.toUpperCase().replace(" ", "")));
this.pokeballs.add(pokeball);
}
public void addPotion(String name, String description, int amount, boolean alive) {
Potion potion = new Potion(name, description, amount, Potion.Potions.valueOf(name.toUpperCase().replace(" ", "")), alive);
this.potions.add(potion);
}
public ArrayList<Pokeball> getPokeballs() {
ArrayList<Pokeball> pokeballs = new ArrayList<>();
for (Pokeball pokeball : this.pokeballs) {
if (pokeball.getAmount() > 0) {
pokeballs.add(pokeball);
}
}
return pokeballs;
}
public ArrayList<Potion> getPotions() {
ArrayList<Potion> potions = new ArrayList<>();
for (Potion potion : this.potions) {
if (potion.getAmount() > 0) {
potions.add(potion);
}
}
return potions;
}
public void availablePokeballs() {
System.out.println("You may choose from these items:");
for (int i = 0; i < this.pokeballs.size(); i++) {
System.out.printf("%d: %s%n", i + 1, this.pokeballs.get(i));
}
System.out.print(">");
}
public void availablePotions() {
System.out.println("You may choose from these items:");
ArrayList<Potion> potionList = this.getPotions();
for (int i = 0; i < potionList.size(); i++) {
System.out.printf("%d: %s%n", i + 1, potionList.get(i));
}
System.out.print(">");
}
public Potion chosenPotion() {
ArrayList<Potion> potions = this.getPotions();
if (in.hasNextInt()) {
int choice = in.nextInt() - 1;
if (choice >= 0 && choice < potions.size()) {
in.nextLine();
return potions.get(choice);
}
} else {
in.nextLine();
}
return null;
}
public Pokeball chosenPokeball() {
ArrayList<Pokeball> pokeballs = this.getPokeballs();
if (in.hasNextInt()) {
int choice = in.nextInt() - 1;
if (choice >= 0 && choice < pokeballs.size()) {
in.nextLine();
return pokeballs.get(choice);
}
} else {
in.nextLine();
}
return null;
}
}

89
java/Map.java Normal file
View File

@ -0,0 +1,89 @@
class Map {
private final Tile[][] tiles;
private int fullWidth;
private int fullHeight;
public Map(int width, int height, int wWidth, int wHeight, Tile empty, Tile wall) {
this.fullHeight = height + (2 * wHeight);
this.fullWidth = width + (2 * wWidth);
Tile[][] map = new Tile[this.fullWidth][this.fullHeight];
for (int i = 0; i < this.fullWidth; i++) {
for (int j = 0; j < this.fullHeight; j++) {
if (i < wWidth || i >= width + wWidth || j < wHeight || j >= height + wHeight) {
map[i][j] = wall;
} else {
map[i][j] = empty;
}
}
}
this.tiles = map;
}
private Tile[][] getTiles() {
return this.tiles;
}
public void generateStructure(String name, int x, int y) throws IllegalArgumentException {
for (Structure structure : Structure.getStructures()) {
if (name.equals(structure.getName())) {
this.placeStructure(structure, x, y);
return;
}
}
throw new IllegalArgumentException("Invalid structure name.");
}
private void placeStructure(Structure structure, int x, int y) throws IllegalArgumentException {
if (x < 0 || y < 0 || this.fullWidth < x + structure.getWidth() || this.fullHeight < y + structure.getHeight()) {
throw new IllegalArgumentException("The structure is misplaced or does not fit.");
}
Tile[][] tiles = structure.getTiles();
for (int i = 0; i < structure.getWidth(); i++) {
for (int j = 0; j < structure.getHeight(); j++) {
if (!tiles[i][j].isSolid()) {
switch (structure.getDoorDirection()) {
case NORTH:
if (this.tiles[x+i][y+j-1].isSolid()) {
throw new IllegalArgumentException("A structure is blocked");
}
break;
case SOUTH:
if (this.tiles[x+i][y+j+1].isSolid()) {
throw new IllegalArgumentException("A structure is blocked");
}
break;
case WEST:
if (this.tiles[x+i-1][y+j].isSolid()) {
throw new IllegalArgumentException("A structure is blocked");
}
break;
case EAST:
if (this.tiles[x+i+1][y+j].isSolid()) {
throw new IllegalArgumentException("A structure is blocked");
}
}
}
this.tiles[x+i][y+j] = tiles[i][j];
}
}
}
public void placeTile(Tile tile, int x, int y) {
if (x < 0 || y < 0 || x >= this.tiles.length || y >= this.tiles[0].length) {
throw new IllegalArgumentException("Invalid tile position");
}
this.tiles[x][y] = tile;
}
public String toString() {
Tile[][] tiles = this.getTiles();
StringBuilder str = new StringBuilder();
for (int i = 0; i < tiles.length; i++) {
for (int j = 0; j < tiles.length; j++) {
str.append(tiles[j][i].toChar());
}
str.append("\n");
}
return str.toString();
}
}

62
java/Pokeball.java Normal file
View File

@ -0,0 +1,62 @@
import java.util.ArrayList;
public class Pokeball {
public enum Pokeballs { POKEBALL, GREATBALL, ULTRABALL, MASTERBALL }
private final String name;
private final String description;
private final Pokeballs type;
private int amount;
public Pokeball(String name, String description, int amount, Pokeballs type) {
this.type = type;
this.name = name;
this.description = description;
this.amount = amount;
}
public String toString() {
return String.format("(%d) %s: %s", this.amount, this.name, this.description);
}
public String saveString() {
return String.format("%s;%s;%d", this.name, this.description, this.amount);
}
public int getAmount() {
return this.amount;
}
public String getName() {
return this.name;
}
public Pokeballs getType() {
return this.type;
}
/**
* Uses a pokeball on an opponent.
* @param target Which pokemon to target.
* @param current Current list the pokemon belongs to.
* @param catcher Where we send the pokemon on a successfull capture.
* @return True if nothing went wrong. False otherwise.
*/
public boolean use(Pokemon target, ArrayList<Pokemon> current, Trainer catcher) {
if (this.amount > 0) {
this.amount--;
switch (this.type) {
case POKEBALL:
return target.tryCapture(current, catcher, 255);
case GREATBALL:
return target.tryCapture(current, catcher, 200);
case ULTRABALL:
return target.tryCapture(current, catcher, 150);
case MASTERBALL:
return target.tryCapture(current, catcher, 0);
}
} else {
System.out.println("No cheating!");
}
return false;
}
}

203
java/Pokemon.java Normal file
View File

@ -0,0 +1,203 @@
import java.util.Random;
import java.util.ArrayList;
public class Pokemon {
private final String name;
private int healthPoints;
private int maxHealthPoints;
private int strength;
private final double criticalChance;
private final Random random;
private final int catchRate;
private int exp;
private int level;
private int fleeCount;
public Pokemon(String name) {
this.random = new Random();
this.name = name;
this.healthPoints = 30 + random.nextInt(70);
this.maxHealthPoints = this.healthPoints;
this.criticalChance = Math.abs(0.1 * random.nextGaussian());
this.catchRate = (int)(Math.random() * 256);
this.exp = 0;
this.level = (int)(Math.abs(2 * random.nextGaussian()) + 1);
this.strength = random.nextInt(7) + this.level;
this.fleeCount = 0;
}
public Pokemon(String name, int healthPoints, int maxHealthPoints, int strength, double criticalChance, int catchRate, int exp, int level) {
this.random = new Random();
this.name = name;
this.healthPoints = healthPoints;
this.maxHealthPoints = maxHealthPoints;
this.criticalChance = criticalChance;
this.catchRate = catchRate;
this.exp = exp;
this.level = level;
this.strength = strength;
this.fleeCount = 0;
}
public String toString() {
return String.format("Level %d %s HP: (%d/%d) STR: %d CHC: %.0f%%", this.level, this.name, this.healthPoints, this.maxHealthPoints, this.strength, (this.criticalChance*100));
}
/**
* Returns a string containing all the pokemon's data.
*/
public String saveString() {
return String.format("%s;%d;%d;%d;%f;%d;%d;%d", this.name, this.healthPoints, this.maxHealthPoints, this.strength, this.criticalChance, this.catchRate, this.exp, this.level);
}
public String getName() {
return this.name;
}
public int getHP() {
return this.healthPoints;
}
public boolean equals(Pokemon target) {
return target == this;
}
/**
* Heals a pokemon.
* @param amount How many hitpoints to heal.
* @return The exact amount of hitpoints healed.
*/
public int heal(int amount) {
if (amount < 0) {
amount = this.maxHealthPoints - this.healthPoints;
} else {
amount = Math.min(this.maxHealthPoints - this.healthPoints, amount);
}
this.healthPoints += amount;
return amount;
}
/**
* Checks if a pokemon has not taken any damage or is fully healed.
* @return True if health is full. False otherwise.
*/
public boolean isDamaged() {
return this.healthPoints < this.maxHealthPoints;
}
/**
* Tries to catch a pokemon.
* @param current The list where the pokemon currently belongs.
* @param catcher The list to send the pokemon on successfull capture.
* @return True on successfull capture. False otherwise.
*/
public boolean tryCapture(ArrayList<Pokemon> current, Trainer catcher, int range) {
if (range == 0) {
this.capture(current, catcher);
System.out.printf("%s was caught.%n", this.name);
return true;
}
if ((int)(Math.random() * (range + 1)) < Math.max((3 * this.maxHealthPoints - 2 * this.healthPoints) * this.catchRate / (3 * this.maxHealthPoints), 1)) {
this.capture(current, catcher);
System.out.printf("%s was caught.%n", this.name);
return true;
} else {
System.out.printf("%s escaped from the pokeball.%n", this.name);
return false;
}
}
/**
* Captures a wild pokemon.
* @param current The pokemon list the pokemon belongs to.
* @param trainer The trainer who is capturing.
*/
private void capture(ArrayList<Pokemon> current, Trainer trainer) {
trainer.addPokemon(this);
for (int i = 0; i < current.size(); i++) {
if (current.get(i) == this) {
current.remove(i);
}
}
}
/** Restores the health of a fainted pokemon. */
public void revive() {
this.healthPoints = this.maxHealthPoints;
}
/**
* Checks if the pokemon has any HP left.
* @return True if any HP is left. False otherwise.
*/
public boolean isConscious() {
return this.healthPoints > 0;
}
/**
* Damages a pokemon.
* @param damageTaken How many hitpoints are to be deducted.
*/
private void damage(int damageTaken) {
this.healthPoints = Math.max(this.healthPoints -= damageTaken, 0);
System.out.printf("%s takes %d damage and is left with %d/%d HP%n", this.name, damageTaken, this.healthPoints, this.maxHealthPoints);
}
/**
* Gives a pokemon exp after each successfull battle. Also handles leveling up.
* @param target Which pokemon did we beat.
*/
private void giveEXP(Pokemon target) {
int exp = (100 * target.level)/7;
this.exp += exp;
System.out.printf("%s gained %d exp.%n", this.name, exp);
if (this.exp > (4 * Math.pow(this.level, 3)) / 5) {
this.level++;
this.maxHealthPoints += 5;
this.healthPoints = maxHealthPoints;
this.strength += 1;
System.out.printf("%s is now level %d. Health has been increased and restored. Strength has been increased.%n", this.name, this.level);
}
}
/**
* Makes a pokemon attack another pokemon.
* @param target The pokemon to take damage.
*/
public void attack(Pokemon target) {
if (this.healthPoints > 0) {
System.out.printf("%s attacks %s.%n", this.getName(), target.getName());
double critical = 1;
if (Math.random() < this.criticalChance) {
System.out.println("Critical hit!");
critical = (2 * this.level +5) / (this.level + 5);
}
double randomDouble = 0.85 + (1.0 - 0.85) * random.nextDouble();
int moveDamage = (int)(Math.random() * 60 + 40);
int damageInflicted = this.level + (int)((((((2 * this.strength) / 5) + 2) * moveDamage * 1.75) / 50 + 2) * critical * randomDouble);
target.damage(damageInflicted);
if (!target.isConscious()) {
System.out.printf("%s is defeated by %s.%n", target.getName(), this.getName());
this.giveEXP(target);
this.fleeCount = 0;
}
} else {
System.out.println("No cheating!");
}
}
/**
* The trainer may flee if the battle is too hard.
* @param target Who are we trying to flee from
* @return True on successfull escape. False otherwise.
*/
public boolean flee(Pokemon target) {
if (random.nextInt(256) < (this.level * 128 / target.level) + (30 * this.fleeCount % 256)) {
this.fleeCount = 0;
return true;
} else {
this.fleeCount++;
return false;
}
}
}

104
java/Potion.java Normal file
View File

@ -0,0 +1,104 @@
public class Potion {
public enum Potions { POTION, SUPERPOTION, HYPERPOTION, MAXPOTION, REVIVE }
private final String name;
private final String description;
private final Potions type;
private final boolean alive;
private int amount;
public Potion(String name, String description, int amount, Potions type) {
this.type = type;
this.name = name;
this.description = description;
this.alive = true;
this.amount = amount;
}
public Potion(String name, String description, int amount, Potions type, boolean alive) {
this.type = Potions.valueOf(name.toUpperCase().replace(" ", ""));
this.name = name;
this.description = description;
this.alive = alive;
this.amount = amount;
}
public String toString() {
return String.format("(%d) %s: %s", this.amount, this.name, this.description);
}
public String saveString() {
return String.format("%s;%s;%d;%b", this.name, this.description, this.amount, this.alive);
}
public int getAmount() {
return this.amount;
}
public String getName() {
return this.name;
}
/** Checks if an item should be used on alive or fainted pokemon. */
public boolean needsAlive() {
return alive;
}
/**
* Spends an item and does something based on the type of item.
* @param target Which pokemon should the item be used on.
* @return True if nothing went wrong. False otherwise.
*/
public boolean use(Pokemon target) {
if (this.amount > 0) {
switch (this.type) {
case POTION:
return potion(target, 20);
case SUPERPOTION:
return potion(target, 50);
case HYPERPOTION:
return potion(target, 200);
case MAXPOTION:
return potion(target, -1);
case REVIVE:
if (!target.isConscious()) {
this.amount--;
target.revive();
System.out.printf("%s was revived.%n", target.getName());
return true;
} else {
System.out.println("You can't revive a conscious pokemon.");
return false;
}
default:
System.out.printf("Invalid item %s%n", name);
return false;
}
} else {
System.out.println("No cheating!");
return false;
}
}
/**
* Checks if a pokemon is able to, and in need of a potion. If it is, heal it.
* @param target The pokemon to heal.
* @param amount The amount to heal the pokemon.
* @return True if nothing went wrong. False otherwise.
*/
private boolean potion(Pokemon target, int amount) {
if (target.isConscious()) {
if (target.isDamaged()) {
this.amount--;
int healed = target.heal(amount);
System.out.printf("%s was healed for %d HP and now has %d HP.%n", target.getName(), healed, target.getHP());
return true;
} else {
System.out.printf("%s has not taken damage, and does not require a potion.%n", target.getName());
return false;
}
} else {
System.out.println("You can't heal a fainted pokemon.");
return false;
}
}
}

58
java/Structure.java Normal file
View File

@ -0,0 +1,58 @@
import java.util.ArrayList;
class Structure {
private static final ArrayList<Structure> structures = new ArrayList<>();
private final Tile[][] tiles;
private final String name;
public Structure(String name, Tile[][] tiles) {
this.name = name;
this.tiles = tiles;
structures.add(this);
}
public String getName() {
return this.name;
}
public Tile[][] getTiles() {
return this.tiles;
}
public static ArrayList<Structure> getStructures() {
return structures;
}
public int getWidth() {
return this.tiles.length;
}
public Direction getDoorDirection() {
for (int x = 0; x < this.getWidth(); x++) {
for (int y = 0; y < this.getHeight(); y++) {
if (!tiles[x][y].isSolid()) {
if (y == tiles[x].length - 1) {
return Direction.SOUTH;
} else if (y == 0) {
return Direction.NORTH;
} else if (x == 0) {
return Direction.WEST;
} else if (x == tiles.length - 1) {
return Direction.EAST;
}
}
}
}
return null;
}
public int getHeight() {
int max = 0;
for (Tile[] tile : this.tiles) {
if (tile.length > max) {
max = tile.length;
}
}
return max;
}
}

60
java/Tile.java Normal file
View File

@ -0,0 +1,60 @@
public class Tile {
private final char representation;
private final boolean solid;
private enum Action { TELEPORT, NONE, ENCOUNTER, MENUBATTLE, MENUSHOP }
private final Action action;
private int[] teleportTarget;
public Tile (char representation, boolean solid, String action) throws IllegalArgumentException {
this.representation = representation;
this.solid = solid;
this.action = Action.valueOf(action.toUpperCase());
if (this.action != Action.TELEPORT) {
this.teleportTarget = null;
} else {
throw new IllegalArgumentException("A teleport tile must have a valid target.");
}
}
public Tile (char representation, boolean solid, String action, int x, int y) throws IllegalArgumentException {
this.representation = representation;
this.solid = solid;
this.action = Action.valueOf(action.toUpperCase());
if (this.action == Action.TELEPORT) {
this.teleportTarget = new int[]{x, y};
} else {
throw new IllegalArgumentException("A non-teleport tile can't have a teleport target.");
}
}
public char toChar() {
return this.representation;
}
public int[] getTeleportTarget() {
return this.teleportTarget;
}
public boolean isSolid() {
return this.solid;
}
public int onWalk() {
if (this.solid) {
System.out.println("You bumped against an immovable structure.");
return -1;
} else {
switch (this.action) {
case TELEPORT:
return 1;
case ENCOUNTER:
return 2;
case MENUBATTLE:
return 3;
case MENUSHOP:
return 4;
}
}
return 0;
}
}

99
java/Trainer.java Normal file
View File

@ -0,0 +1,99 @@
import java.util.ArrayList;
import java.util.Scanner;
class Trainer {
private static final Scanner in = new Scanner(System.in);
private final String name;
private ArrayList<Pokemon> pokemon;
private Inventory inventory;
Trainer(String name, ArrayList<Pokemon> pokemon, Inventory inventory) {
this.name = name;
this.pokemon = pokemon;
this.inventory = inventory;
}
public void setPokemon(ArrayList<Pokemon> pokemon) {
this.pokemon = pokemon;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public ArrayList<Pokemon> getPokemon() {
return this.pokemon;
}
public void addPokemon(Pokemon pokemon) {
this.pokemon.add(pokemon);
}
public ArrayList<Pokemon> getConsciousPokemon() {
ArrayList<Pokemon> pokemon = new ArrayList<>();
for (Pokemon singlePokemon : this.pokemon) {
if (singlePokemon.isConscious()) {
pokemon.add(singlePokemon);
}
}
return pokemon;
}
private ArrayList<Pokemon> getFaintedPokemon() {
ArrayList<Pokemon> pokemon = new ArrayList<>();
for (Pokemon singlePokemon : this.pokemon) {
if (!singlePokemon.isConscious()) {
pokemon.add(singlePokemon);
}
}
return pokemon;
}
public Inventory getInventory() {
return this.inventory;
}
/** Lists all currently available pokemon for the trainer.*/
public void availablePokemon(boolean alive) {
ArrayList<Pokemon> pokemonList;
if (alive) {
pokemonList = this.getConsciousPokemon();
} else {
pokemonList = this.getFaintedPokemon();
}
System.out.println("You may choose from these pokemon:");
for (int i = 0; i < pokemonList.size(); i++) {
System.out.printf("%d: %s%n", i + 1, pokemonList.get(i));
}
System.out.print(">");
}
public void printPokemon() {
for (Pokemon pokemon : this.pokemon) {
System.out.println(pokemon);
}
}
/**
* Asks the user for the name of a pokemon and returns it.
* @param alive Are we looking for alive pokemon?
* @return A pokemon object or null.
*/
public Pokemon choosePokemon(boolean alive) {
ArrayList<Pokemon> pokemonList;
if (alive) {
pokemonList = this.getConsciousPokemon();
} else {
pokemonList = this.getFaintedPokemon();
}
if (in.hasNextInt()) {
int choice = in.nextInt() - 1;
if (choice >= 0 && choice < pokemonList.size()) {
in.nextLine();
return pokemonList.get(choice);
}
}
in.nextLine();
return null;
}
}

3
manifest.txt Normal file
View File

@ -0,0 +1,3 @@
Main-Class: Game
Name: pokemon-cmd/package/
Sealed: true

59
pom.xml
View File

@ -1,59 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pokemon-cmd</groupId>
<artifactId>pokemon-cmd</artifactId>
<version>0.1-alpha</version>
<packaging>jar</packaging>
<name>Pokemon CMD</name>
<url>https://git.knarcraft.net/EpicKnarvik97/pokemon-cmd</url>
<inceptionYear>2017</inceptionYear>
<licenses>
<license>
<name>GNU GENERAL PUBLIC LICENSE</name>
<url>https://fsf.org/</url>
</license>
</licenses>
<developers>
<developer>
<id>EpicKnarvik97</id>
<name>Kristian Knarvik</name>
<url>https://kristianknarvik.knarcraft.net</url>
<roles>
<role>leader</role>
<role>developer</role>
</roles>
<timezone>Europe/Oslo</timezone>
</developer>
</developers>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>Game</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,419 +0,0 @@
import items.*;
import pokemon.Pokemon;
import storage.Inventory;
import storage.Trainer;
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.NumberFormatException;
import java.text.NumberFormat;
import java.text.ParseException;
/** Simulates the game Pokémon */
public class Game {
public static final Scanner in = new Scanner(System.in);
private static Pokemon opponentPokemon;
private static List<Pokemon> availableOpponentPokemon;
private static Pokemon playersCurrentPokemon;
private static Trainer player;
public static void main(String[] args) {
availableOpponentPokemon = readPokemon();
int initialPokemon = availableOpponentPokemon.size();
System.out.println("What is your name?");
String name = in.nextLine();
player = new Trainer(name, randomTeam(), createInventory());
boolean done = false;
triggerNewEncounter();
while (!done) {
if (opponentPokemon == null) {
System.out.printf("You have brutally murdered %d pokemon.%n"
+ "The only ones left are the ones in your possession.%n"
+ "There really is nothing more for you to do here.%n", initialPokemon);
return;
}
if (player.getConsciousPokemon().size() < 1) {
System.out.println("All your pokemon have fainted. Your journey ends here.");
return;
}
while (playersCurrentPokemon == null || !playersCurrentPokemon.isConscious()) {
player.listAvailablePokemon(true);
playersCurrentPokemon = player.choosePokemon(true);
}
System.out.printf("Opponent: %s%nWhat will you do?%n", opponentPokemon);
System.out.printf("b: battle"
+ "%nh: heal or revive"
+ "%nt: throw poke ball"
+ "%nc: change pokemon"
+ "%nf: flee"
+ "%nv: view my pokemon"
+ "%ns: save"
+ "%nl: load"
+ "%nq: quit%n>");
char command = in.next().toLowerCase().charAt(0);
switch (command) {
case 'b':
battle();
break;
case 'h':
healPokemon();
break;
case 't':
throwPokeBall();
break;
case 'c':
choosePokemon();
break;
case 's':
save();
break;
case 'l':
load();
break;
case 'f':
flee();
break;
case 'v':
showPokemon();
break;
case 'q':
done = true;
break;
default:
System.out.println("[Invalid command]");
}
}
}
/**
* Lists all of the player's pokemon
*/
private static void showPokemon() {
player.printPokemon();
}
/**
* Tries to flee from the current opponent
*/
private static void flee() {
boolean fleeSuccessful = playersCurrentPokemon.flee(opponentPokemon);
if (fleeSuccessful) {
System.out.println("You fled the battle.");
triggerNewEncounter();
} else {
System.out.printf("Failed to flee from %s.%n", opponentPokemon.getName());
opponentPokemon.attack(playersCurrentPokemon);
}
}
/**
* Loads game information from a save
*/
private static void load() {
List<Pokemon> loadedPokemon = loadPokemon("pokemon.save");
List<Pokemon> loadedUsersPokemon = loadPokemon("user.save");
Inventory loadedInventory = loadInventory("inventory.save");
if (loadedPokemon == null || loadedUsersPokemon == null || loadedInventory == null) {
System.out.println("One or more save files seem corrupt or missing. Please delete, create or fix the affected file(s).");
} else {
availableOpponentPokemon = loadedPokemon;
player.setPokemon(loadedUsersPokemon);
player.setInventory(loadedInventory);
if (availableOpponentPokemon.size() > 0 && player.getPokemon().size() > 0) {
do {
player.listAvailablePokemon(true);
playersCurrentPokemon = player.choosePokemon(true);
} while (playersCurrentPokemon == null || !playersCurrentPokemon.isConscious());
opponentPokemon = randomPokemon(availableOpponentPokemon);
}
}
}
/**
* Saves all stats about the game
*/
private static void save() {
savePokemon(availableOpponentPokemon, "pokemon.save");
savePokemon(player.getPokemon(), "user.save");
saveInventory(player.getInventory(), "inventory.save");
}
/**
* Chooses a new pokemon from the player's available pokemon
*/
private static void choosePokemon() {
player.listAvailablePokemon(true);
playersCurrentPokemon = player.choosePokemon(true);
while (playersCurrentPokemon == null) {
player.listAvailablePokemon(true);
playersCurrentPokemon = player.choosePokemon(true);
}
opponentPokemon.attack(playersCurrentPokemon);
}
/**
* Makes the player's pokemon attack the enemy pokemon
*/
private static void battle() {
if (opponentPokemon.isConscious() && playersCurrentPokemon.isConscious()) {
playersCurrentPokemon.attack(opponentPokemon);
if (opponentPokemon.isConscious()) {
opponentPokemon.attack(playersCurrentPokemon);
if (!playersCurrentPokemon.isConscious()) {
System.out.println("Your pokemon fainted.");
}
} else {
pokemonFainted(availableOpponentPokemon, opponentPokemon);
System.out.println("The opponent pokemon fainted.");
triggerNewEncounter();
}
}
}
/**
* Heals a pokemon if possible
*/
private static void healPokemon() {
if (player.getInventory().getPotions().size() > 0) {
player.getInventory().availablePotions();
AbstractPotion currentPotion = player.getInventory().getChosenPotion();
if (currentPotion == null) {
in.nextLine();
System.out.println("Invalid potion.");
} else {
Pokemon pokemonToHeal;
if (currentPotion.needsAlive()) {
player.listAvailablePokemon(true);
pokemonToHeal = player.choosePokemon(true);
} else {
player.listAvailablePokemon(false);
pokemonToHeal = player.choosePokemon(false);
}
if (pokemonToHeal == null) {
System.out.println("That is not a valid pokemon");
} else {
if (currentPotion.use(pokemonToHeal)) {
player.getInventory().addItem(currentPotion, -1);
opponentPokemon.attack(playersCurrentPokemon);
}
}
}
} else {
System.out.println("You have used all your healing items.");
}
}
/**
* Tries throwing a poke ball at the enemy pokemon
*/
private static void throwPokeBall() {
if (player.getInventory().getPokeBalls().size() > 0) {
player.getInventory().availablePokeBalls();
AbstractPokeBall currentPokeBall = player.getInventory().getChosenPokeBall();
if (currentPokeBall == null) {
in.nextLine();
System.out.println("Invalid poke ball.");
} else {
boolean captured = currentPokeBall.use(opponentPokemon, availableOpponentPokemon, player);
player.getInventory().addItem(currentPokeBall, -1);
if (captured) {
triggerNewEncounter();
} else {
opponentPokemon.attack(playersCurrentPokemon);
}
}
} else {
System.out.println("You have used all your poke balls.");
}
}
/**
* Triggers an encounter with a new wild pokemon
*/
private static void triggerNewEncounter() {
opponentPokemon = randomPokemon(availableOpponentPokemon);
System.out.printf("A wild %s appeared.%n", opponentPokemon.getName());
}
/**
* Removes a fainted pokemon from encounter-able pokemon
* @param pokemonList <p>List of pokemon to search</p>
* @param target <p>The pokemon to remove</p>
*/
public static void pokemonFainted(List<Pokemon> pokemonList, Pokemon target) {
pokemonList.removeIf(pokemon -> pokemon.equals(target));
}
/**
* Gives a trainer necessary starting items
* @return <p>A list of items</p>
*/
public static Inventory createInventory() {
Inventory inventory = new Inventory();
inventory.addItem(new PokeBall(), 15);
inventory.addItem(new GreatBall(), 10);
inventory.addItem(new UltraBall(), 5);
inventory.addItem(new MasterBall(), 1);
inventory.addItem(new Potion(), 20);
inventory.addItem(new SuperPotion(), 10);
inventory.addItem(new HyperPotion(), 5);
inventory.addItem(new MaxPotion(), 1);
inventory.addItem(new Revive(), 2);
return inventory;
}
/**
* Chooses a random pokemon from a list
* @param pokemon <p>The list to choose from</p>
* @return <p>A pokemon.Pokemon object, or null if the list is empty</p>
*/
public static Pokemon randomPokemon(List<Pokemon> pokemon) {
if (pokemon.size() > 0) {
return pokemon.get((int)(Math.random() * pokemon.size()));
} else {
throw new IllegalArgumentException("Can't get random pokemon from empty list");
}
}
/**
* Reads pokemon from pokemon.Pokemon.txt to an ArrayList.
* @return <p>An ArrayList of pokemon objects</p>
*/
public static ArrayList<Pokemon> readPokemon() {
ArrayList<Pokemon> pokemon = new ArrayList<>();
try (Scanner file = new Scanner(new File("config/Pokemon.txt"))) {
while (file.hasNextLine()) {
pokemon.add(new Pokemon(file.nextLine()));
}
} catch (FileNotFoundException e) {
/* If the file is compiled as jar, this will prevent an empty list. */
try (Scanner file = new Scanner(Game.class.getResourceAsStream("config/Pokemon.txt"))) {
while (file.hasNextLine()) {
pokemon.add(new Pokemon(file.nextLine()));
}
}
}
return pokemon;
}
/**
* Picks a random pokemon from a list
* @param pokemon <p>A list of pokemon objects</p>
* @return <p>A pokemon object which exists in the input list</p>
*/
public static Pokemon pickRandomPokemon(ArrayList<Pokemon> pokemon) {
int index = (int)(Math.random() * (pokemon.size()));
Pokemon randomPokemon = pokemon.get(index);
pokemon.remove(index);
return randomPokemon;
}
/**
* Saves all pokemon in a list to a text file
* @param pokemonList <p>List of pokemon.Pokemon objects to save</p>
* @param saveFile <p>The file to write to</p>
*/
public static void savePokemon(List<Pokemon> pokemonList, String saveFile) {
try (PrintWriter file = new PrintWriter(saveFile)) {
for (Pokemon pokemon : pokemonList) {
file.println(pokemon.saveString());
}
System.out.println("Successfully saved pokemon.");
} catch (FileNotFoundException e) {
System.out.println("The saveFile could not be written.");
}
}
/**
* Saves the inventory to a text file
* @param inventory <p>The inventory to save</p>
* @param saveFile <p>The file to write to</p>
*/
public static void saveInventory(Inventory inventory, String saveFile) {
try (PrintWriter file = new PrintWriter(saveFile)) {
file.println(inventory.getSaveString());
System.out.println("Successfully saved inventory.");
} catch (FileNotFoundException e) {
System.out.println("The saveFile could not be written.");
}
}
/**
* Loads pokemon from a text file
* @param saveFile <p>The file to read</p>
* @return <p>A list of pokemon or null on failure</p>
*/
public static ArrayList<Pokemon> loadPokemon(String saveFile) {
ArrayList<Pokemon> pokemon = new ArrayList<>();
try (Scanner file = new Scanner(new File(saveFile))) {
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
while (file.hasNextLine()) {
String[] data = file.nextLine().split(";");
try {
pokemon.add(new Pokemon(data[0], Integer.parseInt(data[1]), Integer.parseInt(data[2]),
Integer.parseInt(data[3]), format.parse(data[4]).doubleValue(),
Integer.parseInt(data[5]), Integer.parseInt(data[6]), Integer.parseInt(data[7])));
} catch (NumberFormatException | ParseException e) {
System.out.println("Malformed number " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid saveFile: " + saveFile);
return null;
}
}
System.out.println("Successfully loaded pokemon.");
} catch (FileNotFoundException e) {
System.out.println("Missing saveFile " + saveFile);
return null;
}
return pokemon;
}
/**
* Loads inventory from a text file
* @param saveFile <p>The file to write to</p>
* @return <p>A list of items or null on failure</p>
*/
public static Inventory loadInventory(String saveFile) {
Inventory inventory = new Inventory();
try (Scanner file = new Scanner(new File(saveFile))) {
while (file.hasNextLine()) {
try {
String line = file.nextLine();
if (line.isEmpty()) {
break;
}
String[] data = line.split(";");
inventory.addItem(Item.getItemByName(data[0]), Integer.parseInt(data[1]));
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid saveFile: " + saveFile);
return null;
}
}
System.out.println("Successfully loaded items.");
} catch (FileNotFoundException e) {
System.out.println("Missing saveFile " + saveFile);
return null;
}
return inventory;
}
/**
* Returns a random list of 6 pokemon
* @return <p>A list of pokemon.Pokemon</p>
*/
public static ArrayList<Pokemon> randomTeam() {
ArrayList<Pokemon> temporary = readPokemon();
ArrayList<Pokemon> pokemon = new ArrayList<>();
for (int i = 1; i <= 6; i++) {
pokemon.add(pickRandomPokemon(temporary));
}
return pokemon;
}
}

View File

@ -1,31 +0,0 @@
package items;
import pokemon.Pokemon;
import storage.Trainer;
import java.util.List;
/**
* An abstract class representing a poke ball
*/
public abstract class AbstractPokeBall extends Item {
/**
* Instantiates a new poke ball
* @param name <p>The name of the poke ball</p>
* @param description <p>The description of the poke ball</p>
*/
public AbstractPokeBall(String name, String description) {
super(name, description);
}
/**
* Uses a poke ball on an opponent
* @param target <p>Which pokemon to target</p>
* @param current <p>Current list the pokemon belongs to</p>
* @param catcher <p>Where we send the pokemon on a successful capture</p>
* @return <p>True if nothing went wrong. False otherwise</p>
*/
public boolean use(Pokemon target, List<Pokemon> current, Trainer catcher) {
return false;
}
}

View File

@ -1,67 +0,0 @@
package items;
import pokemon.Pokemon;
/**
* An abstract class representing a potion
*/
public abstract class AbstractPotion extends Item {
final boolean alive;
/**
* Instantiates a new potion
* @param name <p>The name of the potion</p>
* @param description <p>The description of the potion</p>
*/
public AbstractPotion(String name, String description) {
super(name, description);
this.alive = true;
}
/**
* Instantiates a new potion
* @param name <p>The name of the potion</p>
* @param description <p>The description of the potion</p>
* @param alive <p>Whether the pokemon needs to be alive to use the potion</p>
*/
public AbstractPotion(String name, String description, boolean alive) {
super(name, description);
this.alive = alive;
}
/** Checks if an item should be used on alive or fainted pokemon. */
public boolean needsAlive() {
return alive;
}
/**
* Uses an item and does something based on the type of item
* @param target <p>Which pokemon should the item be used on</p>
* @return <p>True if nothing went wrong. False otherwise</p>
*/
public boolean use(Pokemon target) {
return false;
}
/**
* Checks if a pokemon is able to, and in need of a potion. If it is, heal it
* @param target <p>The pokemon to heal</p>
* @param amount <p>The amount to heal the pokemon</p>
* @return <p>True if nothing went wrong. False otherwise</p>
*/
boolean potion(Pokemon target, int amount) {
if (target.isConscious()) {
if (target.isDamaged()) {
int healed = target.heal(amount);
System.out.printf("%s was healed for %d HP and now has %d HP.%n", target.getName(), healed, target.getHP());
return true;
} else {
System.out.printf("%s has not taken damage, and does not require a potion.%n", target.getName());
return false;
}
} else {
System.out.println("You can't heal a fainted pokemon.");
return false;
}
}
}

View File

@ -1,22 +0,0 @@
package items;
import pokemon.Pokemon;
import storage.Trainer;
import java.util.List;
/**
* This class represents a great ball item
*/
public class GreatBall extends AbstractPokeBall {
public GreatBall() {
super("Great ball",
"A good, high-performance Poké Ball that provides a higher Pokémon catch rate than a " +
"standard Poké Ball.");
}
@Override
public boolean use(Pokemon target, List<Pokemon> current, Trainer catcher) {
return target.tryCapture(current, catcher, 200);
}
}

View File

@ -1,17 +0,0 @@
package items;
import pokemon.Pokemon;
/**
* This class represents a hyper potion item
*/
public class HyperPotion extends AbstractPotion {
public HyperPotion() {
super("Hyper Potion", "Heals a pokemon for 200 HP.");
}
@Override
public boolean use(Pokemon target) {
return potion(target, 200);
}
}

View File

@ -1,82 +0,0 @@
package items;
import java.util.ArrayList;
import java.util.List;
/**
* This class represents a general item which can be stored in an inventory
*/
public abstract class Item {
final String name;
final String description;
static final List<Item> availableItems = new ArrayList<>();
/**
* Instantiates a new item
* @param name <p>The name of the item</p>
* @param description <p>The description of the item</p>
*/
public Item(String name, String description) {
this.name = name;
this.description = description;
}
/**
* Returns an item by the given name
* @param name <p>The name of the item to get</p>
* @return <p>An item with the name, or null if no such item exists</p>
*/
public static Item getItemByName(String name) {
if (availableItems.isEmpty()) {
initializeItems();
}
for (Item item : availableItems) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
/**
* Initializes all known items so that they are usable
*/
private static void initializeItems() {
availableItems.add(new PokeBall());
availableItems.add(new GreatBall());
availableItems.add(new HyperPotion());
availableItems.add(new MasterBall());
availableItems.add(new MaxPotion());
availableItems.add(new Potion());
availableItems.add(new Revive());
availableItems.add(new SuperPotion());
availableItems.add(new UltraBall());
}
/**
* Makes a nice string describing the item
* @return <p>Name: Description</p>
*/
public String toString() {
return String.format("%s: %s", this.name, this.description);
}
/**
* Returns a string used for saving the item
* @return <p>Name;Description</p>
*/
public String saveString() {
return String.format("%s", this.name);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!Item.class.isAssignableFrom(obj.getClass())) {
return false;
}
return this.name.equals(((Item) obj).name);
}
}

View File

@ -1,21 +0,0 @@
package items;
import pokemon.Pokemon;
import storage.Trainer;
import java.util.List;
/**
* This class represents a master ball item
*/
public class MasterBall extends AbstractPokeBall {
public MasterBall() {
super("Master ball", "The best Poké Ball with the ultimate level of performance. With it, " +
"you will catch any wild Pokémon without fail.");
}
@Override
public boolean use(Pokemon target, List<Pokemon> current, Trainer catcher) {
return target.tryCapture(current, catcher, 0);
}
}

View File

@ -1,17 +0,0 @@
package items;
import pokemon.Pokemon;
/**
* This class represents a max potion item
*/
public class MaxPotion extends AbstractPotion {
public MaxPotion() {
super("Max Potion", "Fully heals a pokemon.");
}
@Override
public boolean use(Pokemon target) {
return potion(target, -1);
}
}

View File

@ -1,21 +0,0 @@
package items;
import pokemon.Pokemon;
import storage.Trainer;
import java.util.List;
/**
* This class represents a poke ball item
*/
public class PokeBall extends AbstractPokeBall {
public PokeBall() {
super("Poke Ball", "A device for catching wild Pokémon. It's thrown like a ball at a " +
"Pokémon, comfortably encapsulating its target.");
}
@Override
public boolean use(Pokemon target, List<Pokemon> current, Trainer catcher) {
return target.tryCapture(current, catcher, 255);
}
}

View File

@ -1,20 +0,0 @@
package items;
import pokemon.Pokemon;
/**
* This class represents potion item
*/
public class Potion extends AbstractPotion {
/**
* Instantiates a potion
*/
public Potion() {
super("Potion", "Heals a pokemon for 20 HP.");
}
@Override
public boolean use(Pokemon target) {
return potion(target, 20);
}
}

View File

@ -1,24 +0,0 @@
package items;
import pokemon.Pokemon;
/**
* This class represents a revive item
*/
public class Revive extends AbstractPotion {
public Revive() {
super("Revive", "Revives a fainted pokemon.", true);
}
@Override
public boolean use(Pokemon target) {
if (!target.isConscious()) {
target.revive();
System.out.printf("%s was revived.%n", target.getName());
return true;
} else {
System.out.println("You can't revive a conscious pokemon.");
return false;
}
}
}

View File

@ -1,17 +0,0 @@
package items;
import pokemon.Pokemon;
/**
* This class represents a super potion item
*/
public class SuperPotion extends AbstractPotion {
public SuperPotion() {
super("Super Potion", "Heals a pokemon for 50 HP.");
}
@Override
public boolean use(Pokemon target) {
return potion(target, 50);
}
}

View File

@ -1,21 +0,0 @@
package items;
import pokemon.Pokemon;
import storage.Trainer;
import java.util.List;
/**
* This class represents an ultra ball item
*/
public class UltraBall extends AbstractPokeBall {
public UltraBall() {
super("Ultra ball", "An ultra-high-performance Poké Ball that provides a higher success rate " +
"for catching Pokémon than a Great Ball.");
}
@Override
public boolean use(Pokemon target, List<Pokemon> current, Trainer catcher) {
return target.tryCapture(current, catcher, 150);
}
}

View File

@ -1,243 +0,0 @@
package pokemon;
import storage.Trainer;
import java.util.List;
import java.util.Random;
/**
* This class represents a pokemon
*/
public class Pokemon {
private final String name;
private int healthPoints;
private int maxHealthPoints;
private int strength;
private final double criticalChance;
private final Random random;
private final int catchRate;
private int exp;
private int level;
private int fleeCount;
/**
* Instantiates a new pokemon with random stats
* @param name <p>The name of the pokemon</p>
*/
public Pokemon(String name) {
this.random = new Random();
this.name = name;
this.healthPoints = 30 + random.nextInt(70);
this.maxHealthPoints = this.healthPoints;
this.criticalChance = Math.abs(0.1 * random.nextGaussian());
this.catchRate = (int)(Math.random() * 256);
this.exp = 0;
this.level = (int)(Math.abs(2 * random.nextGaussian()) + 1);
this.strength = random.nextInt(7) + this.level;
this.fleeCount = 0;
}
/**
* Instantiates a pokemon with set stats
* @param name <p>The name of the pokemon</p>
* @param healthPoints <p>The current HP of the pokemon</p>
* @param maxHealthPoints <p>The max HP of the pokemon</p>
* @param strength <p>The strength of the pokemon</p>
* @param criticalChance <p>The critical hit chance of the pokemon</p>
* @param catchRate <p>The catch rate of the pokemon. A higher rate makes it easier to catch</p>
* @param exp <p>The current xp of the pokemon</p>
* @param level <p>The current level of the pokemon</p>
*/
public Pokemon(String name, int healthPoints, int maxHealthPoints, int strength, double criticalChance, int catchRate, int exp, int level) {
this.random = new Random();
this.name = name;
this.healthPoints = healthPoints;
this.maxHealthPoints = maxHealthPoints;
this.criticalChance = criticalChance;
this.catchRate = catchRate;
this.exp = exp;
this.level = level;
this.strength = strength;
this.fleeCount = 0;
}
/**
* Makes a string containing all information about the pokemon
* @return <p>A descriptive string</p>
*/
public String toString() {
return String.format("Level %d %s HP: (%d/%d) STR: %d CHC: %.0f%%", this.level, this.name, this.healthPoints,
this.maxHealthPoints, this.strength, (this.criticalChance*100));
}
/**
* Returns a string containing all the pokemon's data in a save-able format
*/
public String saveString() {
return String.format("%s;%d;%d;%d;%f;%d;%d;%d", this.name, this.healthPoints, this.maxHealthPoints,
this.strength, this.criticalChance, this.catchRate, this.exp, this.level);
}
/**
* Gets the name of the pokemon
* @return <p>The name of the pokemon</p>
*/
public String getName() {
return this.name;
}
/**
* Gets the current hit points of the pokemon
* @return <p>The current HP of the pokemon</p>
*/
public int getHP() {
return this.healthPoints;
}
/**
* Checks whether two pokemon are equal
* @param target <p>The pokemon to check against</p>
* @return <p>True if they are equal. False otherwise</p>
*/
public boolean equals(Pokemon target) {
return target == this;
}
/**
* Heals a pokemon
* @param amount <p>How many hit points to heal</p>
* @return <p>The exact amount of hit points healed</p>
*/
public int heal(int amount) {
if (amount < 0) {
amount = this.maxHealthPoints - this.healthPoints;
} else {
amount = Math.min(this.maxHealthPoints - this.healthPoints, amount);
}
this.healthPoints += amount;
return amount;
}
/**
* Checks if a pokemon has not taken any damage or is fully healed
* @return <p>True if health is full. False otherwise</p>
*/
public boolean isDamaged() {
return this.healthPoints < this.maxHealthPoints;
}
/**
* Tries to catch a pokemon
* @param current <p>The list where the pokemon currently belongs</p>
* @param catcher <p>The list to send the pokemon on successful capture</p>
* @return <p>True on successful capture. False otherwise</p>
*/
public boolean tryCapture(List<Pokemon> current, Trainer catcher, int range) {
if (range == 0) {
this.capture(current, catcher);
System.out.printf("%s was caught.%n", this.name);
return true;
}
if ((int)(Math.random() * (range + 1)) < Math.max((3 * this.maxHealthPoints - 2 * this.healthPoints) *
this.catchRate / (3 * this.maxHealthPoints), 1)) {
this.capture(current, catcher);
System.out.printf("%s was caught.%n", this.name);
return true;
} else {
System.out.printf("%s escaped from the poke ball.%n", this.name);
return false;
}
}
/**
* Captures a wild pokemon
* @param current <p>The pokemon list the pokemon belongs to</p>
* @param trainer <p>The trainer capturing the pokemon</p>
*/
private void capture(List<Pokemon> current, Trainer trainer) {
trainer.addPokemon(this);
current.removeIf(pokemon -> pokemon == this);
}
/**
* Restores the health of a fainted pokemon
*/
public void revive() {
this.healthPoints = this.maxHealthPoints;
}
/**
* Checks if the pokemon has any HP left
* @return <p>True if any HP is left. False otherwise</p>
*/
public boolean isConscious() {
return this.healthPoints > 0;
}
/**
* Damages a pokemon
* @param damageTaken <p>How many hit points are to be deducted</p>
*/
public void damage(int damageTaken) {
this.healthPoints = Math.max(this.healthPoints -= damageTaken, 0);
System.out.printf("%s takes %d damage and is left with %d/%d HP%n", this.name, damageTaken, this.healthPoints, this.maxHealthPoints);
}
/**
* Gives a pokemon exp after each successful battle. Also handles leveling up
* @param target <p>Which pokemon did we beat</p>
*/
private void giveEXP(Pokemon target) {
int exp = (100 * target.level)/7;
this.exp += exp;
System.out.printf("%s gained %d exp.%n", this.name, exp);
if (this.exp > (4 * Math.pow(this.level, 3)) / 5) {
this.level++;
this.maxHealthPoints += 5;
this.healthPoints = maxHealthPoints;
this.strength += 1;
System.out.printf("%s is now level %d. Health has been increased and restored. Strength has been increased.%n", this.name, this.level);
}
}
/**
* Makes a pokemon attack another pokemon
* @param target <p>The pokemon to take damage</p>
*/
public void attack(Pokemon target) {
if (this.healthPoints > 0) {
System.out.printf("%s attacks %s.%n", this.getName(), target.getName());
double critical = 1;
if (Math.random() < this.criticalChance) {
System.out.println("Critical hit!");
critical = (2.0 * this.level +5) / (this.level + 5);
}
double randomDouble = 0.85 + (1.0 - 0.85) * random.nextDouble();
int moveDamage = (int)(Math.random() * 60 + 40);
int damageInflicted = this.level + (int)((((((2 * this.strength) / 5) + 2) * moveDamage * 1.75) / 50 + 2) * critical * randomDouble);
target.damage(damageInflicted);
if (!target.isConscious()) {
System.out.printf("%s is defeated by %s.%n", target.getName(), this.getName());
this.giveEXP(target);
this.fleeCount = 0;
}
} else {
System.out.println("No cheating!");
}
}
/**
* The trainer may flee if the battle is too hard
* @param target <p>Who are we trying to flee from</p>
* @return <p>True on successful escape. False otherwise</p>
*/
public boolean flee(Pokemon target) {
if (random.nextInt(256) < (this.level * 128 / target.level) + (30 * this.fleeCount % 256)) {
this.fleeCount = 0;
return true;
} else {
this.fleeCount++;
return false;
}
}
}

View File

@ -1,136 +0,0 @@
package storage;
import items.*;
import java.util.*;
/**
* This class represents a pokemon trainer's inventory
*/
public class Inventory {
public static final Scanner in = new Scanner(System.in);
private final Map<Item, Integer> items;
/**
* Initializes a new empty inventory
*/
public Inventory() {
this.items = new HashMap<>();
}
/**
* Adds a new item to the inventory
*
* <p>If the inventory already contains the item, the amount will be added to the existing amount.</p>
*
* @param item <p>The item to be added to the inventory</p>
* @param amount <p>The amount of the item to add</p>
*/
public void addItem(Item item, Integer amount) {
if (items.get(item) != null) {
amount += items.get(item);
}
items.put(item, amount);
}
/**
* Gets all available poke balls from the inventory
* @return <p>A list of poke balls</p>
*/
public List<AbstractPokeBall> getPokeBalls() {
List<AbstractPokeBall> pokeBalls = new ArrayList<>();
for (Item item : items.keySet()) {
if (AbstractPokeBall.class.isAssignableFrom(item.getClass()) && items.get(item) > 0) {
pokeBalls.add((AbstractPokeBall) item);
}
}
return pokeBalls;
}
/**
* Gets all available potions from the inventory
* @return <p>A list of potions</p>
*/
public List<AbstractPotion> getPotions() {
List<AbstractPotion> potions = new ArrayList<>();
for (Item item : items.keySet()) {
if (AbstractPotion.class.isAssignableFrom(item.getClass()) && items.get(item) > 0) {
potions.add((AbstractPotion) item);
}
}
return potions;
}
/**
* Prints out information about available poke balls
*/
public void availablePokeBalls() {
System.out.println("You may choose from these items:");
List<AbstractPokeBall> pokeBalls = getPokeBalls();
for (int i = 0; i < pokeBalls.size(); i++) {
System.out.printf("%d: (%d) %s%n", i + 1, items.get(pokeBalls.get(i)), pokeBalls.get(i));
}
System.out.print(">");
}
/**
* Prints out information about available potions
*/
public void availablePotions() {
System.out.println("You may choose from these items:");
List<AbstractPotion> potionList = getPotions();
for (int i = 0; i < potionList.size(); i++) {
System.out.printf("%d: (%d) %s%n", i + 1, items.get(potionList.get(i)), potionList.get(i));
}
System.out.print(">");
}
/**
* Gets a potion according to the user's input
* @return <p>The potion the user chose, or null on invalid choice</p>
*/
public AbstractPotion getChosenPotion() {
List<AbstractPotion> potions = getPotions();
if (in.hasNextInt()) {
int choice = in.nextInt() - 1;
if (choice >= 0 && choice < potions.size()) {
in.nextLine();
return potions.get(choice);
}
} else {
in.nextLine();
}
return null;
}
/**
* Gets a poke ball according to the user's input
* @return <p>The poke ball the user chose, or null on invalid choice</p>
*/
public AbstractPokeBall getChosenPokeBall() {
List<AbstractPokeBall> pokeBalls = getPokeBalls();
if (in.hasNextInt()) {
int choice = in.nextInt() - 1;
if (choice >= 0 && choice < pokeBalls.size()) {
in.nextLine();
return pokeBalls.get(choice);
}
} else {
in.nextLine();
}
return null;
}
/**
* Gets a save-able string containing all non-empty items in the inventory
* @return <p>A save string Name;Amount</p>
*/
public String getSaveString() {
StringBuilder saveString = new StringBuilder();
for (Item item : items.keySet()) {
saveString.append(item.saveString()).append(";").append(items.get(item));
saveString.append("\n");
}
return saveString.toString();
}
}

View File

@ -1,147 +0,0 @@
package storage;
import pokemon.Pokemon;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* This class represents a pokemon trainer
*/
public class Trainer {
public static final Scanner in = new Scanner(System.in);
final String name;
private List<Pokemon> pokemon;
private Inventory inventory;
/**
* Instantiates a new trainer
* @param name <p>The name of the trainer</p>
* @param pokemon <p>The pokemon belonging to the trainer</p>
* @param inventory <p>The inventory belonging to the trainer</p>
*/
public Trainer(String name, ArrayList<Pokemon> pokemon, Inventory inventory) {
this.name = name;
this.pokemon = pokemon;
this.inventory = inventory;
}
/**
* Sets the list of pokemon belonging to the trainer
* @param pokemon <p>A list of pokemon</p>
*/
public void setPokemon(List<Pokemon> pokemon) {
this.pokemon = pokemon;
}
/**
* Sets the inventory belonging to the trainer
* @param inventory <p>An inventory</p>
*/
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
/**
* Gets the list of pokemon belonging to the trainer
* @return <p>A list of pokemon</p>
*/
public List<Pokemon> getPokemon() {
return this.pokemon;
}
/**
* Adds a pokemon to the trainer's list of pokemon
* @param pokemon <p>A pokemon</p>
*/
public void addPokemon(Pokemon pokemon) {
this.pokemon.add(pokemon);
}
/**
* Gets all conscious pokemon belonging to the trainer
* @return <p>A list of pokemon</p>
*/
public ArrayList<Pokemon> getConsciousPokemon() {
ArrayList<Pokemon> pokemon = new ArrayList<>();
for (Pokemon singlePokemon : this.pokemon) {
if (singlePokemon.isConscious()) {
pokemon.add(singlePokemon);
}
}
return pokemon;
}
/**
* Gets all fainted pokemon belonging to the trainer
* @return <p>A list of pokemon</p>
*/
public ArrayList<Pokemon> getFaintedPokemon() {
ArrayList<Pokemon> pokemon = new ArrayList<>();
for (Pokemon singlePokemon : this.pokemon) {
if (!singlePokemon.isConscious()) {
pokemon.add(singlePokemon);
}
}
return pokemon;
}
/**
* Gets the inventory of the user
* @return <p>An inventory</p>
*/
public Inventory getInventory() {
return this.inventory;
}
/**
* Lists all currently available pokemon for the trainer
* @param alive <p>Whether to list alive pokemon or dead</p>
*/
public void listAvailablePokemon(boolean alive) {
ArrayList<Pokemon> pokemonList;
if (alive) {
pokemonList = this.getConsciousPokemon();
} else {
pokemonList = this.getFaintedPokemon();
}
System.out.println("You may choose from these pokemon:");
for (int i = 0; i < pokemonList.size(); i++) {
System.out.printf("%d: %s%n", i + 1, pokemonList.get(i));
}
System.out.print(">");
}
/**
* Prints all pokemon belonging to the trainer
*/
public void printPokemon() {
for (Pokemon pokemon : this.pokemon) {
System.out.println(pokemon);
}
}
/**
* Asks the user for the name of a pokemon and returns it
* @param alive <p>Whether the chosen pokemon has to be alive</p>
* @return <p>A pokemon object or null</p>
*/
public Pokemon choosePokemon(boolean alive) {
ArrayList<Pokemon> pokemonList;
if (alive) {
pokemonList = this.getConsciousPokemon();
} else {
pokemonList = this.getFaintedPokemon();
}
if (in.hasNextInt()) {
int choice = in.nextInt() - 1;
if (choice >= 0 && choice < pokemonList.size()) {
in.nextLine();
return pokemonList.get(choice);
}
}
in.nextLine();
return null;
}
}