Compare commits

10 Commits
Author SHA1 Message Date
HadiSharifi 5fa039ceff add README 2026-05-11 13:08:48 +03:30
HadiSharifi ed48aaf7d9 implement repairKit in Game class 2026-05-11 12:49:36 +03:30
HadiSharifi c80c0425b1 add repairKit class 2026-05-11 12:29:43 +03:30
HadiSharifi 24175b68bf fix bugs 2026-05-11 12:04:39 +03:30
HadiSharifi 01b8c225d9 fix bugs and add status prints 2026-05-10 22:15:11 +03:30
HadiSharifi 0992256cfe fix bugs and add status prints 2026-05-10 21:47:31 +03:30
HadiSharifi 1060cd0ff7 implement Game class 2026-05-10 20:26:56 +03:30
HadiSharifi 82e4908dcf implement xp/level logic 2026-05-10 12:29:07 +03:30
HadiSharifi 8c8cb94763 implement xp/level logic 2026-05-10 12:18:32 +03:30
HadiSharifi 7c60722ff2 implement Dragon class 2026-05-10 11:57:40 +03:30
37 changed files with 563 additions and 389 deletions
@@ -0,0 +1,239 @@
package org.project;
import org.project.entity.enemies.*;
import org.project.entity.players.Assassin;
import org.project.entity.players.Knight;
import org.project.entity.players.Player;
import org.project.entity.players.Wizard;
import org.project.item.consumables.repairKit;
import org.project.location.Location;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Game {
private final ArrayList<Player> players;
private final ArrayList<Enemy> regularEnemies;
private final ArrayList<Location> locations;
private final Scanner sc;
private Player player;
private final List<String> collectedKeyTypes = new ArrayList<>();
public Game() {
sc = new Scanner(System.in);
players = new ArrayList<>();
players.add(new Assassin());
players.add(new Knight());
players.add(new Wizard());
regularEnemies = new ArrayList<>();
regularEnemies.add(new Goblin());
regularEnemies.add(new Skeleton());
regularEnemies.add(new Vampire());
locations = new ArrayList<>();
locations.add(new Location("Jungle", regularEnemies));
locations.add(new Location("China", new ArrayList<>(regularEnemies.subList(0, 2))));
locations.add(new Location("Iran", new ArrayList<>(regularEnemies.subList(1, 3))));
}
public void start() {
player = choosePlayer();
while (true) {
displayKeys();
Location location = chooseLocation();
Enemy enemy = chooseEnemy(location);
System.out.println("Wanna fight?\n1. Yes\n2. No");
int choice = sc.nextInt();
if (choice != 1) continue;
combat(player, enemy);
System.out.println("Player HP: " + player.getHP());
if (!player.isAlive()) {
System.out.println("Game over.");
break;
}
if (canChallengeDragon()) {
System.out.println("\nYou have collected all keys! The Dragon awaits...");
System.out.println("Challenge the Dragon?\n1. Yes\n2. No");
if (sc.nextInt() == 1) {
challengeDragon();
break;
}
}
}
}
private boolean canChallengeDragon() {
for (Enemy enemy : regularEnemies) {
if (!player.hasKey(enemy)) return false;
}
return true;
}
private void challengeDragon() {
Dragon dragon = new Dragon();
combat(player, dragon);
if (player.isAlive()) {
System.out.println("Congratulations! You defeated the Dragon and completed the game!");
} else {
System.out.println("The Dragon was too powerful. Better luck next time.");
}
}
private Player choosePlayer() {
System.out.print("1. Assassin\n2. Knight\n3. Wizard\nChoose your character: ");
int choice = sc.nextInt();
Player chosen = switch (choice) {
case 1 -> players.get(0);
case 2 -> players.get(1);
default -> players.get(2);
};
System.out.println("You chose " + chosen.getName()
+ " (" + chosen.getClass().getSimpleName() + ")");
return chosen;
}
private void displayKeys() {
System.out.println("=".repeat(30));
System.out.print("Keys collected: ");
for (Enemy enemy : regularEnemies) {
if (player.hasKey(enemy) && !collectedKeyTypes.contains(enemy.getClass().getSimpleName()))
collectedKeyTypes.add(enemy.getClass().getSimpleName());
}
if (collectedKeyTypes.isEmpty()) {
System.out.println("none");
} else {
System.out.println(String.join(", ", collectedKeyTypes));
}
System.out.println("=".repeat(30));
}
private void displayLocations() {
for (Location location : locations) {
System.out.println(location);
}
}
private Location chooseLocation() {
displayLocations();
System.out.print("1. Jungle\n2. China\n3. Iran\nChoose location: ");
int choice = sc.nextInt();
Location location = switch (choice) {
case 1 -> locations.get(0);
case 2 -> locations.get(1);
default -> locations.get(2);
};
System.out.println("You chose " + location.getName());
return location;
}
private Enemy chooseEnemy(Location location) {
int index = new Random().nextInt(location.getEnemies().size());
Enemy enemy = location.getEnemies().get(index);
if (enemy instanceof Vampire) {
enemy = new Vampire();
}
if (enemy instanceof Goblin) {
enemy = new Goblin();
}
if (enemy instanceof Skeleton) {
enemy = new Skeleton();
}
System.out.println("The enemy is: " + enemy.getClass().getSimpleName());
return enemy;
}
private void combat(Player player, Enemy enemy) {
int turn = 0;
while (player.isAlive() && enemy.isAlive()) {
if (turn == 0) {
System.out.println("Choose your action:");
System.out.println("1. Light attack 2. Heavy attack 3. Defend" +
" 4. Heal 5. Special ability 6. Flask 7.Repair Kit");
int choice = sc.nextInt();
boolean actionTaken = handlePlayerAction(choice, enemy);
if (!actionTaken) continue;
turn = 1;
printCombatStatus(enemy);
if (!enemy.isAlive()) break;
}
else {
System.out.println("-".repeat(30));
if (player instanceof Assassin && player.getUsingSpecialAbility()) {
System.out.println(enemy.getClass().getSimpleName() + " skipped its turn!");
turn = 0;
continue;
}
System.out.println(enemy.getClass().getSimpleName() + "'s turn:");
boolean enemyActed = handleEnemyAction(enemy);
if (!enemyActed) continue;
turn = 0;
printCombatStatus(enemy);
if (!player.isAlive()) break;
}
}
if (!player.isAlive()) {
System.out.println("You lost!");
} else {
System.out.println("You won!");
player.gainXP(Player.xpRewardFor(enemy));
player.setHP(player.getMaxHP());
player.setMP(player.getMaxMP());
if (!(enemy instanceof Dragon) && enemy.dropKey()) {
System.out.println(enemy.getClass().getSimpleName() + "'s key dropped!");
player.achieveKey(enemy);
}
}
}
private boolean handlePlayerAction(int choice, Enemy enemy) {
switch (choice) {
case 1 -> { player.lightAttack(enemy); return true; }
case 2 -> { player.heavyAttack(enemy); return player.isSuccessfulAction();}
case 3 -> { player.defend(); return player.isSuccessfulAction(); }
case 4 -> { player.heal(10); return player.isSuccessfulAction(); }
case 5 -> { player.specialAbility(enemy); return player.isSuccessfulAction(); }
case 6 -> { player.getFlask().use(player); return true; }
case 7 -> {new repairKit().use(player); return true;}
default -> { System.out.println("Invalid choice."); return false; }
}
}
private boolean handleEnemyAction(Enemy enemy) {
int choice = new Random().nextInt(3);
switch (choice) {
case 1 -> { enemy.defend(); return enemy.isSuccessfulAction(); }
case 2 -> { enemy.heal(10); return enemy.isSuccessfulAction(); }
}
enemy.attack(player);
return true;
}
private void printCombatStatus(Enemy enemy) {
System.out.println("[" + player.getClass().getSimpleName() + " - " + player.getHP() + "/" + player.getMaxHP() +
" HP | " + player.getMP() + "/" + player.getMaxMP() + " MP]");
System.out.println("[" + enemy.getClass().getSimpleName() + " - " + enemy.getHP() + "/" + enemy.getMaxHP() +
" HP | " + enemy.getMP() + "/" + enemy.getMaxMP() + "MP]");
}
}
+2 -185
View File
@@ -1,190 +1,7 @@
package org.project;
import org.project.entity.enemies.Enemy;
import org.project.entity.enemies.Goblin;
import org.project.entity.enemies.Skeleton;
import org.project.entity.enemies.Vampire;
import org.project.entity.players.Assassin;
import org.project.entity.players.Knight;
import org.project.entity.players.Player;
import org.project.entity.players.Wizard;
import org.project.item.weapons.Sword;
import org.project.item.weapons.Weapon;
import org.project.location.Location;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Weapon wp = new Sword();
ArrayList<Player> players = new ArrayList<>();
players.add(new Assassin());
players.add(new Knight());
players.add(new Wizard());
ArrayList<Enemy> enemies = new ArrayList<>();
enemies.add(new Goblin());
enemies.add(new Skeleton());
enemies.add(new Vampire());
ArrayList<Location> locations = new ArrayList<>();
locations.add(new Location("Jungle", enemies));
locations.add(new Location("China", new ArrayList<>(enemies.subList(0, 2))));
locations.add(new Location("Iran", new ArrayList<>(enemies.subList(1, 3))));
Player player;
Enemy enemy;
Location location;
Scanner sc = new Scanner(System.in);
while (true) {
player = choosePlayer(players,sc);
while (true) {
location = chooseLocation(locations,sc);
enemy = chooseEnemy(location);
System.out.println("wanna fight?\n1.Yes\n2.No");
int choice = sc.nextInt();
if (choice == 1) {
combat(player,enemy,sc);
System.out.println("player AHP: " + player.getHP());
break;
}
else {
continue;
}
}
}
new Game().start();
}
/////////////////////////////////////////////////////////////////////////////////////////
public static void displayLocations(List<Location> locations) {
for (Location location : locations) {
System.out.println(location);
}
}
public static Player choosePlayer(ArrayList<Player> players, Scanner sc) {
System.out.print("1.Assassin\n2.Knight\n3.Wizard\nChoose your Character: ");
int choice = sc.nextInt();
Player player;
switch (choice) {
case 1 -> player = players.get(0);
case 2 -> player = players.get(1);
default -> player = players.get(2);
}
System.out.println("You chose " + player.getName() + "(" + player.getClass().getSimpleName() + ")");
return player;
}
public static Location chooseLocation(ArrayList<Location> locations, Scanner sc) {
displayLocations(locations);
System.out.print("1.Jungle\n2.China\n3.Iran\nChoose Location: ");
int choice = sc.nextInt();
Location location = null;
switch (choice) {
case 1 -> location = locations.get(0);
case 2 -> location = locations.get(1);
case 3 -> location = locations.get(2);
}
System.out.println("You chose " + location.getName() );
return location;
}
public static Enemy chooseEnemy(Location location) {
int random = new Random().nextInt(location.getEnemies().size());
Enemy enemy = location.getEnemies().get(random);
System.out.println("The Enemy is: " + enemy.getClass().getSimpleName());
return enemy;
}
public static void combat(Player player, Enemy enemy, Scanner sc) {
int turn = 0;
int choice;
while (player.isAlive() && enemy.isAlive()) {
if (turn == 0) {
turn = 1;
System.out.println("choose your action:\n1.light attack 2.heavy attack 3.defend 4.heal 5.special ability");
choice = sc.nextInt();
switch (choice) {
case 1:
player.lightAttack(enemy);
break;
case 2:
player.heavyAttack(enemy);
if (player.isSuccessfulAction()) break;
else {turn = 0; continue;}
case 3:
player.defend();
if (player.isSuccessfulAction()) break;
else {turn = 0; continue;}
case 4:
player.heal(10);
if (player.isSuccessfulAction()) break;
else {turn = 0; continue;}
case 5:
player.specialAbility(enemy);
if (player.isSuccessfulAction()) break;
else {turn = 0; continue;}
default:
System.out.println("invalid choice");
}
System.out.println("[" + player.getClass().getSimpleName() + " - " + player.getHP() + "/" + player.getMaxHP()
+ " HP | " + player.getMP() + "/" + player.getMaxMP() + " Mana" + "]");
System.out.println("[" + enemy.getClass().getSimpleName() + " - " + enemy.getHP() + "/" + enemy.getMaxHP()
+ " HP | " + enemy.getMP() + "/" + enemy.getMaxMP() + " Mana" + "]");
}
if (turn == 1) {
System.out.println("-".repeat(30));
if (player instanceof Assassin) {
if (player.getUsingSpecialAbility()){
player.setUsingSpecialAbility(false);
turn = 0;
System.out.println(enemy.getClass().getSimpleName() + " skipped it's turn!");
continue;
}
}
System.out.println(enemy.getClass().getSimpleName() + "'s turn: ");
turn = 0;
choice = new Random().nextInt(3);
switch (choice) {
case 0:
enemy.attack(player);
if (enemy.isSuccessfulAction()) break;
else {turn = 1; continue;}
case 1:
enemy.defend();
if (enemy.isSuccessfulAction()) break;
else {turn = 1; continue;}
case 2:
enemy.heal(10);
if (enemy.isSuccessfulAction()) break;
else {turn = 1; continue;}
}
}
System.out.println("[" + player.getClass().getSimpleName() + " - " + player.getHP() + "/" + player.getMaxHP()
+ " HP | " + player.getMP() + "/" + player.getMaxMP() +" Mana" + "]");
System.out.println("[" + enemy.getClass().getSimpleName() + " - " + enemy.getHP() + "/" + enemy.getMaxHP()
+ " HP | " + enemy.getMP() + "/" + enemy.getMaxMP() + " Mana" + "]");
}
if (!player.isAlive()) {
System.out.println("You lost!");
}
else {
System.out.println("You Won!");
if (enemy.dropKey()) {
System.out.println(enemy.getClass().getSimpleName() + "'s key dropped!");
player.achieveKey(enemy);
}
}
}
}
}
@@ -0,0 +1,61 @@
package org.project.entity.enemies;
import org.project.entity.Entity;
import org.project.item.weapons.Sword;
public class Dragon extends Enemy {
private static final int FIRE_BREATH_MP_COST = 30;
private int fireBreathCharge = 0;
public Dragon() {
super(200, 150, new Sword());
setDefendRate(.5);
}
@Override
public void attack(Entity target) {
System.out.println("Dragon breathes fire at " + target.getClass().getSimpleName() + "!");
fireBreathCharge++;
double damage = getAttackMultiplier() * getWeapon().getDamage();
if (fireBreathCharge >= 3) {
fireBreathCharge = 0;
System.out.println("FIRE BREATH! Dragon unleashes a devastating inferno!");
damage *= 2;
if (target.isDefending()) {
target.setDefending(false);
}
target.takeDamage((int) damage);
setMP(getMP() - FIRE_BREATH_MP_COST);
return;
}
if (target.isDefending()) {
target.setDefending(false);
}
target.takeDamage((int) damage);
setMP(getMP() - getWeapon().getManaCost());
}
@Override
public void defend() {
System.out.println("Dragon roars and ignores the chance to defend!");
setSuccessfulAction(true);
}
@Override
public void heal(int health) {
if (getMP() >= 20) {
System.out.println("Dragon regenerates " + health + " HP!");
setHP(getHP() + health);
setMP(getMP() - 20);
} else {
System.out.println("Dragon has no Mana to regenerate!");
setSuccessfulAction(false);
}
}
}
@@ -24,28 +24,21 @@ public abstract class Enemy implements Entity {
this.mp = mp;
this.maxMP = mp;
this.weapon = weapon;
if (!keyFound) { hasKey = Math.random() < .2;}
if (!keyFound) { hasKey = Math.random() < .9;}
}
@Override
public void attack(Entity target) {
setSuccessfulAction(true);
if (getMP() >= weapon.getManaCost()) {
System.out.println(this.getClass().getSimpleName() + ": attacking " + target.getClass().getSimpleName());
double damage = getAttackMultiplier() * weapon.getDamage();
if(((Sword)(weapon)).charge()) damage *= 1.4;
if (target.isDefending()) {
System.out.println(this.getClass().getSimpleName() + ": attacking " + target.getClass().getSimpleName());
double damage = getAttackMultiplier() * weapon.getDamage();
if (((Sword)(weapon)).charge()) damage *= 1.4;
if (target.isDefending()) {
target.takeDamage((int) (damage * (1 - target.getDefendRate())),this);
target.setDefending(false);
} else {
}else {
target.takeDamage((int) damage,this);
}
setMP(getMP() - weapon.getManaCost());
}
else {
System.out.println("not enough mana");
setSuccessfulAction(false);
}
}
@Override
@@ -115,6 +108,11 @@ public abstract class Enemy implements Entity {
@Override
public void setMP(int mp) {
this.mp = mp;
if (mp > maxMP) {
mp = maxMP;
} else if (mp < 0) {
mp = 0;
}
}
@Override
@@ -23,7 +23,7 @@ public class Goblin extends Enemy{
setMP(getMP() - 20);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Defend");
setSuccessfulAction(false);
}
}
@@ -35,7 +35,7 @@ public class Goblin extends Enemy{
setMP(getMP() - 15);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Heal");
setSuccessfulAction(false);
}
}
@@ -25,7 +25,7 @@ public class Skeleton extends Enemy{
setMP(getMP() - 8);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Defend");
setSuccessfulAction(false);
}
}
@@ -37,7 +37,7 @@ public class Skeleton extends Enemy{
setMP(getMP() - 18);
}
else {
System.out.println("Not enough MP");
System.out.println("Not enough MP for Heal");
setSuccessfulAction(false);
}
}
@@ -48,6 +48,7 @@ public class Skeleton extends Enemy{
if (getHP() <= 0 && !incarnation) {
setHP(getMaxHP() / 2);
incarnation = true;
System.out.println("The Skeleton shatters... but dark magic pulls its bones back together!");
}
}
@@ -16,12 +16,11 @@ public class Vampire extends Enemy{
super.attack(target);
double damage = weapon.getDamage() * getAttackMultiplier();
setAttackMultiplier(1);
if (target.isDefending()) {
super.heal( (int) (.3 * (damage * (1 - target.getDefendRate()))));
}
else {
super.heal( (int) (.3 * damage));
}
int lifeSteal = target.isDefending()
? (int)(.3 * (damage * (1 - target.getDefendRate())))
: (int)(.3 * damage);
System.out.println("Vampire drains " + lifeSteal + " HP from " + target.getClass().getSimpleName() + "!");
setHP(getHP() + lifeSteal);
}
@Override
@@ -31,7 +30,7 @@ public class Vampire extends Enemy{
setMP(getMP() - 15);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Defend");
setSuccessfulAction(false);
}
}
@@ -43,7 +42,7 @@ public class Vampire extends Enemy{
setMP(getMP() - 12);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Heal");
setSuccessfulAction(false);
}
}
@@ -27,8 +27,8 @@ public class Assassin extends Player {
@Override
public void heavyAttack(Entity target) {
super.heavyAttack(target);
if (getUsingSpecialAbility()) {
System.out.println("Assassin strikes from the shadows with lethal precision! (1.8x)");
setAttackMultiplier(1.8);
attack(target);
setAttackMultiplier(1);
@@ -36,12 +36,13 @@ public class Assassin extends Player {
}
else if (getMP() >= weapon.getManaCost()) {
System.out.println("Assassin delivers a heavy blow! (1.4x)");
setAttackMultiplier(1.4);
attack(target);
setAttackMultiplier(1);
setMP(getMP() - weapon.getManaCost());
} else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Attack");
setSuccessfulAction(false);
}
@@ -54,7 +55,7 @@ public class Assassin extends Player {
setMP(getMP() - 12);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Defend");
setSuccessfulAction(false);
}
}
@@ -63,11 +64,11 @@ public class Assassin extends Player {
public void specialAbility(Entity target) {
if (getMP() >= 25) {
setUsingSpecialAbility(true);
System.out.println("Assasin using SpecialAbility");
System.out.println("Assassin melts into the shadows... next heavy attack will be devastating!");
setMP(getMP() - 25);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for using special ability");
setSuccessfulAction(false);
}
}
@@ -79,7 +80,7 @@ public class Assassin extends Player {
setMP(getMP() - 12);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Heal");
setSuccessfulAction(false);
}
}
@@ -87,7 +88,7 @@ public class Assassin extends Player {
@Override
public void takeDamage(int damage) {
if (getUsingSpecialAbility()) {
System.out.println("player using special ability");
System.out.println("Assassin vanishes into the shadows — attack missed!");
} else {
damage = ((AssassinArmor) (getArmor())).reduceDamage(damage, this);
super.takeDamage(damage);
@@ -27,7 +27,6 @@ public class Knight extends Player {
@Override
public void heavyAttack(Entity target) {
super.heavyAttack(target);
if (getMP() >= weapon.getManaCost()) {
setAttackMultiplier(1.5);
attack(target);
@@ -35,7 +34,7 @@ public class Knight extends Player {
setMP(getMP() - weapon.getManaCost());
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Attack");
setSuccessfulAction(false);
}
}
@@ -47,7 +46,7 @@ public class Knight extends Player {
setMP(getMP() - 16);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Defend");
setSuccessfulAction(false);
}
}
@@ -57,12 +56,13 @@ public class Knight extends Player {
if (getMP() >= 30) {
setUsingSpecialAbility(true);
setAttackMultiplier(2);
System.out.println("Knight channels all strength into a devastating strike! (2x)");
attack(target);
setAttackMultiplier(1);
setMP(getMP() - 30);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for using special ability");
setUsingSpecialAbility(false);
}
}
@@ -74,7 +74,7 @@ public class Knight extends Player {
setMP(getMP() - 10);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Heal");
setSuccessfulAction(false);
}
}
@@ -84,6 +84,7 @@ public class Knight extends Player {
super.takeDamage(damage);
if (!getArmor().checkBrake()) {
int reflected = ((KnightArmor) armor).getReflectedDamage(damage);
System.out.println("Knight's armor reflects " + reflected + " damage back at " + attacker.getClass().getSimpleName() + "!");
attacker.takeDamage(reflected);
}
}
@@ -1,8 +1,7 @@
package org.project.entity.players;
import org.project.entity.Entity;
import org.project.entity.enemies.Goblin;
import org.project.entity.enemies.Skeleton;
import org.project.entity.enemies.*;
import org.project.item.armors.Armor;
import org.project.item.consumables.Consumable;
import org.project.item.consumables.Flask;
@@ -26,6 +25,10 @@ public abstract class Player implements Entity, CombatOptions {
private boolean hasVampireKey = false;
private boolean successfulAction = true;
private Consumable flask;
private int level = 1;
private int xp = 0;
private static final int BASE_XP = 50;
private static final double XP_SCALE = 1.4;
public Player(String name, int hp, int mp, Weapon weapon, Armor armor) {
this.name = name;
@@ -35,12 +38,15 @@ public abstract class Player implements Entity, CombatOptions {
this.maxMP = mp;
this.weapon = weapon;
this.armor = armor;
}
@Override
public void attack(Entity target) {
setSuccessfulAction(true);
double damage = getAttackMultiplier() * weapon.getDamage();
System.out.println(this.getClass().getSimpleName() + ": attacking " + target.getClass().getSimpleName()
+ " for " + damage + " damages!");
if (target.isDefending()) {
target.takeDamage( (int) (damage * (1 - target.getDefendRate())));
target.setDefending(false);
@@ -56,9 +62,7 @@ public abstract class Player implements Entity, CombatOptions {
}
@Override
public void heavyAttack(Entity target) {
System.out.println(this.getClass().getSimpleName() + " heavy attacking");
}
public abstract void heavyAttack(Entity target);
@Override
public void defend(){
@@ -76,12 +80,13 @@ public abstract class Player implements Entity, CombatOptions {
int finalDamage = armor.getDefense() - damage;
if (finalDamage < 0) {
System.out.println(this.getClass().getSimpleName() + " took " + -finalDamage + " damages!");
System.out.println(getClass().getSimpleName() + " took " + -finalDamage + " damage! (armor absorbed " + armor.getDefense() + ")");
setHP(getHP() + finalDamage);
armor.setDefense(0);
System.out.println("Your armor has been destroyed!");
}
else {
System.out.println(this.getClass().getSimpleName() + " took " + damage + " damages!");
System.out.println(getClass().getSimpleName() + " took 0 damage! (fully absorbed by armor, " + finalDamage + " durability remaining)");
armor.setDefense(finalDamage);
}
}
@@ -216,4 +221,46 @@ public abstract class Player implements Entity, CombatOptions {
return flask;
}
public int xpToNextLevel() {
return (int) (BASE_XP * Math.pow(XP_SCALE, level - 1));
}
private void levelUp() {
level++;
maxHP += 10;
maxMP += 8;
setHP(getHP() + 10); // heal by the amount gained
setMP(getMP() + 8);
System.out.println("★ LEVEL UP! " + getClass().getSimpleName()
+ " is now level " + level
+ " | Max HP +" + 10 + " | Max MP +" + 8);
}
public void gainXP(int amount) {
xp += amount;
System.out.println(getClass().getSimpleName() + " gained " + amount + " XP! ("
+ xp + "/" + xpToNextLevel() + ")");
while (xp >= xpToNextLevel()) {
xp -= xpToNextLevel();
levelUp();
}
}
public static int xpRewardFor(Entity enemy) {
if (enemy instanceof Dragon) return 300;
if (enemy instanceof Goblin) return 40;
if (enemy instanceof Skeleton) return 50;
return 60;
}
public int getLevel() { return level; }
public int getXP() { return xp; }
public boolean hasKey(Enemy enemy) {
if (enemy instanceof Goblin) return hasGoblinKey;
if (enemy instanceof Skeleton) return hasSkeletonKey;
if (enemy instanceof Vampire) return hasVampireKey;
return false;
}
}
@@ -27,7 +27,6 @@ public class Wizard extends Player{
@Override
public void heavyAttack(Entity target) {
super.heavyAttack(target);
if (getMP() >= weapon.getManaCost()) {
setAttackMultiplier(1.3);
attack(target);
@@ -35,7 +34,7 @@ public class Wizard extends Player{
setMP(getMP() - weapon.getManaCost());
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP to Attack");
setSuccessfulAction(false);
}
}
@@ -47,7 +46,7 @@ public class Wizard extends Player{
setMP(getMP() - 15);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Defend");
setSuccessfulAction(false);
}
}
@@ -56,13 +55,15 @@ public class Wizard extends Player{
public void specialAbility(Entity target) {
if (getMP() >= 20) {
setAttackMultiplier(1.6);
System.out.println("Wizard channels arcane energy — empowered shot fired! (1.6x)");
attack(target);
setAttackMultiplier(1);
setMP(getMP() - 20);
setHP(getHP() + 10);
System.out.println("Wizard absorbs residual magic — restored 10 HP!");
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for using SpecialAbility");
setSuccessfulAction(false);
}
}
@@ -74,7 +75,7 @@ public class Wizard extends Player{
setMP(getMP() - 10);
}
else {
System.out.println("Not enough MP");
System.out.println("Not Enough MP for Heal");
setSuccessfulAction(false);
}
}
@@ -83,6 +84,8 @@ public class Wizard extends Player{
public void takeDamage(int damage) {
if (!getArmor().checkBrake()) {
int finalDamage = ((WizardArmor) armor).absorbDamage(damage, getMP());
int absorbed = damage - finalDamage;
if (absorbed > 0) System.out.println("Wizard's mana field absorbs " + absorbed + " damage!");
super.takeDamage(finalDamage);
}
else {
@@ -19,6 +19,8 @@ public class AssassinArmor extends Armor {
public int reduceDamage(int damage, Player player) {
if (isLowHP(player)) {
System.out.println("Assassin's survival instincts kick in — damage halved!");
return damage / 2;
}
return damage;
@@ -8,7 +8,7 @@ public class WizardArmor extends Armor {
public int absorbDamage(int damage, int mp) {
int reduction = mp / 10; // every 10 MP absorbs 1 damage
int reduction = mp / 10;
return Math.max(0, damage - reduction);
}
@@ -1,6 +1,7 @@
package org.project.item.consumables;
import org.project.entity.Entity;
import org.project.entity.players.Player;
public class Flask extends Consumable {
private int healAmount;
@@ -22,8 +23,10 @@ public class Flask extends Consumable {
System.out.println(target.getClass().getSimpleName()
+ " restored " + healAmount + " MP!");
} else {
target.heal(healAmount);
target.setHP(target.getHP() + healAmount);
System.out.println(target.getClass().getSimpleName() + " healed " + healAmount + " HP!");
}
consume();
System.out.println("(" + getQuantity() + " charges remaining)");
}
}
@@ -0,0 +1,21 @@
package org.project.item.consumables;
import org.project.entity.Entity;
import org.project.entity.players.Player;
public class repairKit extends Consumable{
public repairKit() {
super("Repair Kit",1);
}
@Override
public void use(Entity target) {
if (!hasCharges()) {
System.out.println("Repair Kit is not available");
return;
}
((Player) (target)).getArmor().repair();
consume();
System.out.println("Armor repaired!");
}
}
Binary file not shown.
+134 -153
View File
@@ -1,175 +1,156 @@
# Fourth Assignment - Java Knight ⚔️
A turn-based RPG with Roguelike elements which can be run in the terminal.
# Java 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 turn-based RPG built in Java where you choose your hero, battle monsters across treacherous locations, collect keys from fallen enemies, and ultimately face the Dragon boss.
---
## Tasks 📝
## Overview
### 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 🌲
Three heroes. Three locations. Three enemies standing between you and the Dragon.
A well-structured OOP hierarchy is crucial. Avoid duplicating code by placing shared logic in abstract classes.
Defeat a Goblin, a Skeleton, and a Vampire to collect their keys — only then can you challenge the Dragon and claim victory. Each hero plays completely differently, each enemy has unique mechanics, and every fight demands smart resource management.
- **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
### Features
![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]
- **3 playable characters** — Assassin, Knight, Wizard — each with unique abilities, weapons, and armor mechanics
- **4 enemies** — Goblin, Skeleton, Vampire, and the Dragon boss
- **3 locations** — Jungle, China, Iran — each with different enemy pools
- **Key collection system** — defeat one of each enemy type to unlock the Dragon
- **Rich combat** — light attacks, heavy attacks, defend, heal, special abilities, and flasks
- **Leveling system** — gain XP from victories, level up to increase max HP and MP
- **Special enemy mechanics** — Skeleton revives, Vampire lifesteals, Dragon charges fire breath
---
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 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 17 or higher
- Any Java IDE (IntelliJ IDEA, Eclipse, VS Code) or the command line
### 4️⃣ Step 4: Implement the Game Loop & Progression 🎮
### Run from an IDE
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).
1. Clone or download the repository
2. Open the project in your IDE
3. Run `Main.java`
---
## Evaluation Criteria ⚖
## Gameplay Guide
| **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** |
### Choosing your hero
## 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.
At the start you'll pick one of three characters. Your choice determines your weapon, armor type, flask, and special ability.
## 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.
### The goal
![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.
Explore locations, fight enemies, and collect a key from each enemy type (Goblin, Skeleton, Vampire). Once all three keys are in hand, you'll be offered the chance to challenge the Dragon. Win that fight — and the game is yours.
### Combat actions
Each turn you choose one of six actions:
| # | Action | Description |
|---|--------|-------------|
| 1 | **Light attack** | Always free, no MP cost. May trigger a weapon bonus |
| 2 | **Heavy attack** | Costs MP. Deals boosted damage |
| 3 | **Defend** | Costs MP. Reduces incoming damage this turn |
| 4 | **Heal** | Costs MP. Restores 10 HP |
| 5 | **Special ability** | Costs MP. Unique per character |
| 6 | **Flask** | Free. Uses a consumable charge |
If an action fails due to insufficient MP, you'll be prompted to choose again — your turn is not wasted.
### Locations
| Location | Enemies |
|----------|---------|
| Jungle | Goblin, Skeleton, Vampire |
| China | Goblin, Skeleton |
| Iran | Skeleton, Vampire |
The enemy you face is chosen randomly from the location's pool each visit.
---
## Heroes
### Assassin
*Weapon: Dagger (8 dmg) — Flask: Health Flask (10 HP × 3)*
A high-risk, high-reward fighter. Most actions cost MP, but the special ability unlocks a devastating free strike.
- **Light attack** — 30% chance to critical hit for 1.5x damage
- **Heavy attack** — 1.4x damage, costs MP. If shadow step is active: 1.8x and free
- **Defend** — costs 12 MP, blocks with 70% damage reduction
- **Special ability** — costs 25 MP, activates Shadow Step: enemy skips their next turn, and your next heavy attack becomes 1.8x and free
- **Armor passive** — when below 40% HP, all incoming damage is halved
### Knight
*Weapon: Sword (12 dmg) — Flask: Mana Flask (20 MP × 3)*
A durable tank who punishes attackers. High defend rate and reliable damage output.
- **Light attack** — every 3rd swing triggers a Charged Strike for 1.4x damage
- **Heavy attack** — 1.5x damage, costs MP
- **Defend** — costs 16 MP, blocks with 90% damage reduction
- **Special ability** — costs 30 MP, delivers a 2x damage strike
- **Armor passive** — reflects 15% of received damage back at the attacker
### Wizard
*Weapon: Bow (15 dmg) — Flask: Mana Flask (30 MP × 3)*
A glass cannon with the highest damage ceiling and a unique mana-shield defense.
- **Light attack** — every 4th shot triggers a Charged Strike: fires twice at 1.4x
- **Heavy attack** — 1.3x damage, costs MP
- **Defend** — costs 15 MP, blocks with 60% damage reduction
- **Special ability** — costs 20 MP, fires an empowered 1.6x shot and restores 10 HP
- **Armor passive** — every 10 MP absorbs 1 incoming damage (as long as armor holds)
---
## Enemies
| Enemy | HP | MP | Special |
|-------|----|----|---------|
| Goblin | 80 | 100 | Always attacks at 1.8x multiplier |
| Skeleton | 70 | 100 | Revives at 35 HP the first time it dies |
| Vampire | 90 | 90 | Lifesteals 30% of damage dealt each attack |
| Dragon | 200 | 150 | Every 3rd attack is an unavoidable Fire Breath at 2x damage |
---
## Architecture
The project is structured around a clean inheritance hierarchy:
```
Entity (interface)
├── Player (abstract)
│ ├── Assassin
│ ├── Knight
│ └── Wizard
└── Enemy (abstract)
├── Goblin
├── Skeleton
├── Vampire
└── Dragon
Item (interface)
├── Weapon (abstract)
│ ├── Sword
│ ├── Bow
│ └── Dagger
├── Armor (abstract)
│ ├── KnightArmor
│ ├── WizardArmor
│ └── AssassinArmor
└── Consumable (abstract)
├── Flask
└── RepairKit
Location
Game (orchestrator)
```
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB