Java Basic Game [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm tryin to develop a small text-based fighting game and I'm using eclipse to help me out. I have two classes a Hero and Villian.
Hero Code so far:
public class Hero
{
// instance variables - replace the example below with your own
private int Health;
private int Punch;
private int Kick;
private int Special;
/**
* Constructor for objects of class Hero
*/
public Hero()
{
// initialise instance variables
Health = 100;
Punch = -30;
Kick = -25;
Special = -55;
}
Villian Code so far:
public class Villian
{
// instance variables - replace the example below with your own
private int Health;
private int Punch;
private int Kick;
private int Special;
/**
* Constructor for objects of class Villian
*/
public Villian()
{
// initialise instance variables
Health = 100;
Punch = -25;
Kick = -30;
Special = -50;
}
I want to make it turn-based as well so that when the hero attacks, it's the villian's turn. But I'm having trouble trying to construct a suitable method for the attacks. Can someone please help me with this?

The best way to solve this problem is to use inheritance.
You want to have one class called Entity which holds everything all things need on the game field:
public abstract class Entity {
private int Health;
private int attackDmg;
public Entity(int health, int attackDamage) {
this.health = health;
this.attackDamage = attackDamage;
}
}
Then the two classes you currently have simply inherent everything from Entity:
public class Hero extends Entity {
public Hero() {
super(100, 30);
}
}
and Villian:
public class Villian extends Entity {
public Villian() {
super(100, 20);
}
}
Now you probably want to have some methods that makes the Entity take damage. Because everybody should be able to take damage it comes into the Entity class. Also you probably want to have an attack method, that tells you how much damage the entities does:
public abstract class Entity {
// [...]
public void takeDamage(int damage) {
health -= dmg;
}
public void attack() {
return attackDamage;
}
}
Now you can write in your controller class (that handles all of the turn based logic):
player.takeDamage(villian.attack()); (Given that playeris your Playerand villian your Villian).
Of course this only is a small example, you could also make a method that take a String as an argument, which represents the method of the attack (like "kick" or "punch") and then return different amounts depending on the attack type.
Further infos to inheritance:
http://www.tutorialspoint.com/java/java_inheritance.htm and http://beginnersbook.com/2013/05/java-inheritance-types/
You might also be interested in a game making tutorial:
http://www.gametutorial.net/

You might take a variable like flag and set its value to 1 when hero's turn and its value to 0 when villan's turn
if(flag==1)
{
villans turn;
flag=0;
}
else if(flag==0)
{
heros turn;
flag=1;
}
This works

Related

Getting Variables From Java constructor

I'm new to Java programming, sorry if this is a dumb question.
I find it hard to word this question properly, but I have an assignment to create a aircraft class that can make aircraft land, takeoff etc. And need to test it using Testclass. When the new object are entered it automatically assigns a unique ID to the aircraft in the constructor.
I can do this using a instance method fine as it has a return value which is returned to to Testclass. The question wants me to do this in the constructor itself, however, the constructor never returns anything. So the variable never gets sent to the Testclass. I clearly am not understanding OOP properly. Even when I try to just use a getter method to get the ID created in the constructor it gives me the initialized variable before the the constructor has worked on this. This is the code I have so far and its completely wrong I know but if someone could point me in the right direction or tell me how to word this question better it would be a massive help.
// I need to enter 3 aircraft into the system in the testclass
public class Aircraft {
private int aircraftID;
private static int lastID;
private String airportcode;
private int ID = 100;
private int count;
public Aircraft(int a, int b, int c){
// Constructor
// Assign ID
this.ID = a;
lastID = ID;
ID++;
this.ID =b;
lastID = ID;
ID++;
}
}
OK, you want to create an Aircraft that has an automatically-assigned unique identifier, and can take off and land. That implies you need a field for tracking the identifier, a field for tracking whether it's in the air (or not), and methods for the take off and land operations. You also need a static field for generating the unique identifiers. (Note that this implementation isn't thread safe.)
private class Aircraft {
private static int staticId = 0;
private int uniqueId = 0;
private boolean onGround = true; // Aircraft start on the ground in this implementation
public Aircraft(){
this.uniqueId = staticId; // putting this line first makes uniqueId zero-indexed in effect
staticId++;
}
public void land(){
onGround = true;
}
public void takeoff(){
onGround = false;
}
public boolean isFlying(){
return !onGround; // If it's not on the ground, it's flying
}
public int getUniqueId(){
return uniqueId;
}
}
Unit tests checks all of the methods and expected functionality of the class in question:
import org.junit.Test;
import static org.junit.Assert.*;
import Aircraft;
class Testclass {
private final Aircraft aircraft = new Aircraft();
#Test
public void hasId(){
aircraft.getUniqueId() >= 0;
}
#Test
public void canLand(){
assertTrue(aircraft.land());
}
#Test
public void canTakeOff(){
assertTrue(aircraft.takeOff());
}
#Test
public void checkFlightOperationsAreTrackedCorrectly(){
aircraft.land();
assertFalse(aircraft.isFlying());
aircraft.takeOff();
assertTrue(aircraft.isFlying());
}
}
As pointed out a constructor does not return anything (the simplified version is that with new it returns an object instance). I am kinda guessing at what you are trying to acomplish, but I'll have a go anyways. It seems to me that you are trying to cram the construction of 3 objects into one constructor - which is why your constructor has 3 parameters. Also you are playing havoc with the IDs.
I have removed all the variables that I didnt quite understand, leaving only ID that increments with each instantiated Aircraft. The #Override is mainly just for show.
public class Aircraft {
private int aircraftID;
private static int lastID = 0;
#Override
public String toString(){
return "Aircraft_" + this.aircraftID;
}
public Aircraft() {
lastID++;
this.aircraftID = lastID;
}
}
I took the liberty and wrote the TestClass just to see if we have the same thing in mind. Again the printAircraft() method is for show.
public class TestClass {
private List<Aircraft> aircrafts;
public TestClass(){
aircrafts = new ArrayList<>();
}
public void addAircraft(Aircraft a){
aircrafts.add(a);
}
public void printAircraft(){
Iterator<Aircraft> it = aircrafts.iterator();
while(it.hasNext()){
System.out.println(it.next().toString());
}
}
}
and to test it, we create and instance of TestClass add 3 Aircraft instances and print out the contents
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.printAircraft();
}
This would be the case if you are to write the TestClass. If that is given, it would help to know what it looks like - maybe that would help us understand better.

Storing values from textfields in jframe class in a object in another class

I'm quite new to programming and java in general. I am currently a student and I'm trying to do a project outside of the classroom to make myself more proficient in java.
Currently, I am working on a text-based RPG where I am trying to create the main character, assign the basic skill points to the character and use that info throughout the game.
So far, I've made a jframe class where the user has 6 different skills with a base value of 1. The user can add or deduct a value from the certain skill with plus and minus buttons.
And here is where I got stuck. I don't know how to save these values to an object which can be used by other classes.
I would really appreciate any help I could get.
Thank you.
public class CharacterStatsGUI extends javax.swing.JFrame {
static int skill1 = 1;
static int skill2 = 1;
static int skill3 = 1;
static int skill4 = 1;
static int skill5 = 1;
static int skill6 = 1;
static int skillPoints = 10;
private void txthealthActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txthealth.setText(String.valueOf(skill1));
}
private void btnhpActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(skillPoints >= 1){
skill1++;
skillPoints--;
txthealth.setText(String.valueOf(skill1));
txtpoints.setText(String.valueOf(skillPoints));
}
else{
JOptionPane.showMessageDialog(null, "You dont have enough skills points");
}
}
private void btnhmActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(skillPoints >= 0 && skill1 > 1){
skill1--;
skillPoints++;
txthealth.setText(String.valueOf(skill1));
txtpoints.setText(String.valueOf(skillPoints));
}
else{
JOptionPane.showMessageDialog(null, "Minimum skill value is 1.");
}
}
There are more than one solution for this problem.
Not all of them are efficient, not all are beautiful, but if it is "to make yourself more proficient in java, it is good to know the various ways! Here's some options:
You can change static int skill1 = 1; with public static int skill1 = 1;, and thake that data by calling myCharacterStatsGUI.skill1.
Better than the firs option, you can make this int private and create some public methods like public int getSkill1, or public int getSkill(int numSkill) that returns the int value of the correct skill.
A lot of programmer suggest that the GUI shouldn't related with the data and so, you can create a class MainCharacter, that contains all the character values, skills included. This class must implements the option 2 methods.
Better than the third point, you can separate the MainCharacter class from its values, and store all the skills in a inner class Skills. When you want to pick up these values by calling a specific method. In the following code I want to show you this option:
public Class MainChar{
private Skills skills;
public MainChar(){
this.skills=new Skills();
}
/* Call it from your CharacterStatsGUI class,
in the method txthealthActionPerformed */
public void augmentSkill(){
skills.augment()
}
public int getHealt(){
return skills.getHealt();
}
private class Skills{
/*This example use only a skill, but
you can extend it with others values*/
private int health;
public Skills(){
health=1;
}
public void augment(){
health++;
}
public int getHealt(){
return health;
}
}
}

