Implementing a simple text adventure game in java (working with interfaces) - java

I was doing some reading on ECS/Composition over inheritance and decided to modify a text adventure game that I'm currently working on to better understand the concept.
I decided to try it using a specific weapon in my game.
Now, in my game the logic is that every Weapon is considered an IGameObject. With all this in mind I came up with the following:
Weapon Interface:
public interface IWeapon {
int getWeaponDamage();
}
Weapon class:
public class Weapon implements IWeapon {
private int damage;
public Weapon(int damage)
{
this.damage = damage;
}
#Override
public int getWeaponDamage() {
return this.damage;
}
IGameObject interface:
public interface IGameObject {
String getGameObjectID();
String getGameObjectName();
String getGameObjectDescription();
}
GameObject class:
public class GameObject implements IGameObject {
private String ID;
private String name;
private String Desc;
public GameObject(String ID, String name, String Desc)
{
this.ID = ID;
this.name = name;
this.Desc = Desc;
}
The abstract class that uses all this:
public abstract class GameGun implements IGameObject, IWeapon {
IGameObject gameObj;
IWeapon weaponObj;
//Left out getters to keep it simple and easy to read.
public GameGun(IGameObject game, IWeapon weapon)
{
this.gameObj = game;
this.weaponObj = weapon;
}
public void fire()
{
System.out.println("Shot Fired");
}
public void reload()
{
//implementation for reload method
}
Putting it all together:
Main Method:
GameObject sleep = new GameObject("SLP-1","Sleep Weapon","A Custom Made Gun");
Weapon sleepDamage = new Weapon(10);
GameGun sleepWeapon = new SleepWeapon(sleep,sleepDamage);
Questions:
I just wanted to know if my implementation was correct?
If not, how would I correct it?

I've been correcting many stuff and get it working. You can play with it now :D
PLease take the gist in order to have all the working code.
CONSOLE
Revolver Gun:Gun reloaded
Revolver Gun:Gun shots => 10 damage(s)
Basic Sword:Sword cuts => 5 damage(s)
Basic Sword:Sword cuts => 5 damage(s)
Basic Sword:Sword cuts => 5 damage(s)
Revolver Gun:Gun shots => 10 damage(s)
CODE
package com.rizze.test.labs.sof.gamegun;
import org.junit.Test;
public class GameGunTest {
#Test
public void betterCode2() {
Game sleep = new Game("SLP-1","Sleep Weapon","A Custom Made Gun");
Gun gun = new Gun();
Sword sword = new Sword();
gun.hit();
sword.hit();
sword.hit();
sword.hit();
gun.hit();
}
public class Gun implements IWeapon {
private int damage;
private String name;
public Gun(int damage)
{
this.damage = damage;
this.reload();
}
public Gun()
{
this.damage = 10;
this.name= "Revolver Gun";
this.reload();
}
#Override
public int getDamages() {
return this.damage;
}
/**
*
* #return damages
*/
#Override
public int hit() {
System.out.println( this.name + ":Gun shots => "+damage +" damage(s)");
return this.damage;
}
#Override
public void reload() {
System.out.println(this.name+":Gun reloaded");
}
}
public class Sword implements IWeapon {
private String name;
private int damage;
public Sword(String name){
this.damage = 5;
this.name=name;
}
public Sword(){
this.damage = 5;
this.name="Basic Sword";
}
#Override
public int getDamages() {
return this.damage;
}
/**
*
* #return damages
*/
#Override
public int hit() {
System.out.println( name+ ":Sword cuts => "+damage +" damage(s)");
return damage;
}
#Override
public void reload() {
System.out.println( name+ ":Sword - skipped reload" );
}
}
public class Game implements IGame {
private String id;
private String name;
private String desc;
public Game(String ID, String name, String Desc)
{
this.id = ID;
this.name = name;
this.desc = Desc;
}
#Override
public String getId() {
return this.id;
}
#Override
public String getName() {
return this.getName();
}
#Override
public String getDesc() {
return this.desc;
}
}
}
//IGAME
public interface IGame {
String getId();
String getName();
String getDesc();
}
//IWEAPON
package com.rizze.test.labs.sof.gamegun;
public interface IWeapon {
int getDamages();
int hit();
void reload();
}
GIST
here is the complete GIST :https://gist.github.com/jeorfevre/92d093853bfd3fc5c666b915b309abf1

Related

UML with subclasses

public class Student {
private String name;
private long id;
private String grade;
private int[] test;
private int NUM_TESTS;
public Student(){
name="Un";
id=0;
grade="Un";
test=new int[0];
NUM_TESTS=5;
}
public Student(String x, long z) {
name=x;
id=z;
}
public void setName(String n) {
name=n;
}
public void setID(long i) {
id=i;
}
public void setGrade(String g) {
grade=g;
}
/*public void setTestScore(int t,int s) {
test=t;
test=s;
}
public int getTestScore(int) {
return test;
}*/
public int getNumTests() {
return NUM_TESTS;
}
public String getName() {
return name;
}
public long getID() {
return id;
}
public String getGrade() {
return grade;
}
public String toString() {
return getTestScore()+getNumTests()+getName()+getID()+getGrade();
}
/*public void calculateResult() {
int sum=0;
for (int t:test)sum+=t;
double average= 1.0t*sum/5;*/
}
}
Here is my code I have spaced out the places where I am having the issues. I am writing a Student subclass with subclasses undergrad and postgrad.
Here is the UML
I don't understand how to correctly implement testScore if it is not one of the variables? Nevermind the calculate result I'll fix that myself. I am also unsure if my constructors are accurate. All the students do five exams that's a constant
setTestScore(int t, int s)... I do recommend to use carefully chosen names (identifiers). For example if you just rename the parameters to: setTestScore(int testNumber, int score) you can be more familiar what should you inplement.
test = new int[0];isn't what you want. You want test = new int[NUM_TESTS]
Try to reconsider method setTestScore(int testNumber, int score)
first parameter is actually the index in the array of test and the second is the value.
So, your method should be something like this:
public void setTestScore(int testNumber, int score) {
test[testNumber] = score;
}
I just gave you some guidance for your own implementation...
First of all, It seems that Student class should be abstract. because each student is UnderGraduate or PostGraduate.
Secondly, you should extend the child classes from Student class.
I hope the below code be helpful:
abstract class Student {
private String name;
private long id;
private String grade;
private int[] test;
private final int NUM_TESTS = 5;
public Student(){
name = "UN";
id = 0;
grade = "UN";
test = new int[NUM_TESTS];
}
public Student(String name, long id){
this.name = name;
this.id = id;
}
#Override
public String toString() {
//TODO: write your desire toString method
return getNUM_TESTS()+getName()+getId()+getGrade();
}
abstract void claculateResult();
public int getTestScore(int testNumber){
if(testNumber >= NUM_TESTS)
return 0;
return test[testNumber];
}
public void setTestScore(int testNumber, int score){
if(testNumber >= NUM_TESTS)
return;
test[testNumber] = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public int[] getTest() {
return test;
}
public void setTest(int[] test) {
this.test = test;
}
public int getNUM_TESTS() {
return NUM_TESTS;
}
}
and the UnderGraduate class would be:
public class UnderGraduate extends Student{
public UnderGraduate(){
}
public UnderGraduate(String name, long id){
super();
}
#Override
void claculateResult() {
//TODO: DO whatever you want
}
}
remember that the PostGraduate class is same as UnderGraduate.

City cannot be converted to summable

So I'm supposed to use a "Summable" interface to add up the populations of the cities. I've been staring at it for an hour but still can't find my error. Please Help!
This is my tester
public class SummableTester extends ConsoleProgram
{
public void run()
{
City cookie = new City("Coookie", 20000);
City taco = new City("Taco", 10000);
System.out.println(taco.getValue());
}
}
City Class:
public class City
{
private String name;
private int population;
public City(String name, int population)
{
this.name = name;
this.population = population;
}
public String getName()
{
return this.name;
}
public int getValue()
{
return this.population;
}
public int add(Summable other)
{
return getValue() + other.getValue();
}
}
Summable:
public interface Summable
{
public int add(Summable other);
public int getValue();
}
You implemented Summable interface in your City class, but forgot to include implements Summable in city class.
public class City implements Summable {
}

Text-Based Game in Java. Need advice with Inventory Implementation and general coding advice

I'm having trouble figuring out how to deal with an Inventory for my text based java game. I just finished Data Structures and Algorithms, so I figured this would be a good project for my resume.
Currently, I create the inventory in the constructor of the player class. I would like to instantiate the inventory with 3 potion items, from the item class. I try to do that in the player constructor, but I can't figure out why its not working.
My question is, how should I go about instantiating every character with 3 potions in his/her inventory?
Player class:
package projectmoria;
import java.util.ArrayList;
import java.util.List;
public class Player {
private final String name;
private final String description;
private final int maxHitPoints;
private int hitPoints;
private final int minDamage;
private final int maxDamage;
private final int defense;
private double critChance;
private int currX;
private int currY;
private Room currRoom;
private List<Item> inventory;
public Player(String name, String description, int maxHitPoints,
int minDamage, int maxDamage, int defense, double critChance) {
this.name = name;
this.description = description;
this.maxHitPoints = maxHitPoints;
this.hitPoints = maxHitPoints;
this.minDamage = minDamage;
this.maxDamage = maxDamage;
this.defense = defense;
this.critChance = critChance;
this.currX = 14;
this.currY = 14;
inventory = new ArrayList<>();
inventory.add(Item.addPotion(3, this.player)); //This is the line I need help with
}
public int attack() {
return ProjectMoria.RAND.nextInt(maxDamage - minDamage + 1);
}
public int defend(Monster monster) {
int incomingAttack = monster.attack();
int random = ProjectMoria.RAND.nextInt(99) + 1;
if (random <= monster.getCritChance()) {
incomingAttack = incomingAttack * 2;
IO.monsterCrit(); //TODO - move to different spot
}
IO.playerHitPointsMessage(incomingAttack, monster);
hitPoints = (hitPoints * defense > incomingAttack)
? hitPoints - incomingAttack : 0;
return hitPoints;
}
public void heal(Item potion){
this.hitPoints =+ 20;
inventory.remove(potion);
IO.heal(this.hitPoints);
}
public static Player newWarrior() {
return new Player("Warrior", "A tough, well-rounded fighter with"
+ " a balanced skillset.", 100, 20, 30, 3, 10);
}
public static Player newDuelist() {
return new Player("Duelist", "A quick, nimble duelist with an"
+ " aptitude for landing critical attacks.", 8000, 10, 50, 2,
18);
}
public String getDescription() {
return description;
}
public int getHitPoints() {
return hitPoints;
}
public boolean isAlive() {
return hitPoints > 0;
}
public String getName() {
return name;
}
public int getMaxHitPoints() {
return maxHitPoints;
}
public int getMinDamage() {
return minDamage;
}
public int getMaxDamage() {
return maxDamage;
}
public int getDefense() {
return defense;
}
public double getCritChance() {
return critChance;
}
public int getCurrX() {
return currX;
}
public int getCurrY() {
return currY;
}
public List<Item> getInventory() {
return inventory;
}
public Room getCurrRoom() {
return currRoom;
}
public void setCurrRoom(Room room) {
currRoom = room;
}
public void setCurrX(int currX) {
this.currX = currX;
}
public void setCurrY(int currY) {
this.currY = currY;
}
}
Item class:
package projectmoria;
public class Item {
private final String name;
private final String type;
private final String description;
public Item(String name, String type, String description){
this.name = name;
this.type = type;
this.description = description;
}
public void use(Player player, Item item){
if(item.type.equals("Potion")){
player.heal(item);
}
}
public void addPotion(int numOfPotions, Player player){
for(int i = 0; i < numOfPotions; i ++){
player.getInventory().add(potion());
}
}
public Item potion(){
return new Item ("Potion", "Potion", " a small vial filled with a "
+ "translucent red liquid");
}
}
Actually in Player constructor :
inventory = new ArrayList<>();
inventory.add(Item.addPotion(3, this.player));
you are invoking :
public void addPotion(int numOfPotions, Player player){
This is an instance method.
You can invoke instance methods only on an instance.
Your addPotion() method looks like to be a factory method to create potion Items :
public void addPotion(int numOfPotions, Player player){
for(int i = 0; i < numOfPotions; i ++){
player.getInventory().add(potion());
}
}
public Item potion(){
return new Item ("Potion", "Potion", " a small vial filled with a "
+ "translucent red liquid");
}
So, you should do static addPotion() and potion() and it should solve your problem.
Besides, as potion() is only invoked by addPotion(), you can reduce it level access by making it private.
You have to change the addPotion(...) method as a static method, if you want to call that method as Item.addPotion(...)
I would strongly suggest to make your Item class as an Enum Enum java doc and add these enums into your player's inventory. These are tons of design considerations you should be thinking about. If you go with the enum design. You will force Items to be locked down to only a few types of Items and players share this item.
However if the Item is strongly coupled with your player, for example you want the Item to decrement every time a player uses the portion. Then simply make the method addPotion static.
public static void addPotion(...)

how to search recipe based on important ingredients ? java android

I want to search recipe which match with shopping list items and it will suggest recipe to user based on most important ingredients like in Banana MilkShake {milk and banana} could make banana milkshake alone {sugar and vanilla} are optional,if I add items on shopping list like {banana,milk} it will search recipe on the basis of these ingredients rather {banana,milk,sugar and vanilla}
for example:
Banana Milk Shake Ingredients:
**Ingredient Name
1.banana (important)
2.milk (important)
3.vanilla (optional/not important)
4.sugar (optional/not important)
**Shopping List**
banana
milk
egg
rice
We could also make Banana Milkshake without sugar and vanilla so important ingredients will be milk and banana.
public class Ingredient implements Serializable{
private String name;
private String quantity;
public Ingredient(){
}
public Ingredient(String name,String quantity){
this.name=name;
this.quantity=quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
}
and my working code:
public Set<Recipe> searchByIngredient(List<ShoppingList> shop, List<Recipe> list) {
int matchedItems = 0;
Set<Recipe> result = new HashSet<Recipe>();
for (Recipe rn : list) {
boolean recipeMatched = false;
for (ShoppingList r : shop) {
for (int i = 0; i < rn.getIngre().size(); i++) {
if (rn.getIng(i).contains(r.getName())) {
matchedItems++;
int temp = matchedItems;
if(temp >= 2){
result.add(rn);
recipeMatched = true;
}
}
if (recipeMatched)
break;
}
if (recipeMatched)
break;
}
matchedItems = 0;
}
return result;
}
public class Recipe implements Serializable{
private String instructions;
private String recName;
private String image;
private List<Ingredient> ing = new ArrayList<Ingredient>();
public Recipe(){
}
public Recipe(String item,String quan){
this.ing.add(new Ingredient(item, quan));
}
public List<Ingredient> getIngre(){
return ing;
}
public String getIng(int i){
return ing.get(i).toString();
}
public void setIngredients(List<Ingredient> item){
this.ing = item;
}
public String getRecName() {
return recName;
}
public void setRecName(String recName) {
this.recName = recName;
}
// #Override
public String toString() {
return recName;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
Based on your comments. You could add another variable to your Ingredient class. Like this:
public class Ingredient implements Serializable{
private String name;
private String quantity;
private boolean isImportant;
public Ingredient(){
}
public Ingredient(String name,String quantity){
this.name=name;
this.quantity=quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public boolean getIsImportant() {
return isImportant;
}
public void setIsImportant(boolean isImportant) {
this.isImportant= isImportant;
}
}
Then you could check in the recipe if all the important ingredients are present or not.

Creating an object and calling it

this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)

Categories

Resources