I hope this isn't too amateurish for you guys but I'm having a hard time creating a small text-based game in Java using objects. So far I've wrote classes for Player, Item(this will be for later use, for now I have simpler goals), Room, Inventory(again, for later use) and the Main Class. What should I use to keep track of my location? I want to go through locations back-and-forth like in Zork (example go north, go south etc.) I thought about using an ArrayList that would contain every location, but again this stumbles me even more. What I wrote so far:
class Player{
//int healthPoints; for later use
private String playerName;
public void setPlayerName(String playerNameParam)
{
playerName=playerNameParam;
}
public String getPlayerName(){
return playerName;
}
}
class Item{
private String itemName;
public void setItemName(String itemNameParam)
{
itemName=itemNameParam;
}
public String getItemName()
{
return itemName;
}
}
class ExitRoom{
}
class Room{
private String roomName;
public void setRoomName(String roomNameParam){
roomName=roomNameParam;
}
public String getRoomName(){
return roomName;
}
private String roomDescription;
public void setRoomDescription(String roomDescriptionParam){
roomDescription=roomDescriptionParam;
}
public String getRoomDescription(){
return roomDescription;
}
}
class Inventory{
private ArrayList<Item> items= new ArrayList<Item>();
public boolean findItem(String itemToFind)
{
for(int i=0;i<items.size();i++){
if(items.get(i).getItemName()==itemToFind){
return true;
}
}
return false;
}
}
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
Player player = new Player();
boolean gameRunning=true;
while(gameRunning){
System.out.println("Welcome to TextBasedGamev1!"
+ "Before beginning, please enter your name");
String name=scanner.nextLine();
player.setPlayerName(name);
Room forestWelcome=new Room();
Room forestSouth=new Room();
Room forestNorth=new Room();
Room abandonedHouse=new Room();
}
Any help is really appreciated!
A possible approach (not necessarily the best) would be to store in each room the connections to other rooms. For example:
enum Direction {
NORTH, SOUTH, EAST, WEST;
}
class Room {
private Map<Direction, Room> connections;
...
}
Generally the aproach is using a matrix with each cell and a Point to mark the position of the player, for example
Class Map {
private Room[][] matrix;
private Player player;
...
}
class Player{
private Point position;
....
}
Text adventures are actually state machines.
You might want to look at the 3 free chapters of the book I've been writing on Artificial Intelligence in C# for Games, as it covers this and Java and C# are quite similar.
http://unseenu.wikispaces.com/Game+AI+in+C-Sharp
Related
What is the advantage if we make object as static? Seeking detailed explanation !!
Well you can make a Variable static, and this Var is refering to an Object, Why would it be good? well a static means that it will be visible to all aplication (well also depends of its package visibility, public, protected, default, private)
Why would be good? well maybe you're creating an "static object" in order to use it in diferent objects for example a game, look i made one ("of course it is an example")
public class Dummy {
static Player player = new Player("Yussef");
public static void main(String[] args) {
stageOne();
satageTwo();
}
static void stageOne(){
System.out.println("Ready? Go");
System.out.println(player);
System.out.println("Ouch an enemy hit me");
player.setLife(80);
System.out.println(player);
}
static void satageTwo(){
System.out.println("Good, now you're in next level");
System.out.println(player);
System.out.println("Ouch an enemy hit me");
System.out.println("Ouch an enemy hit me");
player.setLife(40);
System.out.println(player);
}
}
class Player{
private String name;
private int life;
Player(String name){
this.name = name;
life = 100;
}
#Override
public String toString() {
return "My name is: "+name+" And mi actual life is: "+life;
}
public void setLife(int life) {
this.life = life;
}
}
Now Imagine inspite of using the same class, i would've made more Clases, or more players, well the poit is this: My player will have the same life in all my game, and same name, so no matter what stage i play i will have the same attributs or changed them maybe ;).
It is an example i thought, hope it could help u
I am relatively new to Java and as a newbie I have trouble understanding how the code works or executes. Most often I've figured out the answer in a minute or two, sometimes in an hour or two. However, I've been stuck for two days now and I'm afraid I can't work out the problem on my own.
The programming exercise that I'm currently working on is nearly finished, save for one bit that isn't working right: method setMaxSize doesn't seem to work the way it should. I've tried to edit the method addPlayer to make a IF-statement concerning the team's max size and current size. However, the method does not add players to the list, regardless of the fact that the team list is empty at the moment. What did I do wrong? Where's my mistake? How can I get the IF-statement in addPlayer to accept new players in an empty list while checking for the maximum possible number of players in team?
I'd appreciate any feedback I can get and I apologize if it's a noobish question, but I'm really running out of patience here. Also, it's not homework: it's a programming exercise I found online from a university website I found, but I have trouble finishing it.
I'm including the two class files and the main field.
import java.util.ArrayList;
public class Team {
private String name;
private ArrayList<Player> list = new ArrayList<Player>();
private int maxSize;
public Team (String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void addPlayer(Player player){
if (list.size() <= this.maxSize){
this.list.add(new Player(player.getName(), player.goals()));
}
}
public void printPlayers(){
for (Player player : list){
System.out.println(player.toString());
}
}
public void setMaxSize(int maxSize){
this.maxSize = maxSize;
}
public int size(){
return this.list.size();
}
public int goals(){
int goalSum = 0;
for (Player player : list){
goalSum+=player.goals();
}
return goalSum;
}
}
public class Main {
public static void main(String[] args) {
Team barcelona = new Team("FC Barcelona");
Player brian = new Player("Brian");
Player pekka = new Player("Pekka", 39);
barcelona.addPlayer(brian);
barcelona.addPlayer(pekka);
barcelona.addPlayer(new Player("Mikael", 1));
System.out.println("Total goals: " + barcelona.goals());
}
}
public class Player {
private String name;
private int goal;
public Player(String name){
this.name = name;
}
public Player(String name, int goal){
this.name = name;
this.goal = goal;
}
public String getName(){
return this.name;
}
public int goals(){
return this.goal;
}
public String toString(){
return "Player: " + this.name + ", goals " + this.goal;
}
}
You need to call setMaxSize before adding players to the team.
As you have said before, you are never calling setMaxSize, so there is maxSize is initially 0. Additionally, I suggest making setters and getters for all your data fields in each class, and making each field private.
For example, you have a setter for maxSize, but not getter. It doesn't make much sense to do one but not the other, right? You create better encapsulation and allow for future changes of your code much easier this way, and again it is better practice for future projects.
I was working on a part of an in-house library today and wanted to improve some things by adding basic generics to our "Game" class.
Here is the stripped down version of the, now changed, game class:
public abstract class Game<G extends GamePlayer> {
private final List<G> players;
public Game() {
this.players = new LinkedList<>();
}
public Collection<G> getPlayers() {
return players;
}
}
Pretty standard, I know. But when I wanted to use the getPlayers() method in a game module like this: for (GamePlayer player : game.getPlayers()) All it gave me was an error that the return type equals "Collection<Object>" instead of "Collection<G>".
All other functions I have (like G getPlayer(String name)) return the correct type, but not the getPlayers function.
I really want to avoid implementations of this library cast their players to things like
MyGamePlayer player = (MyGamePlayer) myGame.getPlayer("dummy").
What did I do wrong with the generics?
Edit:
Here is the class that contains the for loop:
public class GiftTask implements Runnable {
private final Game game;
private final Item[] items;
public GiftTask(Game game, List<Item> itemList) {
this.game = game;
this.items = itemList.toArray(new Item[itemList.size()]);
}
#Override
public void run() {
for (GamePlayer player : game.getPlayers()) { // This line has the error
player.getInventory().addItem(items);
}
}
}
you should use this:
private final Game<GamePlayer> game;
you're using the raw type of Game.
I have a Java program that creates Swords. Now, I want to store the damagevalue and name of these Swords in a text file, and be able to read these values later. What is the best way to do that?
I have two classes:
Sword.java and NewSword.java, where NewSword.java is the function to create a new sword (o.O). Here's the code:
Sword.java:
package game;
public class Sword {
public static int numberOfSwords=0;
public static void main(String [] args){
functions.NewSword.newSword("Wooden Sword", 2);
System.out.println(numberOfSwords);
}
}
and
NewSword.java:
package functions;
public class NewSword {
public static void newSword(String nameSword, int damageSword){
game.Sword.numberOfSwords++;
}
}
So:
I wish to be able to, in the function newSword(String nameSword, int damageSword), put the nameSword and the damageSword in a text file, and be able to read that... So that I can later do like: "He has a wooden sword, what's the damage?"... I want to put it in a text file, because I want to know how that works, and practice with it. Also, I think it makes it easier if I want to add features to swords, and can put those in text files as well... Hope you can help me!
EDIT: I put the function in another package, that's why it's functions.NewSword.newSword("Wooden Sword", 2);, just for the heck of it :D But also to be a bit organized...
Read throught this: http://www.tutorialspoint.com/java/java_files_io.htm
It explains everything in from creating a file to reading it and will sure help you out.
However regard kviiris commend about learning something about object oriented programming.
Heres the basic approach for your swords:
You write a class for your sword that contains all the information you need for a given sword.
public class Sword {
private String name;
private int damage;
// this is the constructor to create new swords
public Sword(String name, int damage){
this.name = name;
this.damage = damage;
}
}
Now you can access this from your main class and use it to create as many swords as you want simply with
Sword s = new Sword("wooden sword", 2);
Sword s2 = new Sword("iron sword", 20);
Note: you used the same class (Sword) but this are still 2 completely separate swords.
Thats the main use of object oriented programming.
This will compile.
Game.java
package game;
import functions.Sword;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Game {
List<Sword> swords = new ArrayList<Sword>();
public static void main(String[] args) {
Game game = new Game();
game.play();
}
public void play() {
swords.add(new Sword("Wooden sword", 2));
swords.add(new Sword("Silver sword", 4));
System.out.println(swords.size());
System.out.println(Arrays.toString(swords));
}
}
Sword.java
package functions;
public class Sword {
private final String name;
private final int damage;
public Sword(String name, int damage) {
this.name = name;
this.damage = damage;
}
public String getName() {
return name;
}
public int getDamage() {
return damage;
}
}
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I am writing a class to represent cricket players. There are four types of cricket players
1 wicket player
2 batsman
3 bowler
4 allrounder
I'm not sure if I am representing the players in the right way
public class Player {
final static int WICKETPLAYER=1;
final static int BATSMAN=2;
final static int BOWLER=3;
final static int ALLROUNDER=4;
int currentbatting;
int bowlerbating;
int playertype;
public Player(int i,int currentbatting){
this.currentbatting=currentbatting;
playertype=i;
}
public String whatTypeOFplayer(){
switch(playertype){
case WICKETPLAYER:
return "wicketplayer" ;
case BATSMAN:
return " batsman";
case BOWLER:
return "bowler";
case ALLROUNDER:
return "allrounder";
default:
return "error";
}
}
}
First of all, you should use enums to represent the player types instead of ints, like
enum PlayerType {
WICKETPLAYER,
BATSMAN,
BOWLER,
ALLROUNDER
}
Then you could use the name() method to get a string representation of the PlayerType.
If there's more to the player types that just the name (e.g. different behaviour, methods etc.), you might consider creating subclasses of Player, like class WicketPlayer extends Player.
A third way would be to use composition and add components like PlayerBehaviour etc. to the basic player class.
I terms of complexity, I'd say no. 1 is the easiest, whereas no. 3 might be too complex for you right now. So you might try and either use no. 1 or no. 2, depending on your requirements.
You are likely to be better off with an enum and an EnumSet.
public Role {
WICKET_KEEPER, BATSMAN, BOWLER, FIELDER
}
public static final Set<Role> ALL_ROUNDER = EnumSet.allOf(Role.class);
private final EnumSet<Role> roles;
private Role position;
public Player(EnumSet<Role> roles) { this.role = roles; }
public void setPosition(Role role) { this.position = role; }
public String whatTypeOFplayer(){
return roles.equals(ALL_ROUNDER) ? "allrounder" : roles.toString();
}
BTW Its a Wicket Keeper not a Wicket Player http://www.cricketscotland.com/system/files/images/13_13.jpg
A better way is to inherit from the class Player, it will allow you a simpler treatment for each player and different behaviors for common actions. for example:
Player.java
public class Player {
int currentbatting;
int bowlerbating;
int playertype;
public Player(int i,int currentbatting){
this.currentbatting=currentbatting;
playertype=i;
}
public abstract String whatTypeOFplayer() {
return playertype;
}
}
WicketPlayer.java
public WicketPlayer extends Player {
public WicketPlayer(int i,int currentbatting){
super(int i,int currentbatting);
playertype = "wicketplayer";
}
}
Batsman.java
public Batsman extends Player {
public Batsman(int i,int currentbatting){
super(int i,int currentbatting);
playertype = "batsman";
}
}
And so on.
use Java Enums: http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
In this case - and because I smell homework - you should use one base class Player and a subclass for each player type.
Example:
public abstract class Player {
// some attributes and methods all players share
public abstract String whatTypeOfPlayer();
}
public WicketPlayer extends Player {
#Override
public String whatTypeOfPlayer() {
return "Wicket Player";
}
}
Bonus - then I'd use a factory to create players:
public PlayerFactory {
enum PlayerType {WICKETPLAYER, BATSMAN, BOWLER, ALLROUNDER}
public static Player createPlayer(PlayerType type, String name) {
switch(type) {
case WICKETPLAYER : return new WicketPlayer(name);
//...
}
}
}
If you are using Java 5+ use Enum Types Java Enum Types. According to Effective Java it's not a good practice to use a bunch of constants, instead use Enum.
public class Player {
public enum Role{
WICKETPLAYER,
BATSMAN,
BOWLER,
ALLROUNDER;
}
final int currentbatting;
final Role playerRole;
public Player(final Role role, final int currentbatting){
this.currentbatting=currentbatting;
this.playerRole=role;
}
public String whatTypeOFplayer(){
return this.playerRole.toString();
}
}