Design pattern using interface or abstract [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I am trying to calculate the print cost base on different paper size, single side or double side. So here is the detail:
Also need to support for other paper sizes will be added in the future.
And according to my design, developer can just create a A5 class for example to support other paper size, and add other condition in the factory class.
Could someone review my code and help me on whether I have to use interface instead of abstract class?
Here is my code:
PageBase:
public abstract class PageBase {
abstract double GetCost(int total, int color, boolean isSingleSide);
abstract void CalculateUnitPrice(boolean isSingleSide);
}
A4Page Class:
public class A4Page extends PageBase {
public double blackAndWhitePrintUnitCost;
public double colorPrintUniCost;
#Override
public double GetCost(int total, int color, boolean isSingleSide) {
CalculateUnitPrice(isSingleSide);
return color* colorPrintUniCost + (total-color)* blackAndWhitePrintUnitCost;
}
#Override
public void CalculateUnitPrice(boolean isSingleSide) {
if (isSingleSide) {
this.blackAndWhitePrintUnitCost = 0.15;
this.colorPrintUniCost = 0.25;
}
else {
this.blackAndWhitePrintUnitCost = 0.10;
this.colorPrintUniCost = 0.20;
}
}
}
PageFactory:
public class PageFactory {
public PageBase GetPage(String pageType) {
switch (pageType.toUpperCase()) {
case "A4":
return new A4Page();
default:
return new A4Page();
}
}
}
Main:
public class Main {
public static void Main() {
//read
PageFactory pageFactory = new PageFactory();
PageBase page = pageFactory.GetPage("A4");
page.GetCost(0,0,false);
}
}
Decorator is way more elegant than Factory to your problem.
For Decorator, you will need some classes and interfaces:
Interfaces: Colored, Side and Page. All interfaces has a method cost() to be implemented.
Classes: SingleSide, DoubleSide, ColorPage, BlankAndWhitePage, A4
Usage:
Page page1 = new A4(new SingleSide(new ColorPage()))
Page page2 = new A4(new DoubleSide(new BlankAndWhitePage()))
page1.cost();
You need to add some value to each component, to be summed and give the expected value. Each object has a "cost".
Some internals:
class A4 implements Page {
//constructor
private Side side;
public BigDecimal cost() {
return this.valueA4 + side.cost();
}
}
class SingleSide implements Side {
//constructor
private Colored colored;
public BigDecimal cost() {
return this.valueSingleSided+ colored.cost();
}
}
Something in this line could give you some insights about the best object organization.

Illegal expression in java code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am writing this code in Netbeans for a java class, but I am having a few errors and would really appreciate some help. The assignment is:
Design and implement a stringed musical instrument class using the following guidelines:
Data fields for your instrument should include number of strings, an array of string names representing string names (e.g. E,A,D,G), and boolean fields to determine if the instrument is tuned, and if the instrument is currently playing. You are welcome to add additional data fields if you like.
A constructor method that set the tuned and currently playing fields to false.
Other methods
to tune the instrument
to start the instrument playing, and
to stop the instrument from playing.
Other methods as you see fit (Add at least one unique method).
Create a UML class diagram using a diagram tool (e.g. PPT, Visio) of your choice. Prepare the diagrams and place them in a word document along with a brief description of each of your classes.
Create Java classes for your instruments. Be sure that your code matches your design specifications and some minimal functionality is included. For example, if you called the violin.play() method, you should at least print that the violin is playing. Similar functionality should be supplied when you stop playing, tune or call any of your methods. For example:
public void playviolin() {
System.out.println("The violin is now playing.");
}
Write the output from your Instrument class methods to a text file that a user entered from the command line arguments (e.g. java Mynamep3tst myfilename.txt). This allows your program to accept filenames from the user via a command line argument.
Finally, create a Java test class that simulates using your instrument class. In your test class be you should at a minimum: a) Construct 10 instances of your instrument, b) tune your instruments, c) Start playing your instrument, d) Call your unique method, and e) Stop playing your instruments. (Hint: Arrays and Loops will make your job easier and result in more efficient code!)
So here is my code currently:
package andrewrubinfinalproject;
/**
*
* #author Andy
*/
public class AndrewRubinFinalProject {
public static void main(String[] args) {
//fields to determine if the instrument is isTuned,
private boolean isTuned;
//and if the instrument is currently isPlaying.
private boolean isPlaying;
private String name;
private int numberOfStrings = 4; // number of strings
private String nameofStringsInInstrument[] = {"E", "C", "D", "A"}; //an array of string names
//A constructor method that set the isTuned and currently isPlaying fields to false.
public AndrewRubinFinalProject() {
this.isTuned = false;
this.isPlaying = false;
}
public String getNameOfInstrument() {
return name;
}
public void setNameOfInstrument(String nameOfInstrument) {
this.name = nameOfInstrument;
}
// Other methods
public boolean isPlaying() {
return isPlaying;
}
public void setPlaying(boolean playing) {
this.isPlaying = playing;
}
public boolean isTuned() {
return isTuned;
}
public void setTuned(boolean isTuned) {
this.isTuned = isTuned;
}
public void startPlayInstrument() {
System.out.println("The Instrument is now Playing.");
isPlaying = true;
}
public void stopPlayInstrument() {
System.out.println("The Instrument is not Playing anymore.");
isPlaying = false;
}
public void startTuneInstrument() {
System.out.println("The Instrument is Tuned.");
isTuned = true;
}
public void stopTuneInstrument() {
System.out.println("The Instrument is not Tuned.");
isTuned = false;
}
public int getNumberOfStrings() {
return this.numberOfStrings ;
}
public String[] getStringNames() {
return nameofStringsInInstrument;
}
}
You didn't close your main method. You should insert } before you begin to write other methods.
It's a bad habit to use magic numbers in your code, such as private int numberOfStrings = 4;, what if you change the array? You'll have to change this number too.
Instead, it's better to use .length that returns the size of the array.
It seems your assignment is given to check your OOP concepts.
See the code below, I've given a little touch to your code.
package andrewrubinfinalproject;
/**
*
* #author Andy
*/
public class AndrewRubinFinalProject {
//fields to determine if the instrument is isTuned,
private boolean isTuned;
//and if the instrument is currently isPlaying.
private boolean isPlaying;
private String name;
private int numberOfStrings = 4; // number of strings
private String nameofStringsInInstrument[] = {"E", "C", "D", "A"}; //an array of string names
//A constructor method that set the isTuned and currently isPlaying fields to false.
public AndrewRubinFinalProject() {
this.isTuned = false;
this.isPlaying = false;
}
public String getNameOfInstrument() {
return this.name;
}
public void setNameOfInstrument(String nameOfInstrument) {
this.name = nameOfInstrument;
}
// Other methods
public boolean isPlaying() {
return this.isPlaying;
}
public void setPlaying(boolean playing) {
this.isPlaying = playing;
}
public boolean isTuned() {
return this.isTuned;
}
public void setTuned(boolean isTuned) {
this.isTuned = isTuned;
}
public void startPlayInstrument() {
System.out.println("The Instrument is now Playing.");
this.isPlaying = true;
}
public void stopPlayInstrument() {
System.out.println("The Instrument is not Playing anymore.");
this.isPlaying = false;
}
public void startTuneInstrument() {
System.out.println("The Instrument is Tuned.");
this.isTuned = true;
}
public void stopTuneInstrument() {
System.out.println("The Instrument is not Tuned.");
this.isTuned = false;
}
public int getNumberOfStrings() {
return this.numberOfStrings ;
}
public String[] getStringNames() {
return this.nameofStringsInInstrument;
}
}
The problem is with the positioning of your main method.
First write a class as in the above code.
Then in your main method, make an instance of AndrewRubinFinalProject class by calling the constructor.
public static void main(String[] args){
AndrewRubinFinalProject andrewsObject= new AndrewRubinFinalProject();
// you can call any method in your class with respect to andrewsObject
// e.g.
// andrewsObject.setNameOfInstrument("Violin");
// String x= andrewsObject.getNameOfInstrument()
}
What you must know is that the main method does not necessarily be in the class you are writing. It can be somewhere else in your program.
First you should make at least 2 classes. One is Instrument with all its fields and methods. And another is your main project class that contains main() method and created and uses instruments.
The code that you posted will not be compiled as you opened and not closed the main method.
When first starting out in Object Oriented Programming, write up a small description of the problem, or at least think about it in terms that have enough detail.
Initially, the nouns should become your classes. Abstract groups of nouns might be good candidates for interfaces, and the verbs should become methods belonging to the class that is "closest" to the verb. By closest, I mean that performing the verb will require more access to the attributes in the class.

representing different kind of players in a class [closed]

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();
}
}

Categories