This commit is contained in:
Reza
2026-05-10 22:35:43 +03:30
parent 78d4bedb08
commit 74661a417d
50 changed files with 1009 additions and 306 deletions
+5
View File
@@ -16,5 +16,10 @@
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://mirror-maven.runflare.com/maven2" />
</remote-repository>
</component>
</project>
@@ -0,0 +1,11 @@
package org.project;
public class ConsoleColors {
public static final String RESET = "\u001B[0m";
public static final String RED = "\u001B[31m";
public static final String GREEN = "\u001B[32m";
public static final String BLUE = "\u001B[34m";
public static final String YELLOW = "\u001B[33m";
public static final String PURPLE = "\u001B[35m";
public static final String CYAN = "\u001B[36m";
}
+293 -6
View File
@@ -1,15 +1,302 @@
package org.project;
import org.project.entity.enemies.*;
import org.project.entity.players.Knight;
import org.project.entity.players.Player;
import org.project.item.*;
import org.project.item.armors.*;
import org.project.item.consumables.Flask;
import org.project.item.weapons.Sword;
import org.project.location.Location;
import org.project.entity.players.Wizard;
import org.project.entity.players.Assassin;
import org.project.ConsoleColors;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
public class Main {
public static void main(String[] args) {
// TODO: ADD LOCATIONS TO YOUR GAME
List<Location> locations = new ArrayList<>();
private static Scanner input = new Scanner(System.in);
private static Random rand = new Random();
private static Player hero;
private static List<Location> map;
private static Location castle;
private static Map<String, Boolean> collectedKeys;
// TODO: IMPLEMENT GAMEPLAY
public static void main(String[] args) {
setup();
runGame();
}
private static void setup() {
System.out.print("Choose class (1=Knight, 2=Wizard, 3=Assassin): ");
int classPick = input.nextInt();
input.nextLine();
if (classPick == 1) {
hero = new Knight("Arin");
}
else if (classPick == 2) {
hero = new Wizard("Merlin");
}
else if (classPick == 3) {
hero = new Assassin("Ezio");
}
else {
hero = new Knight("Arin");
}
collectedKeys = new HashMap<>();
collectedKeys.put("Goblin", false);
collectedKeys.put("Skeleton", false);
collectedKeys.put("Vampire", false);
map = new ArrayList<>();
Location woods = new Location("Dark Woods");
woods.addEnemy(new Goblin());
woods.addEnemy(new Skeleton());
woods.addEnemy(new Vampire());
map.add(woods);
Location crypt = new Location("Ancient Crypt");
crypt.addEnemy(new Skeleton());
crypt.addEnemy(new Vampire());
map.add(crypt);
castle = new Location("Dragon's Castle");
castle.addEnemy(new Dragon());
}
private static void runGame() {
while (hero.isAlive()) {
boolean allKeys = collectedKeys.get("Goblin") && collectedKeys.get("Skeleton") && collectedKeys.get("Vampire");
if (allKeys) {
System.out.println("\nYou have all three keys! The castle door creaks open...");
System.out.println("1. Enter Castle");
System.out.println("2. Keep exploring");
int cmd = input.nextInt();
input.nextLine();
if (cmd == 1) {
fightDragon();
return;
}
}
System.out.println("\n--- What do you want to do? ---");
System.out.println("1. Hunt for enemies");
System.out.println("2. Travel to another place");
System.out.println("3. Visit Merchant");
System.out.println("4. Use a Flask from bag");
System.out.println("5. Quit game");
int cmd = input.nextInt();
input.nextLine();
if (cmd == 1) {
randomBattle();
}
else if (cmd == 2) {
travel();
}
else if (cmd == 3) {
merchant();
}
else if (cmd == 4) {
useFlaskOutsideCombat();
}
else if (cmd == 5) {
System.out.println("Farewell, " + hero.getClass().getSimpleName() + ".");
return;
}
else {
System.out.println("Wrong input.");
}
}
System.out.println(ConsoleColors.RED + "You have fallen... Game Over." + ConsoleColors.RESET);
}
private static Enemy getRandomEnemy() {
int r = rand.nextInt(3);
if (r == 0) return new Goblin();
else if (r == 1) return new Skeleton();
else return new Vampire();
}
private static void randomBattle() {
Location current = map.get(rand.nextInt(map.size()));
Enemy foe = getRandomEnemy();
System.out.println("\nA " + foe.getClass().getSimpleName() + " ambushes you in " + current.getName() + "!");
fight(foe);
if (hero.isAlive() && !foe.isAlive()) {
rewards(foe);
}
}
private static String getSpecialAbilityName() {
if (hero instanceof Knight) return "Shield Bash";
else if (hero instanceof Wizard) return "Arcane Blast";
else if (hero instanceof Assassin) return "Shadow Cloak";
return "Special Ability";
}
private static void fight(Enemy foe) {
while (hero.isAlive() && foe.isAlive()) {
System.out.println("\n[" + hero.getName() + " | HP: " + hero.getHp() + "/" + hero.getMaxHP() + " | Mana: " + hero.getMp() + "/" + hero.getMaxMP() + "]");
System.out.println("[" + foe.getClass().getSimpleName() + " | HP: " + foe.getHp() + "/" + foe.getMaxHP() + "]");
System.out.println("\nChoose action:");
System.out.println("1. Light Attack (free)");
System.out.println("2. Heavy Attack (10 Mana)");
System.out.println("3. Guard (5 Mana)");
System.out.println("4. Heal yourself (15 Mana)");
System.out.println("5. " + getSpecialAbilityName() + " (20 Mana)");
System.out.println("6. Drink a Flask from bag");
int act = input.nextInt();
input.nextLine();
if (act == 1) {
hero.lightAttack(foe);
}
else if (act == 2) {
hero.heavyAttack(foe);
}
else if (act == 3) {
hero.defend();
}
else if (act == 4) {
if (hero.consumeMana(15)) {
hero.heal(20);
System.out.println(ConsoleColors.GREEN + "You recover some health." + ConsoleColors.RESET);
}
else {
System.out.println(ConsoleColors.YELLOW + "Not enough mana to heal!" + ConsoleColors.RESET);
}
}
else if (act == 5) {
hero.specialAbility(foe);
}
else if (act == 6) {
consumeFlaskInCombat();
}
else {
System.out.println("You hesitate and do nothing.");
}
if (!foe.isAlive()) {
System.out.println("Enemy defeated!");
break;
}
if (foe instanceof Enemy && ((Enemy) foe).isStunned()) {
System.out.println(foe.getClass().getSimpleName() + " is stunned and skips its turn!");
((Enemy) foe).setStunned(false);
} else {
System.out.println("\nEnemy attacks!");
foe.attack(hero);
}
if (!hero.isAlive()) {
System.out.println("You collapse...");
}
}
}
private static void rewards(Enemy foe) {
String type = foe.getClass().getSimpleName();
int xpEarned = 20 + rand.nextInt(30);
int goldEarned = 5 + rand.nextInt(15);
hero.addXp(xpEarned);
hero.addCoins(goldEarned);
System.out.println("You gain " + xpEarned + " XP and " + goldEarned + " gold coins.");
if (collectedKeys.containsKey(type) && !collectedKeys.get(type)) {
double luck = rand.nextDouble();
if (luck < 0.2) {
collectedKeys.put(type, true);
System.out.println(ConsoleColors.PURPLE + "The " + type + " dropped a mysterious key!" + ConsoleColors.RESET);
}
}
hero.heal(hero.getMaxHP());
hero.fillMana(hero.getMaxMP());
System.out.println(ConsoleColors.GREEN + "You catch your breath and are fully restored." + ConsoleColors.RESET);
}
private static void travel() {
Location current = map.get(rand.nextInt(map.size()));
Enemy foe = getRandomEnemy();
System.out.println("You travel to " + current.getName() + "...");
System.out.println("A " + foe.getClass().getSimpleName() + " appears!");
fight(foe);
if (hero.isAlive() && !foe.isAlive()) {
rewards(foe);
}
}
private static void fightDragon() {
System.out.println("You march into the Dragon's lair!");
Enemy dragon = castle.getEnemies().get(0);
fight(dragon);
if (!dragon.isAlive() && hero.isAlive()) {
System.out.println(ConsoleColors.YELLOW + "The dragon is slain! Javanest is free!" + ConsoleColors.RESET);
}
}
private static void merchant() {
System.out.println("\n--- Merchant's Stall ---");
System.out.println("Your gold: " + hero.getCoins());
System.out.println("1. Buy Iron Sword (30 gold)");
System.out.println("2. Buy Knight's Armor (50 gold)");
System.out.println("3. Buy Healing Flask (20 gold)");
System.out.println("4. Leave");
int pick = input.nextInt();
input.nextLine();
if (pick == 1) {
if (hero.getCoins() >= 30) {
hero.addItem(new Sword());
hero.addCoins(-30);
System.out.println("You bought an Iron Sword.");
}
else {
System.out.println("Not enough gold.");
}
}
else if (pick == 2) {
if (hero.getCoins() >= 50) {
hero.addItem(new KnightArmor());
hero.addCoins(-50);
System.out.println("You bought Knight's Armor.");
}
else {
System.out.println("Not enough gold.");
}
}
else if (pick == 3) {
if (hero.getCoins() >= 20) {
hero.addItem(new Flask());
hero.addCoins(-20);
System.out.println("You bought a Flask.");
}
else {
System.out.println("Not enough gold.");
}
}
else {
System.out.println("Come back anytime.");
}
}
private static void useFlaskOutsideCombat() {
for (Item it : hero.getInventory()) {
if (it instanceof Flask) {
it.use(hero);
hero.removeItem(it);
System.out.println("You drink the flask and feel better.");
return;
}
}
System.out.println("Your bag has no Flasks.");
}
private static void consumeFlaskInCombat() {
for (Item it : hero.getInventory()) {
if (it instanceof Flask) {
it.use(hero);
hero.removeItem(it);
System.out.println("You gulp a flask in the heat of battle!");
return;
}
}
System.out.println("No flask to use.");
}
}
@@ -2,20 +2,13 @@ package org.project.entity;
public interface Entity {
void attack(Entity target);
void defend();
void heal(int health);
void fillMana(int mana);
void takeDamage(int damage);
int getMaxHP();
int getMaxMP();
/*
TODO: ADD OTHER REQUIRED AND BONUS METHODS
*/
int getHp();
int getMp();
boolean isAlive();
}
@@ -0,0 +1,29 @@
package org.project.entity.enemies;
import org.project.entity.Entity;
import org.project.item.weapons.Weapon;
import org.project.ConsoleColors;
public class Dragon extends Enemy {
public Dragon() {
super(150, 50, new Weapon(25, 10, "Fiery Breath", 0) {
@Override
public void use(Entity target) {
target.takeDamage(getDamage());
}
});
}
@Override
public void attack(Entity target) {
int damage = getWeapon().getDamage();
System.out.println("🐉 Dragon used Fiery Breath! Bypasses defense!");
if (target instanceof org.project.entity.players.Player) {
org.project.entity.players.Player player = (org.project.entity.players.Player) target;
player.takeRawDamage(damage);
}
else {
target.takeDamage(damage);
}
System.out.println(ConsoleColors.RED + "Dragon dealt " + damage + " damage." + ConsoleColors.RESET);
}
}
@@ -1,34 +1,63 @@
package org.project.entity.enemies;
import org.project.entity.Entity;
import org.project.item.weapons.Weapon;
// TODO: UPDATE IMPLEMENTATION
public abstract class Enemy {
Weapon weapon;
private int hp;
private int mp;
public abstract class Enemy implements Entity {
protected Weapon weapon;
protected int hp;
protected int maxHP;
protected int mp;
protected int maxMP;
protected boolean stunned;
public Enemy(int hp, int mp, Weapon weapon) {
this.hp = hp;
this.maxHP = hp;
this.mp = mp;
this.maxMP = mp;
this.weapon = weapon;
this.stunned = false;
}
public void setStunned(boolean s) {
stunned = s;
}
public boolean isStunned() {
return stunned;
}
@Override
public void attack(Entity target) {
int damage = weapon.getDamage();
target.takeDamage(damage);
}
@Override
public void takeDamage(int damage) {
hp -= damage;
if (hp < 0) hp = 0;
}
public int getHp() {
return hp;
@Override
public void heal(int health) {
hp += health;
if (hp > maxHP) hp = maxHP;
}
public int getMp() {
return mp;
@Override
public void fillMana(int mana) {
mp += mana;
if (mp > maxMP) mp = maxMP;
}
public Weapon getWeapon() {
return weapon;
@Override
public boolean isAlive() {
return hp > 0;
}
}
@Override
public int getHp() { return hp; }
@Override
public int getMp() { return mp; }
@Override
public int getMaxHP() { return maxHP; }
@Override
public int getMaxMP() { return maxMP; }
public Weapon getWeapon() { return weapon; }
@Override
public void defend() {
}
}
@@ -0,0 +1,28 @@
package org.project.entity.enemies;
import org.project.entity.Entity;
import org.project.item.weapons.Weapon;
import org.project.ConsoleColors;
public class Goblin extends Enemy {
private double criticalChance;
public Goblin() {
super(30, 0, new Weapon(5, 0, "Claw", 0) {
@Override
public void use(Entity target) {
target.takeDamage(getDamage());
}
});
this.criticalChance = 0.4;
}
@Override
public void attack(Entity target) {
int damage = getWeapon().getDamage();
if (Math.random() < criticalChance) {
damage *= 2;
System.out.println("👹 Goblin used Critical Strike!");
}
target.takeDamage(damage);
System.out.println(ConsoleColors.RED + "Goblin dealt " + damage + " damage." + ConsoleColors.RESET);
}
}
@@ -1,6 +1,33 @@
package org.project.entity.enemies;
// TODO: UPDATE IMPLEMENTATION
public class Skeleton {
// TODO: DESIGN ENEMY AND IMPLEMENT THE CONSTRUCTOR
}
import org.project.entity.Entity;
import org.project.item.weapons.Weapon;
import org.project.ConsoleColors;
public class Skeleton extends Enemy {
private boolean hasResurrected;
public Skeleton() {
super(40, 0, new Weapon(8, 0, "Bone Sword", 0) {
@Override
public void use(Entity target) {
target.takeDamage(getDamage());
}
});
this.hasResurrected = false;
}
@Override
public void takeDamage(int damage) {
super.takeDamage(damage);
if (!isAlive() && !hasResurrected) {
hp = maxHP / 2;
hasResurrected = true;
System.out.println("☠️ Skeleton resurrected with " + hp + " HP!");
}
}
@Override
public void attack(Entity target) {
int damage = getWeapon().getDamage();
target.takeDamage(damage);
System.out.println(ConsoleColors.RED + "Skeleton dealt " + damage + " damage." + ConsoleColors.RESET);
}
}
@@ -0,0 +1,26 @@
package org.project.entity.enemies;
import org.project.entity.Entity;
import org.project.item.weapons.Weapon;
import org.project.ConsoleColors;
public class Vampire extends Enemy {
private double lifestealPercent;
public Vampire() {
super(50, 0, new Weapon(10, 0, "Dark Claw", 0) {
@Override
public void use(Entity target) {
target.takeDamage(getDamage());
}
});
this.lifestealPercent = 0.3;
}
@Override
public void attack(Entity target) {
int damage = getWeapon().getDamage();
target.takeDamage(damage);
int healed = (int)(damage * lifestealPercent);
heal(healed);
System.out.println(ConsoleColors.RED + "🦇 Vampire dealt " + damage + " damage and healed " + healed + " HP!" + ConsoleColors.RESET);
}
}
@@ -0,0 +1,85 @@
package org.project.entity.players;
import org.project.entity.Entity;
import org.project.item.armors.Armor;
import org.project.item.weapons.Weapon;
import org.project.ConsoleColors;
public class Assassin extends Player {
private boolean invisible;
private boolean guaranteedCrit;
public Assassin(String name) {
super(name, 90, 100,
new Weapon(12, 0, "Dagger", 0) {
@Override
public void use(Entity target) {
target.takeDamage(getDamage());
}
},
new Armor(5, 18, "Leather Armor", 0) {
@Override
public void use(Entity target) { }
});
this.invisible = false;
this.guaranteedCrit = false;
}
@Override
public void takeDamage(int damage) {
if (invisible) {
System.out.println(getName() + " vanishes and dodges the attack!");
invisible = false;
return;
}
super.takeDamage(damage);
}
@Override
public void lightAttack(Entity target) {
int damage = getWeapon().getDamage();
if (guaranteedCrit) {
damage *= 2;
guaranteedCrit = false;
}
target.takeDamage(damage);
System.out.println(getName() + " strikes swiftly! Dealt " + damage + " damage.");
}
@Override
public void heavyAttack(Entity target) {
if (consumeMana(10)) {
int damage = getWeapon().getDamage() * 2;
if (guaranteedCrit) {
damage *= 2;
guaranteedCrit = false;
}
target.takeDamage(damage);
System.out.println(getName() + " stabs viciously! Dealt " + damage + " damage.");
}
else {
System.out.println(ConsoleColors.YELLOW + "Not enough mana!" + ConsoleColors.RESET);
}
}
@Override
public void defend() {
if (consumeMana(5)) {
defending = true;
System.out.println(getName() + " slips into evasive stance.");
}
else {
System.out.println(ConsoleColors.YELLOW + "Not enough mana to defend!" + ConsoleColors.RESET);
}
}
@Override
public void specialAbility(Entity target) {
if (consumeMana(20)) {
invisible = true;
guaranteedCrit = true;
System.out.println(getName() + " blends into shadows... next attack will be critical and incoming attack dodged!");
}
else {
System.out.println(ConsoleColors.YELLOW + "Not enough mana for Shadow Cloak!" + ConsoleColors.RESET);
}
}
@Override
public void heal(int health) {
super.heal(health);
}
}
@@ -1,6 +1,58 @@
package org.project.entity.players;
// TODO: UPDATE IMPLEMENTATION
public class Knight {
// TODO: DESIGN KNIGHT'S WEAPON AND ARMOR AND IMPLEMENT THE CONSTRUCTOR
}
import org.project.entity.Entity;
import org.project.entity.enemies.Enemy;
import org.project.item.armors.KnightArmor;
import org.project.item.weapons.Sword;
import org.project.ConsoleColors;
public class Knight extends Player {
public Knight(String name) {
super(name, 120, 50, new Sword(), new KnightArmor());
}
@Override
public void lightAttack(Entity target) {
int damage = getWeapon().getDamage();
target.takeDamage(damage);
System.out.println(getName() + " used Light Attack! Dealt " + damage + " damage.");
}
@Override
public void heavyAttack(Entity target) {
if (consumeMana(10)) {
int damage = getWeapon().getDamage() * 2;
target.takeDamage(damage);
System.out.println(getName() + " used Heavy Attack! Dealt " + damage + " damage.");
}
else {
System.out.println(ConsoleColors.YELLOW + "Not enough mana!" + ConsoleColors.RESET);
}
}
@Override
public void defend() {
if (consumeMana(5)) {
defending = true;
System.out.println(getName() + " is defending!");
}
else {
System.out.println(ConsoleColors.YELLOW + "Not enough mana to defend!" + ConsoleColors.RESET);
}
}
@Override
public void heal(int health) {
super.heal(health);
}
@Override
public void specialAbility(Entity target) {
if (consumeMana(20)) {
int damage = getWeapon().getDamage() * 3;
target.takeDamage(damage);
if (target instanceof Enemy) {
((Enemy) target).setStunned(true);
}
System.out.println(getName() + " used Shield Bash! Dealt " + damage + " damage and stunned the enemy.");
}
else {
System.out.println(ConsoleColors.YELLOW + "Not enough mana for Shield Bash!" + ConsoleColors.RESET);
}
}
}
@@ -1,89 +1,159 @@
package org.project.entity.players;
import org.project.entity.Entity;
import org.project.item.Item;
import org.project.item.armors.Armor;
import org.project.item.weapons.Weapon;
import java.util.ArrayList;
import java.util.List;
import org.project.ConsoleColors;
// TODO: UPDATE IMPLEMENTATION
public abstract class Player {
public abstract class Player implements Entity {
protected String name;
Weapon weapon;
Armor armor;
private int hp;
private int maxHP;
private int mp;
private int maxMP;
protected Weapon weapon;
protected Armor armor;
protected int hp;
protected int maxHP;
protected int mp;
protected int maxMP;
protected List<Item> inventory;
protected int coins;
protected int xp;
protected int level;
protected boolean defending;
public Player(String name, int hp, int mp, Weapon weapon, Armor armor) {
this.name = name;
this.hp = hp;
this.maxHP = hp;
this.mp = mp;
this.maxMP = mp;
this.weapon = weapon;
this.armor = armor;
this.inventory = new ArrayList<>();
this.coins = 0;
this.xp = 0;
this.level = 1;
this.defending = false;
}
public void takeRawDamage(int damage) {
hp -= damage;
if (hp < 0) hp = 0;
}
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
public void setArmor(Armor armor) {
this.armor = armor;
}
@Override
public void attack(Entity target) {
target.takeDamage(weapon.getDamage());
int damage = weapon.getDamage();
target.takeDamage(damage);
}
@Override
public void defend() {
// TODO
}
@Override
public void takeDamage(int damage) {
hp -= damage - armor.getDefense();
int defense = armor.isBroke() ? 0 : armor.getDefense();
int actualDamage = Math.max(damage - defense, 0);
if (defending) {
actualDamage = 0;
defending = false;
}
hp -= actualDamage;
if (hp < 0) hp = 0;
if (!armor.isBroke()) {
armor.reduceDurability(1);
}
}
@Override
public void heal(int health) {
hp += health;
if (hp > maxHP) {
hp = maxHP;
}
if (hp > maxHP) hp = maxHP;
}
@Override
public void fillMana(int mana) {
mp += mana;
if (mp > maxMP) {
mp = maxMP;
}
if (mp > maxMP) mp = maxMP;
}
public String getName() {
return name;
@Override
public boolean isAlive() {
return hp > 0;
}
@Override
public int getHp() {
return hp;
}
@Override
public int getMp() {
return mp;
}
@Override
public int getMaxHP() {
return maxHP;
}
public int getMp() {
return mp;
}
@Override
public int getMaxMP() {
return maxMP;
}
public abstract void lightAttack(Entity target);
public abstract void heavyAttack(Entity target);
@Override
public abstract void defend();
public abstract void specialAbility(Entity target);
public boolean consumeMana(int cost) {
if (mp >= cost) {
mp -= cost;
return true;
}
return false;
}
public void addItem(Item item) {
inventory.add(item);
}
public void removeItem(Item item) {
inventory.remove(item);
}
public List<Item> getInventory() {
return inventory;
}
public void addCoins(int amount) {
coins += amount;
}
public int getCoins() {
return coins;
}
public void addXp(int amount) {
xp += amount;
checkLevelUp();
}
private void checkLevelUp() {
int xpNeeded = level * 50;
while (xp >= xpNeeded) {
xp -= xpNeeded;
level++;
maxHP += 20;
maxMP += 10;
hp = maxHP;
mp = maxMP;
System.out.println(ConsoleColors.YELLOW + name + " leveled up to Level " + level + "!" + ConsoleColors.RESET);
xpNeeded = level * 50;
}
}
public int getXp() {
return xp;
}
public int getLevel() {
return level;
}
public String getName() {
return name;
}
public Weapon getWeapon() {
return weapon;
}
public Armor getArmor() {
return armor;
}
}
}
@@ -0,0 +1,65 @@
package org.project.entity.players;
import org.project.entity.Entity;
import org.project.item.armors.Armor;
import org.project.item.weapons.Weapon;
import org.project.ConsoleColors;
public class Wizard extends Player {
public Wizard(String name) {
super(name, 150, 80,
new Weapon(8, 0, "Staff", 0) {
@Override
public void use(Entity target) {
target.takeDamage(getDamage());
}
},
new Armor(3, 15, "Wizard Robe", 0) {
@Override
public void use(Entity target) { }
});
}
@Override
public void lightAttack(Entity target) {
int damage = getWeapon().getDamage();
target.takeDamage(damage);
System.out.println(getName() + " casts Light Bolt! Dealt " + damage + " damage.");
}
@Override
public void heavyAttack(Entity target) {
if (consumeMana(10)) {
int damage = getWeapon().getDamage() * 2;
target.takeDamage(damage);
System.out.println(getName() + " casts Fireball! Dealt " + damage + " damage.");
}
else {
System.out.println(ConsoleColors.YELLOW + "Not enough mana!" + ConsoleColors.RESET);
}
}
@Override
public void defend() {
if (consumeMana(5)) {
defending = true;
System.out.println(getName() + " raises a magic barrier!");
}
else {
System.out.println(ConsoleColors.YELLOW + "Not enough mana to defend!" + ConsoleColors.RESET);
}
}
@Override
public void heal(int health) {
super.heal(health);
}
@Override
public void specialAbility(Entity target) {
if (consumeMana(20)) {
int damage = getWeapon().getDamage() * 3;
target.takeDamage(damage);
heal(30);
System.out.println(getName() + " unleashes Arcane Blast! Dealt " + damage + " damage and recovered 30 HP.");
}
else {
System.out.println(ConsoleColors.YELLOW + "Not enough mana for Arcane Blast!" + ConsoleColors.RESET);
}
}
}
@@ -4,8 +4,6 @@ import org.project.entity.Entity;
public interface Item {
void use(Entity target);
/*
TODO: ADD OTHER REQUIRED AND BONUS METHODS
*/
String getName();
int getPrice();
}
@@ -1,42 +1,60 @@
package org.project.item.armors;
// TODO: UPDATE IMPLEMENTATION
public abstract class Armor {
import org.project.item.Item;
public abstract class Armor implements Item {
private int defense;
private int maxDefense;
private int durability;
private int maxDurability;
private String name;
private int price;
private boolean isBroke;
public Armor(int defense, int durability) {
public Armor(int defense, int durability, String name, int price) {
this.defense = defense;
this.maxDefense = defense;
this.durability = durability;
this.maxDurability = durability;
this.isBroke = false;
this.name = name;
this.price = price;
}
public void reduceDurability(int amount) {
if (!isBroke) {
durability -= amount;
checkBreak();
}
}
public void checkBreak() {
if (durability <= 0) {
isBroke = true;
defense = 0;
durability = 0;
}
}
// TODO: (BONUS) UPDATE THE REPAIR METHOD
public void repair() {
isBroke = false;
defense = maxDefense;
durability = maxDurability;
}
public int getDefense() {
return defense;
}
public int getDurability() {
return durability;
}
public boolean isBroke() {
return isBroke;
}
@Override
public String getName() {
return name;
}
@Override
public int getPrice() {
return price;
}
}
@@ -1,6 +1,12 @@
package org.project.item.armors;
// TODO: UPDATE IMPLEMENTATION
public class KnightArmor {
// TODO: DESIGN ARMOR'S ATTRIBUTES IMPLEMENT THE CONSTRUCTOR
import org.project.entity.Entity;
public class KnightArmor extends Armor {
public KnightArmor() {
super(10, 20, "Knight Armor", 50);
}
@Override
public void use(Entity target) {
}
}
@@ -1,8 +1,20 @@
package org.project.item.consumables;
// TODO: UPDATE IMPLEMENTATION
public abstract class Consumable {
/*
TODO: ADD OTHER REQUIRED AND BONUS METHODS
*/
}
import org.project.item.Item;
public abstract class Consumable implements Item {
private String name;
private int price;
public Consumable(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public String getName() {
return name;
}
@Override
public int getPrice() {
return price;
}
}
@@ -1,16 +1,22 @@
package org.project.item.consumables;
import org.project.entity.Entity;
import org.project.entity.players.Player;
// TODO: UPDATE IMPLEMENTATION
public class Flask {
/*
THIS IS AN EXAMPLE OF A CONSUMABLE DESIGN.
*/
public class Flask extends Consumable {
// TODO: UPDATE USE METHOD
public Flask() {
super("Flask", 20);
}
@Override
public void use(Entity target) {
target.heal(target.getMaxHP() / 10);
int healAmount = target.getMaxHP() / 10;
target.heal(healAmount);
if (target instanceof Player) {
System.out.println(((Player) target).getName() + " used Flask and restored " + healAmount + " HP.");
}
else {
System.out.println(target.getClass().getSimpleName() + " used Flask and restored " + healAmount + " HP.");
}
}
}
}
@@ -1,26 +1,24 @@
package org.project.item.weapons;
import org.project.entity.Entity;
import java.util.ArrayList;
// TODO: UPDATE IMPLEMENTATION
public class Sword {
/*
THIS IS AN EXAMPLE OF A WEAPON DESIGN.
*/
int abilityCharge;
public class Sword extends Weapon {
private int abilityCharge;
public Sword() {
// TODO: DESIGN SWORD'S ATTRIBUTES IMPLEMENT THE CONSTRUCTOR
super(15, 0, "Sword", 30);
this.abilityCharge = 0;
}
// TODO: (BONUS) UPDATE THE UNIQUE ABILITY
public void uniqueAbility(ArrayList<Entity> targets) {
abilityCharge += 2;
for (Entity target : targets) {
target.takeDamage(getDamage());
}
}
}
public int getAbilityCharge() {
return abilityCharge;
}
}
@@ -1,19 +1,20 @@
package org.project.item.weapons;
import org.project.entity.Entity;
import org.project.item.Item;
// TODO: UPDATE IMPLEMENTATION
public abstract class Weapon {
public abstract class Weapon implements Item {
private int damage;
private int manaCost;
private String name;
private int price;
/*
TODO: ADD OTHER REQUIRED AND BONUS ATTRIBUTES
*/
public Weapon(int damage, int manaCost) {
public Weapon(int damage, int manaCost, String name, int price) {
this.damage = damage;
this.manaCost = manaCost;
this.name = name;
this.price = price;
}
@Override
@@ -28,8 +29,13 @@ public abstract class Weapon {
public int getManaCost() {
return manaCost;
}
@Override
public String getName() {
return name;
}
/*
TODO: ADD OTHER REQUIRED AND BONUS METHODS
*/
@Override
public int getPrice() {
return price;
}
}
@@ -1,28 +1,24 @@
package org.project.location;
import org.project.entity.enemies.Enemy;
import java.util.ArrayList;
import java.util.List;
public class Location {
private String name;
private List<Enemy> enemies;
private ArrayList<Enemy> enemies;
public Location(ArrayList<Location> locations, ArrayList<Enemy> enemies) {
this.locations = locations;
this.enemies = enemies;
public Location(String name) {
this.name = name;
this.enemies = new ArrayList<>();
}
public void addEnemy(Enemy enemy) {
enemies.add(enemy);
}
public String getName() {
return name;
}
public ArrayList<Location> getLocations() {
return locations;
}
public ArrayList<Enemy> getEnemies() {
public List<Enemy> getEnemies() {
return enemies;
}
}
}
Binary file not shown.
+113 -157
View File
@@ -1,175 +1,131 @@
# Fourth Assignment - Java Knight ⚔️
A turn-based RPG with Roguelike elements which can be run in the terminal.
```markdown
# Java Knight ⚔️ A Turn-Based Roguelike RPG
### **Prologue: The Legend of Javanest**
*For centuries, the land of Javanest lived in peace, until a magical Dragon attacked, plunging the realm into absolute darkness. With a wicked curse, the Dragon transformed the innocent people into horrific monsters: Goblins, Skeletons, and Vampires. Retreating to its impenetrable Castle, the Dragon divided the three keys to its lair and hid them among these cursed creatures. Now, it is your duty to step up and save the land. You must battle these monsters, recover the unique key from each monster type, and finally slay the Dragon to break the curse and restore peace to Javanest!*
### **Introduction**
Welcome to **Java knight**, a turn-based RPG inspired by Roguelike games! In this assignment, you will develop a **text-based role-playing game (RPG)**. This project is designed to rigorously test your understanding of **Object-Oriented Programming (OOP) principles**.
⚠️ **REQUIREMENT:** You **must** utilize all the OOP concepts you have learned so far—including *Inheritance, Interfaces, Abstract Classes, Encapsulation, Polymorphism, Overloading, and Overriding*. It is extremely important that you use everything in its right place. Your design and architecture will be graded based on how well you apply these principles to avoid code duplication and maintain a clean structure.
🎯 **Your goal is not just to complete the assignment but to learn and apply OOP effectively!**
### **What is a Turn-Based Game?**
In this combat system, two sides - which are usually the player's side and the enemy's side - attack each other in turns. The side which is not attacking can perform actions to avoid or deflect the enemy's attack.
### **Core Mechanics:**
- **Turn-based combat** Players and monsters take turns attacking each other.
- **Character classes with Unique Traits** Players can choose from archetypes like **Knight, Assassin, or Wizard**, each starting with distinctly different base stats.
- **Unified Mana/Stamina System** All player classes use a unified resource (Mana/Stamina) to perform actions.
- **Standardized Action Set** Every player character has exactly 5 specific actions available during their turn.
- **Experience & Leveling System** Earn XP based on enemy strength to automatically level up and increase your base stats.
- **Progression System** You cannot fight the Dragon immediately. You must farm enemies for a chance to drop their specific key, collect all three, and grow stronger first.
A text-based role-playing game developed in Java, focusing on **Object-Oriented Programming** principles.
---
## Tasks 📝
## 📖 Game Introduction
*For centuries, the land of Javanest lived in peace, until a magical Dragon attacked, plunging the realm into darkness. The Dragon transformed innocent people into monsters and hid the three keys to its lair among them. You must battle these creatures, collect the keys, and defeat the Dragon to save the land.*
### 1️⃣ Step 1: Fork & Setup 🍴
1. **Fork** this repository and clone it to your local machine.
```bash
git clone https://git.meshcomp.ir/AdvancedProgramming1404/HW-04-JAVA-KNIGHT.git
```
2. Create a new branch named `develop` and switch to it.
```bash
git checkout -b develop
```
### 2️⃣ Step 2: Implement the Class Hierarchy 🌲
A well-structured OOP hierarchy is crucial. Avoid duplicating code by placing shared logic in abstract classes.
- **Entities & Locations:** You have `Entity`, `Item`(Bonus) , and `Location`.
- **Players:** `Player` is an abstract class implementing `Entity`. Subclasses: `Wizard`, `Knight`, `Assassin`.
- **Base Stat Differences:** Each class must have distinct starting stats. For example:
- **Knight:** Highest Base Damage.
- **Wizard:** Highest Max Health (HP).
- **Assassin:** Highest Max Stamina/Mana.
- **Enemies:** `Enemy` is an abstract class implementing `Entity`. Subclasses: `Skeleton`, `Goblin`, `Vampire`, and **`Dragon`**.
- **The Boss:** Even though `Dragon` is the final boss, it **must** be a subclass of `Enemy` to inherit common combat properties, while possessing extremely high stats and unique mechanics.
- **Item (Bonus):** `Consumable`, `Armor`, `Weapon` are abstract classes implementing `Item`. example :
- KnightArmor extends Armor - you can add more subclasses of Armor for extra score
- Sword extends Weapon - you can add more subclasses of Weapon for extra score
- Flask extends Consumable - you can add more subclasses of Consumable for extra score
![structure](Readme_Pictures/structure.png)
### 3️⃣ Step 3: Implement Player & Monster Methods 🏹
**Player Actions (The Rule of Five):**
Every player class **must** implement exactly the following 5 actions (You can use an interface like `ICombatActions`). Every action (except Light Attack) consumes a specific amount of Mana/Stamina. The **Special Ability** must consume the *highest* amount of Mana compared to the others.
1. **Light Attack:** Deals moderate damage and costs **NO Mana**. (Note: If the player runs out of Mana/Stamina, this is the ONLY action they can perform.)
2. **Heavy Attack:** Deals high damage, medium Mana cost.
3. **Defend:** Completely blocks or significantly reduces the damage of the enemy's *next* strike. Medium Mana cost.
4. **Heal:** Restores a portion of the player's HP. Medium-high Mana cost.
5. **Special Ability:** A unique class-based ultimate move (Highest Mana cost):
- **Wizard** 🧙‍♂️: Casts a devastating spell that damages the enemy while simultaneously replenishing some HP.
- **Assassin** 🗡️: Turns invisible, dodging the next incoming attack completely and guaranteeing a *Critical Hit* on their next turn.
- **Knight** ⚔️: Performs a shield bash that stuns the enemy, forcing them to skip their next turn while dealing heavy damage.
**Monster Abilities:**
- **Goblin** 👹: High critical hit chance but low health.
- **Skeleton** ☠️: Can resurrect once per battle with 50% HP.
- **Vampire** 🦇: Lifesteal ability a portion of the damage it deals to the player is added back to its own health.
- **Dragon (Final Boss)** 🐉: Immune to normal defense. Its fiery breath bypasses shields and deals massive damage.
🔹 Make sure each entity **prints messages** when performing actions. example output (while in combat) :
```bash
You chose to FIGHT!
[Ser Duncan - 45/45 HP | 40/40 Mana]
[Goblin - 30/30 HP]
In **Java Knight**, you choose one of three character classes, fight cursed enemies in turn-based combat, manage mana and equipment, and progress until you can face the final boss.
---
Your Turn:
1. Light Attack | 2. Heavy Attack (-8 Mana) | 3. Defend (-6 Mana) | 4. Heal (-12 Mana) | 5. Shield Bash (-15 Mana)
```
## 🚀 How to Compile & Run
```bash
→ Chose: Light Attack
⚔️ Ser Duncan (Knight) used Light Attack! (0 Mana)
Goblin took 10 damage!
Goblin has 20/30 HP remaining.
Ser Duncan Mana: 40/40
```
```
Goblin's Turn :
👹 Goblin used Critical Strike!
💥 Critical hit! Ser Duncan took 20 damage!
Ser Duncan has 25/45 HP remaining.
```
🔹 *Narrative Console:* Use ANSI escape codes to print colorful narrative logs (e.g., Red for damage, Blue for Mana usage, Green for healing).
### Requirements
- Java JDK 8 or higher
- IntelliJ IDEA (or any Java IDE)
### Execution (using IntelliJ IDEA)
1. Open the project folder (`Java-Knight`) in IntelliJ IDEA.
2. Wait for the IDE to index and import the Maven project.
3. Navigate to `src/main/java/org/project/Main.java`.
4. Right-click on `Main.java` and select **Run 'Main.main()'**.
### 4️⃣ Step 4: Implement the Game Loop & Progression 🎮
1. **The Core Loop:** The game starts with the player entering a location. A random standard enemy (`Goblin`, `Skeleton`, or `Vampire`) spawns immediately.
2. **Player Choices:** Before engaging, the player is presented with the following options:
- **1. Fight the enemy:** Enter the turn-based combat sequence.
- **2. Move to another location:** Skip the current enemy and spawn a new random one.
- **3. Go to the Castle to fight the Dragon:** *(Note: This option must remain strictly hidden or locked until the player has successfully collected all 3 keys).*
3. **The Key Drop Logic (RNG Gatekeeping):**
- When the player defeats an enemy, there is a **specific percentage chance (e.g., 20%)** that it will drop the unique key associated with its species (Goblin Key, Skeleton Key, Vampire Key).
- **One Key Per Species:** Once a player obtains a specific key (e.g., Goblin Key), subsequent enemies of that same type (other Goblins) will **never** drop a key again.
- The player **must collect all 3 distinct keys** to unlock Option 3 and enter the Castle.
4. **Post-Combat Recovery:** After each successful battle, the player's HP and Mana bars must automatically replenish (either fully or partially) to their base amounts so they are ready for the next encounter.
5. **Experience & Leveling System:**
- Defeating an enemy grants **XP**. The amount of XP must scale proportionally to the enemy's power level.
- Upon reaching an XP threshold, the player levels up. **Leveling up must automatically increase the player's Max HP and Max Stamina/Mana**, making them strong enough to eventually face the Dragon.
6. **Final Boss Fight:** Once the 3 Keys are obtained and the player chooses to go to the Castle, they will face the Dragon. Defeating the Dragon breaks the curse, resulting in **Victory**. Dying at any point results in **Game Over**.
🔹 Example game loop structure:
```java
while (player.isAlive() && enemy.isAlive())
player.attack(enemy);
if (enemy.isAlive()) {
enemy.attack(player);
}
}
```
### 5️⃣ Step 5: Extra Features & Bonus Tasks ⭐
*(Optional for extra credit)*
**Dynamic Economy & Merchant System:** Implement coins that drop from enemies. Add a "Visit Merchant" option to the main loop where players can spend coins to buy specific weapons, armors, or consumables.
**Multiple Weapons & Inventory:** Players can buy, store, and swap between multiple weapons or use consumables mid-combat.
**Multiplayer/Party Mode:** Allow multiple players to team up and fight multiple enemies together. The Dragon's breath attack will damage the entire party simultaneously.
**PvP Mode:** Implement a **Player vs. Player** combat system.
### 6️⃣ Step 6: Write a Comprehensive README 📄
As the final mandatory step of your development, you must replace the default `README.md` with your own comprehensive documentation. Your README should include:
- A brief introduction to the game.
- How to compile and run your project from the terminal.
- An explanation of the classes, design patterns, and OOP principles you used.
- A brief guide on how to play (controls, stats, classes).
The game will start directly in the terminal window of the IDE.
---
## Evaluation Criteria ⚖
## 🧱 Class Structure & OOP Design
| **Criteria** | **Points** |
|-------------------------------------------------------------|------------|
| Proper use of OOP principles | **50** |
| Working combat mechanics, Leveling System & Enemy abilities | **20** |
| Clear and Comprehensive `README.md` | **20** |
| Code readability, documentation, and comments | **10** |
| Meaningful, interactive, & colored console outputs | **10** |
| Inventory (item) and Merchant System (bonus) | **20** |
| Other Extra features (bonus tasks) | **20** |
| **Total Score** | **150** |
The project strictly follows **Object-Oriented Programming** principles.
## Tips 🚀
- **Follow OOP principles**: Avoid redundant code by using inheritance properly. Think carefully about what belongs in an abstract class vs. a specific subclass. Make sure you use overriding and overloading correctly.
- **Test your code**: Run different scenarios (fighting, running out of mana, leveling up, dying) to ensure everything works as expected.
- **Ask for help**: If you're stuck, reach out to your classmates or mentors.
### Core Interfaces & Abstract Classes
- **`Entity`** Interface for any participant in combat. Declares methods like `attack()`, `defend()`, `heal()`, `takeDamage()`, `getHp()`, `getMp()`.
- **`Item`** Interface for all objects that can be used. Provides `use()`, `getName()`, `getPrice()`.
## Submission ⌛
- **Deadline**: Submit your assignment before **21 Ordibehesht (May 11th, 2026)**.
- **Submission Format**: Push your code to your forked repository, create a PR, and ensure your comprehensive `README.md` is included in the root directory.
### Players
- **`Player`** (abstract) Implements `Entity`. Contains all common fields (health, mana, max stats), inventory, coins, experience points, and leveling logic. Defines abstract methods for the five mandatory actions.
- **`Knight`** High base damage, strong armor. Special ability: **Shield Bash** (stuns enemy for one turn).
- **`Wizard`** Highest health. Special ability: **Arcane Blast** (heavy damage + self heal).
- **`Assassin`** Highest mana. Special ability: **Shadow Cloak** (dodges next attack and guarantees a critical hit next turn).
![cover](Readme_Pictures/image.png)
###### - Born of God and Void. You shall seal the blinding light that plagues their dreams. You are the Vessel. You are the Java Knight.
### Enemies
- **`Enemy`** (abstract) Implements `Entity`. Holds common properties and the stun state.
- **`Goblin`** High critical hit chance (40%).
- **`Skeleton`** Resurrects once per battle with 50% HP.
- **`Vampire`** Lifesteal (30% of damage dealt).
- **`Dragon`** Final boss, breath attack bypasses defense.
### Items (for bonuses: Merchant/Inventory)
- **`Weapon`** (abstract) `Sword`, `Dagger`, etc.
- **`Armor`** (abstract) `KnightArmor`, `LeatherArmor`. Has durability and can break; can be repaired.
- **`Consumable`** (abstract) `Flask` restores 10% of max HP.
### Key OOP Concepts Used
| Concept | Example |
|------------------|-------------------------------------------------------------------------|
| Inheritance | `Knight``Player``Entity` |
| Interface | `Item` implemented by `Weapon`, `Armor`, `Consumable` |
| Abstract classes | `Player`, `Enemy`, `Weapon`, `Armor` |
| Polymorphism | `entity.attack(target)` works on any `Entity` subclass |
| Encapsulation | All fields are private; access only via getters/setters |
| Method overriding| `specialAbility()`, `attack()`, `takeDamage()` overridden in subclasses |
---
## 🎮 How to Play
### Starting the Game
- Run the program. You will be asked to **choose a class**:
- `1` Knight (high damage)
- `2` Wizard (high HP)
- `3` Assassin (high mana)
- A random location is selected, and an enemy appears.
### Main Menu
After each encounter, you can:
1. **Hunt for enemies** Fight a random enemy in the current area.
2. **Travel to another place** Move to a different location and encounter a new enemy.
3. **Visit Merchant** Buy weapons, armor, or flasks using collected gold.
4. **Use a Flask from bag** Consume a healing item from your inventory (if you have any).
5. **Quit game**
### Combat (Turn-Based)
Each turn, you can choose one of **six actions**:
1. **Light Attack** Free, moderate damage.
2. **Heavy Attack** Costs 10 Mana, high damage.
3. **Guard** Costs 5 Mana, completely blocks the next enemy attack.
4. **Heal** Costs 15 Mana, restores 20 HP.
5. **Special Ability** Costs 20 Mana, unique effect per class.
6. **Drink a Flask** Use a healing item from inventory (if purchased from merchant).
After your action, if the enemy is alive, it attacks you (unless stunned by Knight's Shield Bash).
### Progression
- Defeating enemies earns **XP** and **gold**.
- When XP reaches a threshold (Level × 50), you **level up**, increasing Max HP and Max Mana.
- After every victorious battle, HP and Mana are fully restored.
- Each enemy type has a **20% chance** to drop its unique key. Once a key is obtained, that enemy type will never drop another key.
- **Collect all three keys** (Goblin, Skeleton, Vampire) to unlock the option to enter the Dragon's Castle.
- Defeat the Dragon to **win the game**. Dying at any point results in **Game Over**.
### Merchant & Inventory (Bonus Features)
- Gold earned from enemies can be spent at the **Merchant** (option 3 in main menu).
- You can purchase:
- **Iron Sword** (30 gold)
- **Knight's Armor** (50 gold)
- **Healing Flask** (20 gold)
- Items go into your **inventory** and can be used in or out of combat.
- Flasks are consumed upon use.
---
## 🎨 Console Output & Colors
The game uses **ANSI escape codes** for colorful messages:
- 🔴 **Red** damage taken
- 🟢 **Green** healing
- 🟡 **Yellow** warnings (low mana, level up)
- 🟣 **Purple** special events (key drops)
---
## 🌟 Bonus Implemented Features
- Dynamic economy with **merchant system** and **gold**
- **Inventory** management (buy, store, and use items)
- Three distinct character classes with unique abilities
- Advanced combat mechanics (armor breaking, enemy resurrection, lifesteal, stun)
- Full turn-based game loop with enemy spawn, key collection, and final boss
```