7 Commits
Author SHA1 Message Date
farnam_jhn 71f3134b10 Updated README.md & REPORT.md
+ added jar build to repo
- removed unnecessarily files
2026-05-11 14:18:10 +03:30
farnam_jhn 82027ac95e + (fix) : fixed bugs related to changing location. 2026-05-11 12:36:46 +03:30
farnam_jhn 70f03438fa + (fix): fixed major bugs :
1. Skeleton now resurrects
2. Armor doesn't heal the player
+ (buff) buffed players
2026-05-11 12:17:45 +03:30
farnam_jhn 6102cf0dbc + Finished Main Loop
+ Finished the game mechanics
+ Added a weapon for Vampire
2026-05-11 00:36:04 +03:30
farnam_jhn deb26fc24f + Added Armors
+ Added Weapons
+ Added REPORT.md
+ Finished the classes
+ (fix) Fixed problems caused by class hierarchy
- (todo) main loop, key mechanic.
2026-05-10 17:38:01 +03:30
farnam_jhn 4e8daa6655 + Finished Player & Enemy
+ Implemented specialAbility for every Entity
2026-05-09 19:42:42 +03:30
farnam_jhn 5bf47bf93c + Added classes : Assassin, Dragon, Goblin, Vampire, Wizard
+ Implemented inheritance structure
+ Implemented 5 methods of Player actions
2026-05-05 11:51:13 +03:30
32 changed files with 1080 additions and 304 deletions
+11
View File
@@ -0,0 +1,11 @@
<component name="ArtifactManager">
<artifact type="jar" name="HW-04-JAVA-KNIGHT:jar">
<output-path>$PROJECT_DIR$/out/artifacts/HW_04_JAVA_KNIGHT_jar</output-path>
<root id="archive" name="HW-04-JAVA-KNIGHT.jar">
<element id="directory" name="META-INF">
<element id="file-copy" path="$PROJECT_DIR$/META-INF/MANIFEST.MF" />
</element>
<element id="module-output" name="Java-Knight" />
</root>
</artifact>
</component>
+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>
+322 -4
View File
@@ -1,15 +1,333 @@
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.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) {
// TODO: ADD LOCATIONS TO YOUR GAME
List<Location> locations = new ArrayList<>();
// Colors
private static final String RESET = "\u001B[0m"; // Reset ANSI code
private static final String RED = "\u001B[31m";
private static final String GREEN = "\u001B[32m";
private static final String YELLOW = "\u001B[33m";
private static final String BLUE = "\u001B[34m";
private static final String PURPLE = "\u001B[35m";
private static final String LIGHT_GRAY = "\u001B[37m";
// TODO: IMPLEMENT GAMEPLAY
private static boolean gameRunning = true;
static List<Location> locations = new ArrayList<>();
public static void main(String[] args) {
// Scanner
Scanner scanner = new Scanner(System.in);
Random random = new Random(); // for initial location
Location castle = new Location("Castle", new Dragon());
Location forest = new Location("Forest");
Location ruins = new Location("Ruins");
Location village = new Location("Village");
locations.add(forest);
locations.add(ruins);
locations.add(village);
locations.add(castle);
// Main loop
boolean isRunning = true;
while (isRunning){
System.out.println(YELLOW + "------------------Legend of AP------------------" + RESET);
System.out.println(" Choose your option :");
System.out.println(BLUE + " 1." + RESET + " Start a new game");
System.out.println(BLUE + " 2." + RESET + " Exit");
int option = scanner.nextInt();
switch (option){
case 1:
startNewGame(scanner, random);
break;
case 2:
System.out.println("Goodbye!");
isRunning = false;
break;
default:
continue;
}
}
}
public static void startNewGame(Scanner scanner, Random random){
Player player;
int randNum1 = random.nextInt(3); // used for random initial location.
System.out.println("Enter your name : ");
String name = scanner.next();
Location currentLocation = locations.get(randNum1);
int charOption = 0;
while ( (charOption <= 0) ||
(charOption >= 4)) {
System.out.println("Choose your character :");
System.out.println(BLUE + " 1." + RESET + " Knight");
System.out.println(BLUE + " 2." + RESET + " Assassin (it has a cool" + GREEN + " green" + RESET + " light saber!)");
System.out.println(BLUE + " 3." + RESET + " Wizard");
charOption = scanner.nextInt();
}
player = switch (charOption) {
case 1 -> new Knight(name);
case 2 -> new Assassin(name);
case 3 -> new Wizard(name);
default -> null;
};
// Resetting running flag
gameRunning = true;
System.out.println("Going to : " + GREEN + currentLocation.getName() + RESET);
spawnRandomEnemy(currentLocation,random);
while (gameRunning && !player.isDead()){
int choice = miniMenu(currentLocation,player);
switch (choice){
case 1:
if (currentLocation.hasEnemy()) {
fight(player, currentLocation.getEnemy(), currentLocation);
if (!player.isDead() && !currentLocation.hasEnemy()) {
// gain XP and recover
player.gainXP(100);
player.fullRestore();
System.out.println(GREEN + "HP and MP restored." + RESET);
// spawn a new enemy
spawnRandomEnemy(currentLocation, random);
}
}
break;
case 2:
currentLocation = moveToLocation(scanner, currentLocation, player);
if (!currentLocation.hasEnemy()) {
spawnRandomEnemy(currentLocation, random);
}
System.out.println(GREEN + "Arrived at: " + currentLocation.getName() + RESET);
break;
case 3:
if (player.hasAllKeys()){
currentLocation = locations.get(3);
System.out.println(PURPLE + "--DRAGON FIGHT--" + RESET);
Enemy dragon = new Dragon();
fight(player,dragon,currentLocation);
if (dragon.isDead()){
System.out.println(YELLOW + "VICTORY!" + RESET);
System.out.println("Level : " + player.getLevel());
gameRunning = false;
}
}else {
System.out.println("Locked !");
}
break;
}
}
}
public static int miniMenu(Location loc,Player player){
boolean castleUnLocked = player.hasGoblinKey() && player.hasSkelKey() && player.hasVampKey();
Scanner scanner = new Scanner(System.in);
int chosenOpt = 0;
while (chosenOpt <= 0 ||
chosenOpt >= 4){
System.out.println("Choose an option : ");
System.out.println(BLUE + " 1." + RESET + " Stay at " + loc.getName() + " and fight with " + loc.getEnemy().getName());
System.out.println(BLUE + " 2." + RESET + " Move to another place");
if (castleUnLocked){
System.out.println(BLUE + " 3." + PURPLE + " Go to castle and fight with the dragon" + RESET);
}
else {
System.out.println(" \uD83D\uDD12" + LIGHT_GRAY + "3. Go to castle and fight with the dragon" + RESET);
}
chosenOpt = scanner.nextInt();
}
return chosenOpt;
}
private static void spawnRandomEnemy(Location location, Random random) {
int enemyType = random.nextInt(3);
switch (enemyType){
case 0:
location.setEnemy(new Vampire());
System.out.println("A " + RED + "Vampire" + RESET + " Spawned !");
break;
case 1:
location.setEnemy(new Skeleton());
System.out.println("A Skeleton Spawned !");
break;
case 2:
location.setEnemy(new Goblin());
System.out.println("A " + GREEN + "Goblin" + RESET + " Spawned !");
break;
}
}
private static Location moveToLocation(Scanner scanner, Location current, Player player) {
int choice = -1;
do {
System.out.println("Choose a location to move to:");
for (int i = 0; i < locations.size(); i++) {
String prefix = locations.get(i).equals(current) ? " * " : " ";
System.out.println(BLUE + " " + (i + 1) + "." + RESET + " " + prefix + locations.get(i).getName());
}
choice = scanner.nextInt() - 1;
if (choice == 3 && !player.hasAllKeys()){
System.out.println("Locked!");
choice = -1;
}
} while (choice < 0 || choice >= locations.size());
return locations.get(choice);
}
private static void fight(Player player, Enemy enemy, Location location) {
System.out.println(RED + " COMBAT STARTED!" + RESET);
while (!player.isDead() && !enemy.isDead()) {
// Player turn
playerTurn(player, enemy);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// Enemy turn
if (!enemy.isStunned()) {
enemyTurn(player, enemy);
} else {
System.out.println(BLUE + enemy.getName() + RESET + " is stunned. skipping to player...");
enemy.stun(false);
}
}
if (player.isDead()){
System.out.println("Game over.");
System.out.println("Level : " + player.getLevel());
gameRunning = false;
} else if (enemy.isDead()) {
System.out.println(player.getName() + RED + " Killed " + "a " + RESET + enemy.getName() + " at " + GREEN + location.getName() + RESET);
keyMechanic(player,enemy);
location.clearEnemy();
}
}
private static void playerTurn(Player player, Enemy enemy) {
Scanner scanner = new Scanner(System.in);
System.out.println("\n" + BLUE + "Your Turn:" + RESET);
System.out.println(RED + "HP : " + RESET + player.getHp() + "/" + player.getMaxHP() +
GREEN + " | MP: " + RESET + player.getMp() + "/" + player.getMaxMP());
System.out.println(BLUE + " 1." + RESET + " Light Attack " + GREEN + "(0 MP)" + RESET);
System.out.println(BLUE + " 2." + RESET + " Heavy Attack " + GREEN + "(-" + player.getWeapon().getManaCost() + " MP)" + RESET);
System.out.println(BLUE + " 3." + RESET + " Defend " + GREEN + "(-5 MP)" + RESET);
System.out.println(BLUE + " 4." + RESET + " Heal " + GREEN + "(-10 MP)" + RESET);
System.out.println(BLUE + " 5." + RESET + " Special Ability " + GREEN + "(-" + player.specialAblMPCost() + " MP)" + RESET);
int choice;
do {
choice = scanner.nextInt();
} while (choice <= 0 ||
choice >= 6);
switch (choice) {
case 1:
player.lightAttack(enemy);
break;
case 2:
if (player.getMp() >= player.getWeapon().getManaCost()) {
player.heavyAttack(enemy);
} else {
System.out.println(RED + "Not enough MP!, light attacking." + RESET);
player.lightAttack(enemy);
}
break;
case 3:
player.defend();
break;
case 4:
if (player.getMp() >= 10) {
player.heal(30);
} else {
System.out.println(RED + "Not enough MP!" + RESET);
}
break;
case 5:
if (player.getMp() >= player.specialAblMPCost()) {
player.specialAbility(enemy);
} else {
System.out.println(RED + "Not enough MP!" + RESET);
}
break;
}
System.out.println(RED + "HP : " + RESET + player.getHp() + "/" + player.getMaxHP() +
GREEN + " | MP: " + RESET + player.getMp() + "/" + player.getMaxMP());
System.out.println(RED + "Enemy's HP : " + RESET + enemy.getHp());
}
private static void enemyTurn(Player player,Enemy enemy) {
System.out.println(RED + "\n" + enemy.getName() + "'s Turn:" + RESET);
// randomly choosing between attack and specialAbility with probability of 1/3
Random random = new Random();
if (random.nextInt(3) == 0) {
enemy.specialAbility(player);
} else {
enemy.attack(player);
}
System.out.println(RED + "Your HP : " + RESET + player.getHp() + "/" + player.getMaxHP());
}
private static void keyMechanic(Player player, Enemy enemy){
Random random = new Random();
if (enemy instanceof Goblin){
if (player.hasGoblinKey()) return;
if (random.nextInt(3) == 0) player.gotGoblinKey();
}
else if (enemy instanceof Vampire){
if (player.hasVampKey()) return;
if (random.nextInt(3) == 0) player.gotVampKey();
}
else if (enemy instanceof Skeleton) {
if (player.hasSkelKey()) return;
if (random.nextInt(3) == 0) player.gotSkelKey();
}
}
}
@@ -1,21 +1,24 @@
package org.project.entity;
public interface Entity {
void attack(Entity target);
import org.project.entity.players.Player;
void defend();
public abstract class Entity {
void heal(int health);
public abstract void stun(boolean value);
void fillMana(int mana);
public abstract void setHp(int newHp);
void takeDamage(int damage);
public abstract boolean isCritical();
int getMaxHP();
public abstract boolean isStunned();
int getMaxMP();
public abstract void makeCritical(boolean value);
/*
TODO: ADD OTHER REQUIRED AND BONUS METHODS
*/
public abstract void makeDie();
public abstract void takeDamage(int damage);
public abstract boolean isDead();
public abstract void heal(int health);
}
@@ -0,0 +1,26 @@
package org.project.entity.enemies;
import org.project.entity.players.Player;
import org.project.item.weapons.DragonBreath;
import org.project.item.weapons.Weapon;
public class Dragon extends Enemy{
private static final int HP = 600;
public Dragon(){
Weapon dragonBreath = new DragonBreath();
super(HP, dragonBreath);
}
@Override
public String getName() {
return "Dragon";
}
@Override
public void specialAbility(Player target) {
target.breakShield();
super.attack(target);
}
}
@@ -1,34 +1,90 @@
package org.project.entity.enemies;
import org.project.entity.Entity;
import org.project.entity.players.Player;
import org.project.item.weapons.Weapon;
// TODO: UPDATE IMPLEMENTATION
public abstract class Enemy {
public abstract class Enemy extends Entity {
Weapon weapon;
private int hp;
private int mp;
private boolean stunned = false;
private boolean critical = false;
private boolean dead = false;
public Enemy(int hp, int mp, Weapon weapon) {
private static final double DAMAGE_MODIFIER = 1.5; // Used for critical hits
public Enemy(int hp, Weapon weapon) {
this.hp = hp;
this.mp = mp;
this.weapon = weapon;
}
public void attack(Entity target){
if (critical){
target.takeDamage((int)(weapon.getDamage() * DAMAGE_MODIFIER));
}
else {
target.takeDamage(weapon.getDamage());
}
}
@Override
public void heal(int health) {
hp += health;
}
@Override
public void takeDamage(int damage) {
hp -= damage;
if (hp <= 0){
hp = 0;
makeDie();
}
}
@Override
public void stun(boolean value) {
stunned = value;
}
@Override
public void makeCritical(boolean value) {
critical = value;
}
@Override
public void makeDie() {
dead = true;
}
@Override
public void setHp(int newHp) {
hp = newHp;
}
@Override
public boolean isCritical(){
return critical;
}
@Override
public boolean isStunned() {
return stunned;
}
@Override
public boolean isDead() {
return dead;
}
public int getHp() {
return hp;
}
public int getMp() {
return mp;
}
public abstract String getName();
public Weapon getWeapon() {
return weapon;
}
public abstract void specialAbility(Player target);
}
@@ -0,0 +1,41 @@
package org.project.entity.enemies;
import java.util.Random;
import org.project.entity.Entity;
import org.project.entity.players.Player;
import org.project.item.weapons.Dagger;
import org.project.item.weapons.Weapon;
public class Goblin extends Enemy{
private static final int HEALTH_POINT = 100;
public Goblin(){
Weapon goblinDagger = new Dagger();
super(HEALTH_POINT, goblinDagger);
}
@Override
public void specialAbility(Player target) {
this.criticality();
super.attack(target);
}
@Override
public String getName() {
return "Goblin";
}
// makes the next move critical with a probability of 80
private void criticality(){
Random random = new Random();
int randNum = random.nextInt(100);
if (randNum < 80){
this.makeCritical(true);
}
}
}
@@ -1,6 +1,38 @@
package org.project.entity.enemies;
// TODO: UPDATE IMPLEMENTATION
public class Skeleton {
// TODO: DESIGN ENEMY AND IMPLEMENT THE CONSTRUCTOR
import org.project.entity.players.Player;
import org.project.item.weapons.Dagger;
import org.project.item.weapons.Weapon;
public class Skeleton extends Enemy {
private static final int HP = 100;
private int deathCounter = 0;
public Skeleton(){
Weapon skeletonDagger = new Dagger();
super(HP,skeletonDagger);
}
@Override
public void specialAbility(Player target) {
super.attack(target);
}
@Override
public String getName() {
return "Skeleton";
}
@Override
public void makeDie() {
if (deathCounter == 0){
this.setHp(HP / 2);
deathCounter++;
System.out.println("Skeleton resurrected!");
return;
}
super.makeDie();
}
}
@@ -0,0 +1,30 @@
package org.project.entity.enemies;
import org.project.entity.Entity;
import org.project.entity.players.Player;
import org.project.item.weapons.Bite;
import org.project.item.weapons.Weapon;
public class Vampire extends Enemy{
private static final int SPECIAL_ABL_DMG = 40;
private static final int RANDEMANT_PERCENT = 70; // this constant determines how much of dealt damage should be given to vamp.
private static final int HP = 350;
public Vampire(){
Weapon vampBite = new Bite();
super(HP, vampBite);
}
@Override
public String getName() {
return "Vampire";
}
@Override
public void specialAbility(Player target) {
System.out.println("Stealing life!...");
target.takeDamage(SPECIAL_ABL_DMG);
this.heal((SPECIAL_ABL_DMG * RANDEMANT_PERCENT) / 100);
}
}
@@ -0,0 +1,34 @@
package org.project.entity.players;
import org.project.entity.Entity;
import org.project.entity.enemies.Enemy;
import org.project.item.armors.Armor;
import org.project.item.armors.AssasinArmor;
import org.project.item.weapons.LightSaber;
import org.project.item.weapons.Weapon;
public class Assassin extends Player{
private static final int MAX_HP = 300;
private static final int MAX_MP = 50;
private static final int SPECIAL_ABILITY_MANA_COST = 5;
public Assassin(String name){
Weapon assassinSaber = new LightSaber("Green"); // idk why but i gave assassin a light saber.
Armor assassinArmor = new AssasinArmor();
super(name, MAX_HP, MAX_MP, assassinSaber, assassinArmor, MAX_HP,MAX_MP);
}
@Override
public void specialAbility(Enemy target) {
mp -= SPECIAL_ABILITY_MANA_COST;
System.out.println("Turning invisible...");
this.defend();
this.makeCritical(true);
}
@Override
public int specialAblMPCost() {
return SPECIAL_ABILITY_MANA_COST + DEFEND_MP_COST;
}
}
@@ -1,6 +1,35 @@
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.Armor;
import org.project.item.armors.KnightArmor;
import org.project.item.weapons.Sword;
import org.project.item.weapons.Weapon;
public class Knight extends Player {
private static final int MAX_HP = 400;
private static final int MAX_MP = 40;
private static final int SPECIAL_ABILITY_MANA_COST = 20;
public Knight(String name){
Weapon knightSword = new Sword();
Armor knightArmor = new KnightArmor();
super(name, MAX_HP, MAX_MP, knightSword, knightArmor, MAX_HP,MAX_MP);
}
@Override
public void specialAbility(Enemy target) {
System.out.println("Performing shield bash...");
target.stun(true);
target.takeDamage(50);
this.mp -= SPECIAL_ABILITY_MANA_COST;
}
@Override
public int specialAblMPCost() {
return SPECIAL_ABILITY_MANA_COST;
}
}
@@ -1,60 +1,197 @@
package org.project.entity.players;
import org.project.entity.Entity;
import org.project.entity.enemies.Enemy;
import org.project.item.armors.Armor;
import org.project.item.weapons.Weapon;
// TODO: UPDATE IMPLEMENTATION
public abstract class Player {
public abstract class Player extends Entity {
protected String name;
Weapon weapon;
Armor armor;
private int hp;
private int maxHP;
private int mp;
protected int mp;
private int maxMP;
private int experiencePoint = 0;
private int level = 1;
private boolean stunned = false;
private boolean isDefending = false;
private boolean critical = false;
private boolean dead = false;
private boolean hasGoblinKey = false;
private boolean hasVampKey = false;
private boolean hasSkelKey = false;
private int xpToNextLevel = 100;
public Player(String name, int hp, int mp, Weapon weapon, Armor armor) {
private static final double DAMAGE_MODIFIER = 1.5; // Used for critical hits
private static final int LIGHT_ATTACK_DAMAGE = 30;
protected static final int DEFEND_MP_COST = 5;
protected static final int HEAL_MP_COST = 10;
public Player(String name, int hp, int mp, Weapon weapon, Armor armor,int maxHP, int maxMP) {
this.name = name;
this.hp = hp;
this.mp = mp;
this.maxHP = maxHP;
this.maxMP = maxMP;
this.weapon = weapon;
this.armor = armor;
}
@Override
public void attack(Entity target) {
public void lightAttack(Entity target){
if (critical){
target.takeDamage((int)(LIGHT_ATTACK_DAMAGE*DAMAGE_MODIFIER));
this.makeCritical(false);
}
else {
target.takeDamage(LIGHT_ATTACK_DAMAGE);
}
}
public void heavyAttack(Entity target){
if (critical){
target.takeDamage((int)(weapon.getDamage()*DAMAGE_MODIFIER));
}
else {
target.takeDamage(weapon.getDamage());
}
mp -= weapon.getManaCost();
}
@Override
public void defend() {
// TODO
this.mp -= DEFEND_MP_COST;
isDefending = true;
System.out.println("Defending...");
}
public void breakShield(){ // used for dragon ability
if (isDefending){
isDefending = false;
System.out.println("Shield broken.");
}
}
@Override
public void takeDamage(int damage) {
if (!isDefending) {
if (armor.getDefense() - damage > 0){
armor.use();
} else if (armor.isBroke()) {
hp -= damage;
} else {
hp -= damage - armor.getDefense();
armor.use();
}
}
else {
System.out.println("Defended the attack.");
isDefending = false;
}
if (hp <= 0){
hp = 0;
this.dead = true;
}
}
@Override
public void heal(int health) {
mp -= HEAL_MP_COST;
hp += health;
if (hp > maxHP) {
hp = maxHP;
}
}
@Override
public void fillMana(int mana) {
mp += mana;
if (mp > maxMP) {
mp = maxMP;
public void gainXP(int amount){
this.experiencePoint += amount;
System.out.println("Gained " + amount + " XP.");
while (experiencePoint >= xpToNextLevel){
levelUp();
}
}
public void levelUp(){
this.experiencePoint -= xpToNextLevel;
this.level++;
int oldMaxHP = maxHP;
int oldMaxMP = maxMP;
maxMP += 5;
maxHP += 50;
hp = maxHP;
mp = maxMP;
System.out.println("Level Up! You are now at level : " + level);
System.out.println("Stats : HP : " + oldMaxHP + " -> " + maxHP + " , MP : " + oldMaxMP + " -> " + maxMP);
xpToNextLevel += xpToNextLevel / 4;
}
public int getLevel(){
return level;
}
public void fullRestore(){
this.setHp(getMaxHP());
this.setMp(getMaxMP());
}
public void gotGoblinKey(){
hasGoblinKey = true;
System.out.println("Got the goblin key.");
}
public void gotVampKey(){
hasVampKey = true;
System.out.println("Got the vampire key.");
}
public void gotSkelKey(){
hasSkelKey = true;
System.out.println("Got the skeleton key.");
}
public void setMp(int mp){
this.mp = mp;
}
@Override
public void makeCritical(boolean value) {
critical = value;
}
@Override
public void makeDie() {
dead = true;
}
public abstract void specialAbility(Enemy target);
@Override
public void stun(boolean value) {
stunned = value;
}
@Override
public void setHp(int newHp) {
hp = newHp;
}
@Override
public boolean isCritical(){ return critical;}
@Override
public boolean isStunned() {
return stunned;
}
public String getName() {
return name;
@@ -64,20 +201,28 @@ public abstract class Player {
return hp;
}
public boolean isDefending() {
return isDefending;
}
@Override
public boolean isDead() {
return dead;
}
public int getMaxHP() {
return maxHP;
}
public int getMp() {
return mp;
}
@Override
public int getMaxMP(){
return maxMP;
}
public int getMp() {
return mp;
}
public Weapon getWeapon() {
return weapon;
}
@@ -86,4 +231,21 @@ public abstract class Player {
return armor;
}
public boolean hasGoblinKey(){
return hasGoblinKey;
}
public boolean hasSkelKey() {
return hasSkelKey;
}
public boolean hasVampKey() {
return hasVampKey;
}
public boolean hasAllKeys(){
return (hasSkelKey && hasVampKey && hasGoblinKey);
}
public abstract int specialAblMPCost();
}
@@ -0,0 +1,36 @@
package org.project.entity.players;
import org.project.entity.Entity;
import org.project.entity.enemies.Enemy;
import org.project.item.armors.Armor;
import org.project.item.armors.WizardArmor;
import org.project.item.weapons.FireBall;
import org.project.item.weapons.Weapon;
public class Wizard extends Player{
private static final int MAX_HP = 500;
private static final int MAX_MP = 30;
private static final int SPELL_DAMAGE = 40;
private static final int SPELL_HEAL_AMOUNT = 20;
private static final int SPECIAL_ABILITY_MANA_COST = 11;
public Wizard(String name ){
Weapon wizardWeapon = new FireBall();
Armor wizardArmor = new WizardArmor();
super(name, MAX_HP, MAX_MP, wizardWeapon, wizardArmor, MAX_HP, MAX_MP);
}
@Override
public void specialAbility(Enemy target) {
mp -= SPECIAL_ABILITY_MANA_COST;
System.out.println("Casting spell...");
target.takeDamage(SPELL_DAMAGE);
this.heal(SPELL_HEAL_AMOUNT);
}
@Override
public int specialAblMPCost() {
return SPECIAL_ABILITY_MANA_COST + HEAL_MP_COST;
}
}
@@ -1,11 +0,0 @@
package org.project.item;
import org.project.entity.Entity;
public interface Item {
void use(Entity target);
/*
TODO: ADD OTHER REQUIRED AND BONUS METHODS
*/
}
@@ -1,33 +1,33 @@
package org.project.item.armors;
// TODO: UPDATE IMPLEMENTATION
public abstract class Armor {
private int defense;
private int maxDefense;
private int durability;
private int maxDurability;
private int durabilityCost;
private boolean isBroke;
public Armor(int defense, int durability) {
public Armor(int defense, int durability, int durabilityCost) {
this.defense = defense;
this.durability = durability;
this.durabilityCost = durabilityCost;
}
public void checkBreak() {
public void use(){
durability -= durabilityCost;
System.out.println("Used Armor.");
checkBreak();
}
private void checkBreak() {
if (durability <= 0) {
isBroke = true;
durability = 0;
defense = 0;
System.out.println("Armor broke.");
}
}
// TODO: (BONUS) UPDATE THE REPAIR METHOD
public void repair() {
isBroke = false;
defense = maxDefense;
durability = maxDurability;
}
public int getDefense() {
return defense;
}
@@ -0,0 +1,11 @@
package org.project.item.armors;
public class AssasinArmor extends Armor{
private static final int DURABILITY = 75;
private static final int DEFENSE = 20;
private static final int SINGLE_DEFENSE_COST = 25;
public AssasinArmor(){
super(DEFENSE,DURABILITY,SINGLE_DEFENSE_COST);
}
}
@@ -1,6 +1,11 @@
package org.project.item.armors;
// TODO: UPDATE IMPLEMENTATION
public class KnightArmor {
// TODO: DESIGN ARMOR'S ATTRIBUTES IMPLEMENT THE CONSTRUCTOR
public class KnightArmor extends Armor{
private static final int DURABILITY = 100;
private static final int DEFENSE = 30;
private static final int SINGLE_DEFENSE_COST = 25;
public KnightArmor(){
super(DEFENSE,DURABILITY,SINGLE_DEFENSE_COST);
}
}
@@ -0,0 +1,11 @@
package org.project.item.armors;
public class WizardArmor extends Armor{
private static final int DURABILITY = 50;
private static final int DEFENSE = 15;
private static final int SINGLE_DEFENSE_COST = 25;
public WizardArmor(){
super(DEFENSE,DURABILITY,SINGLE_DEFENSE_COST);
}
}
@@ -1,8 +0,0 @@
package org.project.item.consumables;
// TODO: UPDATE IMPLEMENTATION
public abstract class Consumable {
/*
TODO: ADD OTHER REQUIRED AND BONUS METHODS
*/
}
@@ -1,16 +0,0 @@
package org.project.item.consumables;
import org.project.entity.Entity;
// TODO: UPDATE IMPLEMENTATION
public class Flask {
/*
THIS IS AN EXAMPLE OF A CONSUMABLE DESIGN.
*/
// TODO: UPDATE USE METHOD
@Override
public void use(Entity target) {
target.heal(target.getMaxHP() / 10);
}
}
@@ -0,0 +1,9 @@
package org.project.item.weapons;
public class Bite extends Weapon{
private static final int DAMAGE = 30;
public Bite(){
super(DAMAGE, 0); // the dagger is only meant to get used by skeleton and goblin, hence it doesen't use mana.
}
}
@@ -0,0 +1,9 @@
package org.project.item.weapons;
public class Dagger extends Weapon{
private static final int DAMAGE = 30;
public Dagger(){
super(DAMAGE, 0); // the dagger is only meant to get used by skeleton and goblin, hence it doesen't use mana.
}
}
@@ -0,0 +1,9 @@
package org.project.item.weapons;
public class DragonBreath extends Weapon{
public static final int DAMAGE = 200;
public DragonBreath(){
super(DAMAGE, 0);
}
}
@@ -0,0 +1,10 @@
package org.project.item.weapons;
public class FireBall extends Weapon{
private static final int DAMAGE = 50;
private static final int MANA_COST = 8;
public FireBall() {
super(DAMAGE,MANA_COST);
}
}
@@ -0,0 +1,12 @@
package org.project.item.weapons;
public class LightSaber extends Weapon{ // xD
private static final int DAMAGE = 70;
private static final int MANA_COST = 9;
private String color; // color has no purpose at all, i just made it for fun.
public LightSaber(String color){
this.color = color;
super(DAMAGE,MANA_COST);
}
}
@@ -4,23 +4,13 @@ import org.project.entity.Entity;
import java.util.ArrayList;
// TODO: UPDATE IMPLEMENTATION
public class Sword {
/*
THIS IS AN EXAMPLE OF A WEAPON DESIGN.
*/
public class Sword extends Weapon {
int abilityCharge;
private static final int DAMAGE = 60;
private static final int MANA_COST = 8;
public Sword() {
// TODO: DESIGN SWORD'S ATTRIBUTES IMPLEMENT THE CONSTRUCTOR
super(DAMAGE,MANA_COST);
}
// TODO: (BONUS) UPDATE THE UNIQUE ABILITY
public void uniqueAbility(ArrayList<Entity> targets) {
abilityCharge += 2;
for (Entity target : targets) {
target.takeDamage(getDamage());
}
}
}
@@ -1,24 +1,12 @@
package org.project.item.weapons;
import org.project.entity.Entity;
// TODO: UPDATE IMPLEMENTATION
public abstract class Weapon {
private int damage;
private int manaCost;
/*
TODO: ADD OTHER REQUIRED AND BONUS ATTRIBUTES
*/
public Weapon(int damage, int manaCost) {
this.damage = damage;
this.manaCost = manaCost;
}
@Override
public void use(Entity target) {
target.takeDamage(damage);
public Weapon(int dmg, int mpCost) {
this.damage = dmg;
this.manaCost = mpCost;
}
public int getDamage() {
@@ -28,8 +16,4 @@ public abstract class Weapon {
public int getManaCost() {
return manaCost;
}
/*
TODO: ADD OTHER REQUIRED AND BONUS METHODS
*/
}
@@ -6,23 +6,44 @@ import java.util.ArrayList;
public class Location {
private String name;
private Enemy enemy;
private boolean playerInside = false;
private ArrayList<Enemy> enemies;
public Location(String name) {
this.name = name;
this.enemy = null;
}
public Location(ArrayList<Location> locations, ArrayList<Enemy> enemies) {
this.locations = locations;
this.enemies = enemies;
public Location(String name, Enemy enemy) {
this.name = name;
this.enemy = enemy;
}
public String getName() {
return name;
}
public ArrayList<Location> getLocations() {
return locations;
public Enemy getEnemy() {
return enemy;
}
public ArrayList<Enemy> getEnemies() {
return enemies;
public void setPlayerInside(boolean value){
playerInside = value;
}
public void setEnemy(Enemy enemy) {
this.enemy = enemy;
}
public boolean hasEnemy() {
return enemy != null && !enemy.isDead();
}
public boolean hasPlayer() {
return playerInside;
}
public void clearEnemy() {
this.enemy = null;
}
}
+89 -163
View File
@@ -1,175 +1,101 @@
# Fourth Assignment - Java Knight ⚔️
A turn-based RPG with Roguelike elements which can be run in the terminal.
### Legend of Advanced Programming
(please forgive for this stupid name although it's better than JAVA KNIGHT)
#### Description :
LAP is a simple TUI, rogue-like, turn-based game written in Java programming language
this is one of my assignments for AP course at SBU-CS bachelors degree.
#### Inspiration :
as i know this assignment is a tradition in this course and all of my seniors have done such assignment passing this course.
it's an assignment to test your OOP abilities therefore the game is developed object oriented.
### The lore
You are a warrior in *Javanest*, a town that is under attack of *The Dragon* and its minions.
you have to fight the minions in order to get *Minion Keys* (There is three of them : one for each minion).
Dragon lives in the castle that has a door with three lock, in order to unlock them you need all three keys.
### How to play
At first you choose your character. you have three choices :
1. The knight : A brave warrior with a strong armor and a sharp sword
2. The assassin : A powerful warrior with a Green light saber
3. The Wizard : A Warrior with fire balls!
### **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!*
after you made your choice you teleport into a random spot
every time ypu move to a spot a random enemy gets spawned.
after the enemy spawned you have three choices :
### **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**.
1. Stay at the spot and fight
2. Move to another spot
3. Go to the Castle and fight the Dragon
⚠️ **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.
>Note : option three is only available if you have all the keys (Keys drop randomly when you kill an Enemy.)
> otherwise you get a *Locked!* message.
🎯 **Your goal is not just to complete the assignment but to learn and apply OOP effectively!**
#### The combat
You have five options in the combat :
1. Light Attack (Free attack)
2. Heavy attack (MP Cost may vary based on the character)
3. Defend
4. Heal
5. Special ability
### **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.
#### Warriors special abilities :
### **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.
| Warrior | Special Ability | Effect |
|-------------|-----------------|--------|
| Knight | Shield Bash | Stun enemy + heavy damage |
| Assassin | Invisibility | Dodge + guaranteed critical hit |
| Wizard | Life Steal Spell | Damage enemy + heal |
---
#### Minions special abilities :
## Tasks 📝
| Minion | Ability | Description |
|------------|---------|-------------|
| Goblin | Critical Strike | 80% chance to crit |
| Skeleton | Resurrection | Revives once with 50% HP |
| Vampire | Life Steal | Drains health from player |
| Dragon | Fiery Breath | Ignores defense, unblockable |
### 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
#### End Gane
Once you defeat the dragon the Javanest gets freed and you win the game.
### Object orientation description
any Entity we have discussed obeys from a class hierarchy structure :
```Class Hierarchy
Entity (abstract)
├── Player (abstract)
│ ├── Knight
│ ├── Assassin
│ └── Wizard
└── Enemy (abstract)
├── Goblin
├── Skeleton
├── Vampire
└── Dragon
```
2. Create a new branch named `develop` and switch to it.
```bash
git checkout -b develop
Items do the same only difference being there is no parent class/interface for items :
```Class Hierarchy
Items (not a Parent class/Interface)
├── Weapon (abstract)
│ ├── Bite (Vampire)
│ ├── Dagger (Goblin)
│ ├── DragonBreath (Dragon)
│ ├── FireBall (Wizard)
│ ├── LightSaber (Assassin)
│ └── Sword (Knight)
└── Armor (abstract)
├── AssassinArmor
├── KnightArmor
└── WizardArmor
```
### 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]
---
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
if you use IntelliJ or Eclipse IDE you can clone the repo and just run Main.java
otherwise you have two approaches :
1. Painfully compile every class
2. Use the JAR build :
```Powershell/Shell
git clone https://github.com/farnam-jhn/Legend-of-AP
cd Legend-of-Ap
java -jar out/artifacts/HW_04_JAVA_KNIGHT.jar
```
```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).
### 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).
---
## Evaluation Criteria ⚖
| **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** |
## 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.
## 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.
![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.
+31
View File
@@ -0,0 +1,31 @@
### Headache : A critique of the project design (Optional to read)
At first i thought this is just another simple assignment like the rest, however as i started working with it i stepped upon a tangled design.
the irony is the fact that TA team allowed changing the design structure indicating they knew the flaws.
#### Flaws :
- First of all,
there is literally no game available in the market in which the NPCs have Mana system. like what do you think a NPC does when it ran out of mana?
will it just stand there and look at you and wait for it destiny?
- Second,
how player should have two attack styles (lightAttack and heavyAttack), if the Entity interface only provides one attack style?
to implement such mechanic you either have to implement two methods for two attack styles in Entity interface which doesn't make sense as Enemies should only have one attack style,
or you can just delete attack completely and implement it based on the entity instance.
The attack method situation was just an example, methods like "defend" ,"fillMana" and "getMaxMP" follow the same story. none of them is usable for Enemy class.
This whole situation and entanglement only defeats the purpose of class hierarchy which is code redundancy and code reusability.
- Third and the most important,
the whole concept of a text-based RougeLike game just don't make sense, for the upcoming years
it would be much more logical to call it a "Card Game" as the follwing
### The actual report
i simply changed anything i complained about in first section (Nah you can't get away without reading that!)
#### Just one more moment...
i changed Entity from interface to abstract since i had problems with Player and Enemy sub-classes (idk if it was my language server issue or it was an actual problem).
actual features of the game are in [README.md](README.md)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB