Complete text-based RPG game with combat, leveling, and classes

This commit is contained in:
2026-06-06 18:33:00 +03:30
parent 78d4bedb08
commit e171d9e3c3
52 changed files with 1172 additions and 337 deletions
+10
View File
@@ -0,0 +1,10 @@
# Default ignored files
/shelf/
/workspace.xml
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="Java-Knight" />
</profile>
</annotationProcessing>
</component>
</project>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://maven.devneeds.ir/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="25" project-jdk-type="JavaSDK" />
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Java-Knight.iml" filepath="$PROJECT_DIR$/Java-Knight.iml" />
</modules>
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="AdditionalModuleElements">
<content url="file://$MODULE_DIR$" dumb="true">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
</component>
</module>
+318 -5
View File
@@ -1,15 +1,328 @@
package org.project;
import org.project.location.Location;
import org.project.entity.enemies.*;
import org.project.entity.players.*;
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<>();
// TODO: IMPLEMENT GAMEPLAY
private static final String RESET = "\u001B[0m";
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 boolean gameRunning = true;
static List<Location> locations = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
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);
boolean isRunning = true;
while (isRunning){
System.out.println(YELLOW + "------------------Java knight------------------" + 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);
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");
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;
};
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("--DRAGON FIGHT--" );
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." + YELLOW + " Go to castle and fight with the dragon" + RESET);
}
else {
System.out.println(" \uD83D\uDD12" + BLUE + "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()) {
playerTurn(player, enemy);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (enemy.isDead()) {
break;
}
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();
}
}
}
@@ -3,19 +3,19 @@ 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();
public abstract boolean isDead();
public abstract boolean isCritical();
public abstract void makeCritical(boolean value);
public abstract boolean isStunned();
public abstract void stun(boolean value);
int getMaxMP();
/*
TODO: ADD OTHER REQUIRED AND BONUS METHODS
*/
}
@@ -0,0 +1,25 @@
package org.project.entity.enemies;
import org.project.entity.players.Player;
public class Dragon extends Enemy{
private static int HP = 500;
private static int fire = 60;
public Dragon () {
super (HP , fire);
}
@Override
public String getName() {
return "Dragon";
}
@Override
public void specialAbility(Player target) {
target.breakShield();
target.takeDamage(fire);
}
}
@@ -1,34 +1,93 @@
package org.project.entity.enemies;
import org.project.item.weapons.Weapon;
import org.project.entity.Entity;
import org.project.entity.players.Player;
// TODO: UPDATE IMPLEMENTATION
public abstract class Enemy {
Weapon weapon;
public abstract class Enemy implements Entity {
private int hp;
private int mp;
private boolean stunned = false;
private boolean critical = false;
private boolean dead = false;
private int enemyDamage;
public Enemy(int hp, int mp, Weapon weapon) {
private static double Damagemodifier = 1.5;
public Enemy(int hp, int enemyDamage) {
this.hp = hp;
this.mp = mp;
this.enemyDamage = enemyDamage;
}
this.weapon = weapon;
public void attack(Entity target){
if (critical){
target.takeDamage((int)(enemyDamage * Damagemodifier));
}
else {
target.takeDamage(enemyDamage);
}
}
@Override
public void takeDamage(int damage) {
hp -= damage;
if (hp <= 0){
hp = 0;
makeDie();
}
}
public void makeDie() {
dead = true;
}
public int getHp() {
return hp;
}
public void setHp(int newHp) {
hp = newHp;
}
public int getMp() {
return mp;
}
public Weapon getWeapon() {
return weapon;
@Override
public boolean isCritical(){
return critical;
}
@Override
public void makeCritical(boolean value) {
critical = value;
}
@Override
public boolean isStunned() {
return stunned;
}
@Override
public void stun(boolean value) {
stunned = value;
}
@Override
public boolean isDead() {
return dead;
}
@Override
public void heal(int health) {
hp += health;
}
public abstract String getName();
public abstract void specialAbility(Player target);
}
@@ -0,0 +1,36 @@
package org.project.entity.enemies;
import java.util.Random;
import org.project.entity.Entity;
import org.project.entity.players.Player;
public class Goblin extends Enemy{
private static int HP = 80;
private static int goblinDamage = 20;
public Goblin () {
super(HP , goblinDamage);
}
@Override
public void specialAbility(Player target) {
this.criticality();
super.attack(target);
}
@Override
public String getName() {
return "Goblin";
}
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.Entity;
import org.project.entity.players.Player;
public class Skeleton extends Enemy {
private static int HP = 100;
private int deathCounter = 0;
private static int skeletonDamage = 30;
public Skeleton(){
super(HP,skeletonDamage);
}
@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,27 @@
package org.project.entity.enemies;
import org.project.entity.Entity;
import org.project.entity.players.Player;
public class Vampire extends Enemy{
private static int HP = 200;
private static int vampierDamage = 40;
public Vampire () {
super(HP , vampierDamage);
}
@Override
public String getName() {
return "Vampire";
}
@Override
public void specialAbility(Player target) {
System.out.println("Stealing life!...");
target.takeDamage(vampierDamage);
this.heal((vampierDamage * 70) / 100);
}
}
@@ -0,0 +1,43 @@
package org.project.entity.players;
import org.project.entity.Entity;
import org.project.item.armors.AssasinArmor;
import org.project.item.weapons.Knife;
import org.project.item.weapons.Weapon;
import org.project.item.armors.Armor;
public class Assassin extends Player{
private static int Maxhp = 300;
private static int Maxmp = 50;
private static int SpecialabilitymanaCost = 10;
public Assassin(String name){
super(name,Maxhp,Maxmp,new Knife(),new AssasinArmor(),Maxhp,Maxmp);
}
@Override
public void specialAbility(Entity target) {
if (getMp() < SpecialabilitymanaCost) {
System.out.println("Not enough mana!");
return;
}
System.out.println("Turning invisible...");
this.defend();
this.makeCritical(true);
fillMana(-SpecialabilitymanaCost);
}
@Override
public int specialAblMPCost() {
return SpecialabilitymanaCost;
}
}
@@ -1,6 +1,45 @@
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 int Maxhp = 400;
private static int Maxmp = 40;
private static int SpecialabilitymanaCost = 20;
public Knight(String name) {
super(name,Maxhp,Maxmp,new Sword(),new KnightArmor(),Maxhp,Maxmp);
}
@Override
public void specialAbility(Entity target) {
if (getMp() < SpecialabilitymanaCost) {
System.out.println("Not enough mana!");
return;
}
System.out.println("Performing shield bash...");
target.stun(true);
target.takeDamage(50);
fillMana(-SpecialabilitymanaCost);
System.out.println(name + " used Shield Bash!");
System.out.println(" is stunned!");
}
@Override
public int specialAblMPCost() {
return SpecialabilitymanaCost;
}
}
@@ -4,50 +4,178 @@ import org.project.entity.Entity;
import org.project.item.armors.Armor;
import org.project.item.weapons.Weapon;
// TODO: UPDATE IMPLEMENTATION
public abstract class Player {
public abstract class Player implements Entity {
protected String name;
Weapon weapon;
Armor armor;
protected Weapon weapon;
protected Armor armor;
private int hp;
private int maxHP;
private int mp;
private int maxMP;
private int experiencePoint = 0;
private int xpToNextLevel = 100;
private int level = 1;
private boolean stunned = false;
private boolean defending = false;
private boolean critical = false;
private boolean dead = false;
private boolean hasGoblinKey = false;
private boolean hasVampKey = false;
private boolean hasSkelKey = false;
public Player(String name, int hp, int mp, Weapon weapon, Armor armor) {
private static double Damagemodifier = 1.5;
private static int Lightattackdamage = 20;
protected static int Defendmpcost = 5;
protected static int Healmpcost = 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.weapon = weapon;
this.armor = armor;
this.maxHP = maxHP;
this.maxMP = maxMP;
}
@Override
public void attack(Entity target) {
target.takeDamage(weapon.getDamage());
lightAttack(target);
}
public void lightAttack(Entity target)
{
if (critical){
target.takeDamage((int)(Lightattackdamage * Damagemodifier));
this.makeCritical(false);
}
else {
target.takeDamage(Lightattackdamage);
}
}
public void heavyAttack(Entity target){
int cost = weapon.getManaCost();
if (mp < cost) {
System.out.println("Not enough MP!");
return;
}
mp -= cost;
int damage = weapon.getDamage();
if (critical){
damage = (int)(damage * Damagemodifier);
critical = false;
}
target.takeDamage(damage);
}
@Override
public void defend() {
// TODO
if (mp < Defendmpcost) {
System.out.println("Not enough MP!");
return;
}
mp -= Defendmpcost;
defending = true;
System.out.println("Defending");
}
public void breakShield(){
if (defending){
defending = false;
System.out.println("Shield broken");
}
}
@Override
public void takeDamage(int damage) {
hp -= damage - armor.getDefense();
if (defending) {
System.out.println("Defended the attack.");
defending = false;
return;
}
int finalDamage = damage;
if (armor != null && !armor.isBroke()) {
finalDamage = Math.max(0, damage - armor.getDefense());
armor.use();
}
hp -= finalDamage;
if (hp <= 0) {
hp = 0;
dead = true;
}
}
@Override
public void heal(int health) {
if (mp < Healmpcost) {
System.out.println("Not enough MP!");
return;
}
mp -= Healmpcost;
hp += health;
if (hp > maxHP) {
hp = maxHP;
if (hp > maxHP) hp = maxHP;
}
public void gainXP(int amount){
this.experiencePoint += amount;
System.out.println("Gained " + amount + " XP.");
while (experiencePoint >= xpToNextLevel){
levelUp();
}
}
@Override
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 makeCritical(boolean value) {
critical = value;
}
public void fillMana(int mana) {
mp += mana;
if (mp > maxMP) {
@@ -55,35 +183,112 @@ public abstract class Player {
}
}
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;
}
public void setHp(int hp){
this.hp = hp;
}
public String getName() {
return name;
}
public int getHp() {
return hp;
}
@Override
public int getMaxHP() {
return maxHP;
}
public int getMp() {
return mp;
}
@Override
public int getMaxMP() {
return maxMP;
}
public Weapon getWeapon() {
return weapon;
}
public Armor getArmor() {
return armor;
}
}
public boolean defending() {
return defending;
}
public boolean isDead() {
return dead;
}
public boolean isStunned() {
return stunned;
}
@Override
public boolean isCritical(){
return critical;
}
public boolean hasGoblinKey(){
return hasGoblinKey;
}
public boolean hasSkelKey() {
return hasSkelKey;
}
public boolean hasVampKey() {
return hasVampKey;
}
public boolean hasAllKeys(){
return (hasSkelKey && hasVampKey && hasGoblinKey);
}
public abstract void specialAbility(Entity target);
public void stun(boolean value) {
stunned = value;
}
public abstract int specialAblMPCost();
}
@@ -0,0 +1,41 @@
package org.project.entity.players;
import org.project.entity.Entity;
import org.project.item.armors.Cloak;
import org.project.item.weapons.Wand;
import org.project.item.weapons.Weapon;
import org.project.item.armors.Armor;
public class Wizard extends Player {
private static int Maxhp = 500;
private static int Maxmp = 45;
private static int SpecialabilitymanaCost = 15;
public Wizard (String name) {
super(name,Maxhp,Maxmp,new Wand(),new Cloak(),Maxhp,Maxmp);
}
@Override
public void specialAbility(Entity target) {
if (getMp() < SpecialabilitymanaCost) {
System.out.println("Not enough mana!");
return;
}
System.out.println("Casting spell...");
target.takeDamage(40);
this.heal(20);
fillMana(-SpecialabilitymanaCost);
}
@Override
public int specialAblMPCost() {
return SpecialabilitymanaCost;
}
}
@@ -1,42 +1,45 @@
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 use(){
durability -= durabilityCost;
System.out.println("Used Armor.");
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;
}
}
@@ -0,0 +1,11 @@
package org.project.item.armors;
public class AssasinArmor extends Armor{
private static int Durability = 75;
private static int Defense = 20;
private static int Defensecost = 25;
public AssasinArmor(){
super(Defense,Durability,Defensecost);
}
}
@@ -0,0 +1,11 @@
package org.project.item.armors;
public class Cloak extends Armor{
private static int Durability = 50;
private static int Defense = 15;
private static int Defensecost = 25;
public Cloak(){
super(Defense,Durability,Defensecost);
}
}
@@ -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 int Durability = 100;
private static int Defense = 30;
private static int Defensecost = 25;
public KnightArmor(){
super(Defense,Durability,Defensecost);
}
}
@@ -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,15 @@
package org.project.item.weapons;
import org.project.entity.Entity;
import java.util.ArrayList;
public class Knife extends Weapon {
private static int Damage = 30;
public Knife() {
super(Damage, 5);
}
}
@@ -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 Manacost = 8;
public Sword() {
// TODO: DESIGN SWORD'S ATTRIBUTES IMPLEMENT THE CONSTRUCTOR
super(Damage,Manacost);
}
// TODO: (BONUS) UPDATE THE UNIQUE ABILITY
public void uniqueAbility(ArrayList<Entity> targets) {
abilityCharge += 2;
for (Entity target : targets) {
target.takeDamage(getDamage());
}
}
}
@@ -0,0 +1,16 @@
package org.project.item.weapons;
import org.project.entity.Entity;
import java.util.ArrayList;
public class Wand extends Weapon {
private static int Damage = 50;
private static int Manacost = 8;
public Wand() {
super(Damage,Manacost);
}
}
@@ -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
*/
}
@@ -2,27 +2,52 @@ package org.project.location;
import org.project.entity.enemies.Enemy;
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;
}
}
Binary file not shown.
+50 -155
View File
@@ -1,175 +1,70 @@
# Fourth Assignment - Java Knight ⚔️
A turn-based RPG with Roguelike elements which can be run in the terminal.
# Java Knight - Turn-Based RPG Game
### **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!*
## Project Overview
### **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**.
This project is a simple turn-based RPG game written in Java.
The player can choose a character and fight different enemies such as Skeletons, Goblins, Vampires, and a final Dragon boss.
⚠️ **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.
The game focuses on basic object-oriented programming concepts like inheritance, abstraction, and interfaces.
---
## Tasks 📝
## Features
### 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 🌲
- Choose between different character classes:
- Knight
- Assassin
- Wizard
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]
- Turn-based combat system
- Different enemy types with unique behaviors
- HP and MP system for player and enemies
- Weapon and armor system
- Experience points (XP) and leveling up
- Special abilities for each character
- Simple map progression (Village, Forest, Castle)
---
Your Turn:
1. Light Attack | 2. Heavy Attack (-8 Mana) | 3. Defend (-6 Mana) | 4. Heal (-12 Mana) | 5. Shield Bash (-15 Mana)
```
## Game Mechanics
```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).
### Combat System
Each turn, the player can choose one action:
- Light Attack (no MP cost)
- Heavy Attack (uses MP)
- Defend (reduces incoming damage)
- Heal (restores HP but uses MP)
- Special Ability (strong attack with MP cost)
### 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).
Enemies also attack automatically after the player's turn.
---
## Evaluation Criteria ⚖
### Level System
- Players gain XP after defeating enemies
- After reaching a certain XP threshold, the player levels up
- Leveling up increases HP and MP
| **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.
### Items System
- Weapons increase attack power
- Armor reduces incoming damage and can break after repeated use
- Keys are collected by defeating specific enemies
## 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.
## Object-Oriented Design
This project uses basic OOP principles:
- **Encapsulation**: All player stats are private with getters/setters
- **Inheritance**: Different player classes extend the base Player class
- **Polymorphism**: Enemies and players share the Entity interface
- **Abstraction**: Abstract Player class defines shared behavior
---
## Conclusion
In this project, I was able to build a simple text-based RPG game using basic Java concepts such as classes, inheritance, and interfaces. Through this project, I learned how different game mechanics like combat, leveling up, and inventory systems can be implemented using object-oriented programming.