Using a class to randomize dice rolls - java

I'm writing a dice game program that creates a die for the user and computer, then asks for user name, number of sides on dice, and how many iterations the user would like to play with the computer. Then have the program check after each roll to see which roll is higher and at the end of the iterations it writes back the total wins for each user and computer and who the winner is. The problem i'm having is that I need to create a roll() class to randomize the dice and set it to a value for the users roll and computers roll and i'm getting this error...
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Random.java:388)
at classwork6_3.Die.roll(Die.java:52)
at classwork6_3.ClassWork6_3.main(ClassWork6_3.java:29)
Here is my main() class...
package classwork6_3;
import java.util.*;
public class ClassWork6_3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Random r = new Random();
System.out.print("Enter user's name: ");
String name = s.nextLine();
int value = 0;
int value2 = 0;
System.out.print("How many sides does the die have?: ");
int sides = s.nextInt();
s.nextLine();
System.out.print("How many times would you like to roll?: ");
int numRoll = s.nextInt();
int counter = 0;
int counter2 = 0;
Die user = new Die(name, sides, value);
Die comp = new Die(value);
for(int i = 1; i<= numRoll; i++){
value = r.nextInt(user.roll(sides)) + 1;
value2 = r.nextInt(comp.roll(sides)) + 1;
System.out.printf("%s rolled: %d\n", user.getOwner(), user.getValue());
System.out.print("Computer rolled: " + comp.getValue() + "\n\n");
if(value > value2){
counter++;
} else if(value2 > value){
counter2++;
}
}
System.out.printf("%s TOTAL WINS: %d\n", user.getOwner(), counter);
System.out.print("Computer TOTAL WINS: " + counter2 + "\n\n");
if(counter > counter2){
System.out.printf("%s wins!!\n", user.getOwner());
}else if(counter2 > counter){
System.out.print("Computer wins\n");
}else{
System.out.print("It's a tie!\n");
}
}
}
Here is my Die() class...
package classwork6_3;
import java.util.*;
public class Die {
Random r = new Random();
private int sides;
private int value;
private String owner;
public Die(String owner, int sides, int value){
this.sides = sides;
this.value = value;
this.owner = owner;
}
public Die (int value){
this.value = value;
}
public int getSides(){
return sides;
}
public int getValue(){
return value;
}
public String getOwner(){
return owner;
}
public void setSides(int sides){
this.sides = sides;
}
public void setValue(int value){
this.value = value;
}
public void setOwner(String owner){
this.owner = owner;
}
public int roll(int rand){
rand = r.nextInt(value);
return value;
}
}

Here are the issues with your code :
You are never returning the random value generated by the roll(...) method
public int roll(int rand){
rand = r.nextInt(value);
return value;
}
Change it to
public int roll(int rand) {
return r.nextInt(rand);
}
Within the for-loop all you need to do is just call the roll()
method. Since it already calculates the random value of the die, there is no need for you to call r.nextInt() again.
value = r.nextInt(user.roll(sides)) + 1;
value2 = r.nextInt(comp.roll(sides)) + 1;
Change it to
value = user.roll(sides) + 1;
value2 = comp.roll(sides) + 1;
Now print out the values using :
System.out.printf("%s rolled: %d\n", user.getOwner(), value);
System.out.print("Computer rolled: " + value2 + "\n\n");
Your code will work as expected after performing the above mentioned steps. Also as a side note do not use variable names that have an ambiguous meaning like value, value2 etc.

Whenever you make a new die, your value is never changed from zero, causing that error to pop-up since the range it would be looking through whenever you call roll(), acording to your Die class, is 0 to 0. Change value to the value the user puts in and the make a new die.

Related

Vector in java always overwriting everything with the last value

I'm a beginner in java and I have the following exercise to solve:
Read a set of sports lottery bets to an unspecified number of players. After that, read the template, compare the result and display a message.
Bet Class: must contain the player's name and an integer vector with thirteen positions to store the bet: 1 – winner of team A, 2 – winner of team B, and 0 for draw. Create the necessary constructor methods and the toString method.
ReadBets Class: This class must have an attribute that is a vector of objects of the Bet class. In addition, this class must have a method to read the person's name and their sports lottery game. Create the necessary constructor methods and the toString method.
ReadTemplate Class: This class should read the correct answers from the sports lottery game and store the result in an integer vector. Create the necessary constructor methods and the toString method.
GenerateResult Class: this class must compare the players' bets with the result of the template and, if you have 6 correct answers, show the winner's name, his game and the message: “WINNER, CONGRATULATIONS”. Otherwise, show the player name and the message “Try again, this time you didn't win”.
Main Class: implement in this class the control and execution flow for this problem creating the necessary objects to solve this class.
There is a complicating factor for me which is that each object bet is composed of a string name with a vector with the bets.
I made a solution to the problem that already reads validating only the allowed values (0,1,2), reads the template and compares.
However, I noticed that the last name typed and the last bets are always being recorded in the vector. In all positions.
I'm hours assembling and disassembling the code and I can't find a way to solve it.
I read that it may have to do with the new but I didn't understand how to solve it because at each position of the vector of objects I need to give a new to create the object with the internal vector that will store that player's bets.
Below are my classes:
MAIN:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public void execute(){}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//ReadBet a = new ReadBet();
V_Bets a = new V_Bets();
System.out.println("Enter the total bets that will be placed");
a.totalBets(input.nextInt());
a.Data entry();
a.Data output();
ReadTemplate g = new ReadTemplate();
g.getTemplate();
GenerateResult gr = new GenerateResult();
gr.generateResult();
}
}
BETS:
import java.util.Arrays;
public class Bet {
private static String name;
public static int[] Bet vector =new int [6];
/*public String getName(){
return this.name;
}*/
public static String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
#Override
public String toString() {
return "Bet [name=" + name + ",Betvector=" + Arrays.toString(Betvector) + "]";
}
public int getBet(int i) {
return this.vector Bets[i];
}
public void setBets(int[] bets) {
this.vector Bets = bets;
}
public int[] getCloneArray() {
returnVectorBets.clone();
}
}
V_BETS
import java.util.Scanner;
public class V_Bets {
Input Scanner = new Scanner (System.in);
private int size;
public static Total BetBets[] = new Bet[100];
//total Bets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
private Bet bets = new Bet();
int i=0;
int j=0;
public void dataentry() {
for(j=0;j<size;j++) { //for external - from J that controls the total bets that will be registered
totalBets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
System.out.println("Enter the name of the Player:");
totalStakes[j].setName(input.next()); //setting the player's name
// loop to set the guesses
System.out.println("Please enter guesses for each Sports Lottery game");
System.out.println("1 - Winner Team A, 2 - Winner Team B and 0 - Tie");
for ( i=0;i<bets.vetorApostas.length;i++) // receive the bet until it reaches 6
{
System.out.println("Game "+i +":");
totalStakes[j].vectorStakes[i] = input.nextInt(); // receive the user's bets
while (totalApostas[j].vectorApostas[i] < 0 ) // if the user enters a negative number it says to try again
{
System.err.println("Negative Number, try again:");
totalBets[j].vectorBets[i]= entry.nextInt();
}
if (totalApostas[j].vetorApostas[i] > 2) // if the number is greater than 2 it says to try again
{
while (totalBets[j].vectorBets[i] > 2 ) {
System.err.println("Please enter numbers between 0 and 2");
totalBets[j].vectorBets[i]= entry.nextInt();
}
}
}
}
}
/*public void dataoutput() {
//System.out.println("The player's name is:"+total Bets[i].getName());
System.out.println("Your Bet:");
for ( i=0;i < Bet.vectorBeats.length; i++){
System.out.print(+TotalStakes[i].vectorStakes[i].getStakes(i)+ " ");
}
}
public void dataoutput() {
System.out.println("Your Bet::");
for (j=0; j<totalBets[i].vectorBets.length; j++) {
System.err.print("Player "+Total Bets[j].getName()+" ");
for (i = 0; i < totalBets[i].vectorBets.length; i++) {
System.err.print(total Bets[j].vector Bets[i] + " ");
}
}
}*/
public void totalOfBets(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
TEMPLATE:
public class Template {
//private String name;
public static int[]vectorTemplate =new int [6];
public int getBet(int i) {
return this.vectorTemplate[i];
}
public void setBets(int[] bets) {
this.vectorTemplate = bets;
}
public int getTemplate(int i) {
return this.vectorTemplate[i];
}
public void setTemplate(int[] bets) {
this.vectorTemplate = bets;
}
}
READ TEMPLATE:
import java.util.Arrays;
import java.util.Scanner;
public class ReadTemplate {
private Template template = new Template();
Input Scanner = new Scanner (System.in);
int guesses;
int counter=0;
int j;
int x;
int i;
public void getTemplate() {
System.out.println(" ");
for ( j=0;j<6;j++) // Receive numbers until it reaches 6
{
System.out.println("Now Enter Game Template: "+j);
template.vectorTemplate[j]= entry.nextInt(); // Receive user numbers
while (template.vetorTemplate[j] < 0 ) // If you enter a negative number, ask the user to type again
{
System.err.println("Negative Number, try again:");
template.vectorTemplate[j]=input.nextInt();
}
if (template.vectorTemplate[j] > 2) // if the number is greater than 2 ask again
{
while (template.vectorTemplate[j] > 2 )
{
System.err.println("Please enter numbers between 0 and 2");
template.vectorTemplate[j]=input.nextInt();
}
}
}
//printing the template
System.out.println("Template:");
for (i = 0; i < template.vectorTemplate.length; i++) {
System.out.print(template.vectorTemplate[i] + " ");
}
}
}
GENERATE RESULTS:
public class GenerateResult extends ReadTemplate {
private Bet bets = new Bet();
private Template template = new Template();
//private v_bets v_bets = new v_bets();
private int size;
public void generateResult() {
//Checking if it's right
int x;
V_Bets a = new V_Bets();
for(j=0;j<2;j++) {
int i=0;
int counter=0;
for (x = 0; x < template.vectorTemplate.length; x++) {
if (a.totalStakes[j].vectorStakes[i] == template.vectorTemplate[x]) {
counter++;
}
i++;
}
System.out.println(" ");
System.out.println("Counter of Equals! "+counter);
if (counter <= 5){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("Try again, this time you won");
}
else if (counter == 6){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("WINNER,CONGRATULATIONS!");
}
}
}
public void totalOfBets(int size) {
this.size = size;
}
}
I am immensely grateful to anyone who can help understand where I went wrong and how to evolve.

Reroll dices in yahtzee game

I´m trying to create a simple yahtzee game where an array is filled with 5 random numbers and where the player can choose to roll specific dices again. However I cant figure out how to write the method that is supposed to replace specific numbers in the array with new random numbers and return it. Any suggestions how to approach this?
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class YatzyGame {
private final Integer NBROFDICE = 5;
private final Integer DICEMAXVALUE = 6;
Random rnd = new Random();
Scanner keyboard = new Scanner(System.in);
public void startGame() {
int[] dice = new int[NBROFDICE];
rollDice(dice);
printDice(dice);
System.out.println("Do you want to reroll any dices? " + "Y/N");
String answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("y")) {
rerollDice(dice);
} else if (answer.equalsIgnoreCase("n")) {
calculateSum(dice);
} else {
System.out.println("Wrong command!");
}
}
public int[] rollDice(int[] dice) {
for (int i = 0; i < dice.length; i++) {
dice[i] = rnd.nextInt(DICEMAXVALUE) + 1;
}
return dice;
}
public int[] rerollDice(int[] dice) {
System.out.println("What dices do you want to reroll? Dices index are 0-4");
int diceToReroll = keyboard.nextInt();
// Replace the numbers at the index the user specifies with new random numbers and return the array.
}
public void printDice(int[] dices) {
System.out.println("Your dices show: " + Arrays.toString(dices));
}
public void calculateSum(int[] dices) {
int sum = 0;
for (int i : dices) {
sum += i;
}
if (sum == 30) {
System.out.println("YAHTZEE! Your total score is 50! Congratulations!");
} else
System.out.println("Your total score is: " + sum);
}
public static void main(String[] args) {
new YatzyGame().startGame();
}
}
public int[] rollDice(int[] dice) {
System.out.println("What dice do you want to reroll? Dices index are 0-4");
int diceToRoll = keyboard.nextInt();
dice[diceToRoll] = rnd.nextInt(DICEMAXVALUE) + 1;
}
Like this you can make a function:
public int[] reroll(int amountOfRerolls, int[] dices){
for(int i =0;i<dicesToReroll;i++){
this.rollDice(dices);
}
return dices;
}
This makes the programm a bit more modal since you can reuse your rollDice() method wherever you need it. Also you could expand it a bit by handing in the indexes that are allowed to be rerolled in case needed.
edit: style

Copy Constructor Test not Working (Java)

I'm working on CS homework and have run into a problem. The end of the homework asks about using a copy constructor. The goal is to "make one Payroll object, instantiate it, make a second one, then print them both. Then, change values in the second Payroll object, and show that the changed values only appear in one and not both (that is, print out the original and the copy with slightly changed values)." I tried changing the values in the second Payroll object, but it also changes it in the first. I've listed my code below:
import java.util.Random;
public class Payroll {
private int[] employeeId;
private int[] hours;
private double[] payRate;
public Payroll(){
this.employeeId = new int[0];
this.hours = new int[0];
this.payRate = new double[0];
}
public Payroll(Payroll obj){
this.employeeId = obj.employeeId;
this.hours = obj.hours;
this.payRate = obj.payRate;
}
public Payroll(int i){
this.employeeId = new int[i];
this.hours = new int[i];
this.payRate = new double[i];
}
public int getEmployeeIdAt(int index){
return employeeId[index];
}
public int getHoursAt(int index){
return hours[index];
}
public double getPayRateAt(int index){
return payRate[index];
}
public double getGrossPay(int index){
double grossPay = hours[index] * payRate[index];
grossPay = Math.round(grossPay * 100);
return grossPay/100;
}
public void setEmployeeIdAt(int index, int id){
this.employeeId[index] = id;
}
public void setHoursAt(int index, int hrs){
this.hours[index] = hrs;
}
public void setPayRateAt(int index, double pr){
this.payRate[index] = pr;
}
public void setHoursAt(int i){
Random rand = new Random();
int randHours = rand.nextInt((50 - 15) + 1) + 15;
this.hours[i] = randHours;
}
}
import java.util.Scanner;
public class PayrollDriver {
public static void main(String[] args) {
Payroll pr = new Payroll(5);
Scanner scan = new Scanner(System.in);
int empID = 1001;
for(int i = 0; i < 5; i++){
pr.setEmployeeIdAt(i, empID);
empID++;
}
for(int i = 0; i < 5; i++){
System.out.println("Enter the hourly pay rate for employee number " + pr.getEmployeeIdAt(i) + ": ");
double payRate = scan.nextDouble();
if(payRate < 7.50){
do{
System.out.println("ERROR: Enter 7.50 or greater for pay rate: ");
payRate = scan.nextDouble();
} while(payRate < 7.50);
}
pr.setPayRateAt(i, payRate);
pr.setHoursAt(i);
}
System.out.println("PAYROLL DATA");
System.out.println("======================");
for(int i = 0; i < 5; i++){
System.out.println("Employee ID: " + pr.getEmployeeIdAt(i) + " Hours: " + pr.getHoursAt(i) + " Rate: " + pr.getPayRateAt(i) +
" Gross Pay: $" + pr.getGrossPay(i));
}
System.out.println("Would you like to run the Copy Constructor Test? Enter 'y' (lowercase) if yes, enter any other letter if no: ");
char copyTestVerify = scan.next().charAt(0);
if(copyTestVerify == 'y'){
CopyConstructorTest ct = new CopyConstructorTest();
ct.CopyTest();
}
scan.close();
}
}
The following is my CopyConstructorTest class, the one that tests whether or not the copy constructor will change the original object's values:
public class CopyConstructorTest {
public void CopyTest(){
Payroll pay = new Payroll(5);
pay.setEmployeeIdAt(0, 1001);
Payroll payCopy = new Payroll(pay);
System.out.println("Original: " + pay.getEmployeeIdAt(0));
System.out.println("Copy: " + payCopy.getEmployeeIdAt(0));
payCopy.setEmployeeIdAt(0, 5000);
System.out.println("Original after changes: " + pay.getEmployeeIdAt(0));
System.out.println("Copy after changes: " + payCopy.getEmployeeIdAt(0));
}
}
I'm not positive on what I'm doing wrong. Any help or guidance is much appreciated.
You are just copying the references to the arrays, not the actual data. Therefore whenever you change the data in one of your objects, the changes are seen in both, since they point to the same array.
The easiest way to copy the data is probably using System.arraycopy():
public Payroll(Payroll obj) {
this.employeeId = new int[obj.employeeId.length];
System.arraycopy(obj.employeeId, 0, this.employeeId, 0, obj.employeeId.length);
...

Arrays JOptionPane version

can anyone help me with this.
the assignment is to use JOptionPane in arrays. the user will input the length of the array. then at the end of the program, it will display the largest number.
here is what i got so far:
import javax.swing.JOptionPane;
public class array
{
public static void main(String[] args)
{
String L;
int lenght;
L=JOptionPane.showInputDialog(null,"enter lenght: ");
lenght=Integer.parseInt(L);
int[]num = new int[lenght];
for(int counter = 0; counter < lenght ;counter++)
{
JOptionPane.showInputDialog(null,"enter #: "+(counter+0));
int max=num[0];
if (num[counter] > max)
{
max = num[counter];
}
}
JOptionPane.showMessageDialog(null,"the largest number is: " + max);
}
}
then there is this error:
error: cannot find symbol
maxis defined in scope of for loop. So it is not available outside of for.
Define it outside of the for loop and it should work:
public static void main(String[] args) {
String L;
int lenght;
L = JOptionPane.showInputDialog(null, "enter lenght: ");
lenght = Integer.parseInt(L);
int[] num = new int[lenght];
int max=0;
for (int counter = 0; counter < lenght; counter++) {
JOptionPane.showInputDialog(null, "enter #: " + (counter + 0));
max = num[0];
if (num[counter] > max) {
max = num[counter];
}
}
JOptionPane.showMessageDialog(null, "the largest number is: " + max);
}
Update:
You never store the input value to num[counter]
num[counter] = Integer.parseInt(JOptionPane.showInputDialog(null, "enter #: " + (counter + 0)));
package retedunits;
import java.util.Scanner;
public class RentedUnits {
private Integer TOTAL_NUMBER_RENT_UNITS; //Total number of rented units
private Double rentPerUnit; //Rent Per Unit
private Double maintainancePerUnit; //Average Maintainance cost per unit
private Integer currentUnitsRented; //Number of units currently occupied
private Double rentIncreaseFactor; //The level at which people leave
//PROFIT MAX
private Double maxRentForProfit;
private Integer maxUnitsForProfit;
public RentedUnits(Integer totalUnits, Double initalRentPerUnit, Double initialMaintainanceCost, Integer currentRented, Double rentIncreaseFactor){
this.TOTAL_NUMBER_RENT_UNITS = totalUnits;
this.rentPerUnit = initalRentPerUnit;
this.maintainancePerUnit = initialMaintainanceCost;
this.currentUnitsRented = currentRented;
this.rentIncreaseFactor = rentIncreaseFactor;
}
public Double getMaxRentForProfit() {
return maxRentForProfit;
}
public Integer getMaxUnitsForProfit() {
return maxUnitsForProfit;
}
private void increaseRent(Double increasedRent){
//For each $40 increase in rent one unit is vacant.
if(increasedRent > this.rentIncreaseFactor) {
//The number of units that will become vacant is one for every increase of rentIncreaseFactor
int numberVacate = (int) (increasedRent % this.rentIncreaseFactor);
this.currentUnitsRented -= numberVacate;
this.rentPerUnit += increasedRent;
}
else {
this.rentPerUnit += increasedRent;
}
}
private Double calculateProfit(){
//Calculate total rent collected from units that are rented
Double totalRent = this.currentUnitsRented * this.rentPerUnit;
//calculate the maintainanec of all units
Double totalMaintainence = this.TOTAL_NUMBER_RENT_UNITS * this.maintainancePerUnit;
return totalRent - totalMaintainence;
}
public void maximizeProfit(){
/*Keep increasing rent, and let people leave till the total collected
* rent keeps increasing.
*/
/* Assume you begin at all units occupied*/
Double maximumProfit = 0.0;
Double maxProfitRent = 0.0;
Integer maxProfitUnits = 0;
/* Keep increasing rent till all people leave while tracking max profit*/
while(this.currentUnitsRented == 0){
increaseRent(this.rentIncreaseFactor);
if(this.calculateProfit() > maximumProfit){
maximumProfit = this.calculateProfit();
maxProfitRent = this.rentPerUnit;
maxProfitUnits = this.currentUnitsRented;
}
}
this.maxRentForProfit= maxProfitRent;
this.maxUnitsForProfit = maxProfitUnits;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
RentedUnits rentedUnits = new RentedUnits(50, 600.0, 27.0, 50, 40.0);
rentedUnits.maximizeProfit();
System.out.println(rentedUnits.getMaxUnitsForProfit() + " units needs to be rented at " + rentedUnits.getMaxRentForProfit() + " rent per unit to get maximum profit.");
}
}

I'm wanting to test which of two integers is closest to a third int in Java

I feel like this has an extremely obvious answer, so forgive me if I'm being stupid.
I'm creating a simple text-based game for elementary school kids in which the user, playing as a mage, needs to ward off mighty dragons by mixing together various spell cards (in my case, multiplying their values together to try and get the closest to the dragon's weakness number). This weakness number changes every turn, until the dragon hits an HP less than or equal too 0, at which point another dragon will spawn and the player will have to ward that one off too. The entire project takes up five classes, one for the player, another for the cards, another for the dragon, another for the game's play methods, and a fifth, the driver.
The first thing that comes to mind for me is to make a method in Player.java that goes something like this:
public int isClosestToo(int num, int max){
int counter = 0;
for(int i = num; i <= max; i++){
counter++
}
return counter;
}
followed by an if statement in my game class' play method:
if(isClosestToo(num1) > isClosestToo(num2){
/*do something*/
}
I realize that this would work, but I want to make sure I'm not missing something blatantly obvious and simpler that I could do. Some method in the Integer class maybe?
Please keep in mind this is a very early version of the project, and I hope to implement Slick2D graphics later.
Here's all of my code thus far:
From Game.java:
import java.util.Scanner;
public class Game {
Scanner scan = new Scanner(System.in);
public Game(){}
public void play(){
Player p = new Player();
while(p.getHP() > 0){
Dragon d = new Dragon();
System.out.println("You have " + p.getHP() + " HP");
System.out.println(d);
System.out.println(p.elementHandToString());
System.out.println(p.attackHandToString());
System.out.println("Choose the two cards that multiply to be closest too the weakness of the dragon for the most damage!");
int element = scan.nextInt();
int attack = scan.nextInt();
int damage = d.getWeakness() - (p.getElementCard(element - 1).getNum() * p.getAttackCard(attack - 1).getNum());
d.setHP(d.getHP() - damage);
p.afterTurn(element, attack);
d.newWeakness();
}
}
}
And Player.java:
import java.util.Random;
import java.util.ArrayList;
public class Player {
Random r = new Random();
int hp;
ArrayList<Card> attackHand;
ArrayList<Card> elementHand;
ArrayList<String> elements;
ArrayList<String> attacks;
public Player(){
this.hp = 100;
this.genHands();
attackHand = new ArrayList<Card>();
elementHand = new ArrayList<Card>();
//arraylist of types of elements, feel free to add more using the .add method
elements = new ArrayList<String>();
elements.add("Fire");
elements.add("Ice");
elements.add("Water");
elements.add("Air");
elements.add("Rock");
elements.add("Mana");
//arraylist of types of attacks, feel free to add more using the .add method
attacks = new ArrayList<String>();
attacks.add("Projectile");
attacks.add("Self");
attacks.add("Explosion");
attacks.add("Repeated");
attacks.add("Debuff");
attacks.add("Melee");
}
public Player(int hp){ this.hp = hp; }
public int getHP(){ return hp; }
public ArrayList<Card> getAttackHand(){ return attackHand; }
public ArrayList<Card> getElementHand(){ return elementHand; }
public Card getAttackCard(int whichCard){ return attackHand.get(whichCard); }
public Card getElementCard(int whichCard){ return elementHand.get(whichCard); }
public void afterTurn(int element, int attack){
attackHand.add(new Card(genRand(1, 12), attacks.get(genRand(1, 12))));
elementHand.add(new Card(genRand(1, 12), elements.get(genRand(1,12))));
attackHand.remove(attack - 1);
elementHand.remove(element - 1);
}
public String elementHandToString(){ return "Card 1: " + elementHand.get(0) + "/nCard 2: " + elementHand.get(1) + "/nCard 3: " + elementHand.get(2) + "/nCard 4: " + elementHand.get(3); }
public String attackHandToString(){ return "Card 1: " + attackHand.get(0) + "/nCard 2: " + attackHand.get(1) + "/nCard 3: " + attackHand.get(2) + "/nCard 4: " + attackHand.get(3); }
//generates the player's hands
public void genHands(){
//creates a deck of random elemental cards
for(int x = 0; x <= 4; x++){
elementHand.add(new Card(genRand(1, 12), elements.get(genRand(0, elements.size() - 1))));
}
//creates a deck of random attack cards
for(int i = 0; i <= 4; i++){
attackHand.add(new Card(genRand(1, 12), attacks.get(genRand(0, attacks.size() - 1))));
}
}
//returns a random integer between min and max
//#param1 minimum number for random to be
//#param2 maximum number for random to be
public int genRand(int min, int max){ return r.nextInt(max) + min; }
}
Dragon.java:
package alchemy;
import java.util.Random;
public class Dragon {
int hp;
int weakness;
Random r = new Random();
public Dragon(){
hp = genRand(1, 144);
weakness = genRand(1, hp);
}
public int getHP(){
return hp;
}
public void setHP(int newHP){
hp = newHP;
}
public String toString(){
return "A dragon with " + hp + "HP has appeared!" + "/nIts current weakness is " + weakness + "/nPlay two cards that multiply to a number close to its weakness for damage!";
}
public int getWeakness(){
return weakness;
}
public void newWeakness(){
weakness = genRand(1, hp);
}
public int genRand(int min, int max){
return r.nextInt(max) + min;
}
}
And lastly, Card.java:
import java.util.Random;
public class Card{
int num;
Random r = new Random();
String element;
public Card(){
num = 0;
element = "n/a";
}
public Card(int n, String e){
num = n;
element = e;
}
public int getNum(){
return num;
}
public String getElement(){
return element;
}
public String toString(){
return "This is a " + element + "card with a value of " + num + ".";
}
}
Primarily, the issue I'm running into is the play() loop of the Game class, where I need to calculate the damage that the player does. Obviously, (before I program in elemental logic), I want that damage to actually do damage instead of ending up as a negative number and making the dragon gain HP. Any and all help would be greatly appreciated. Thank you!
-Nick
In java, when a method starts with "is", it returns boolean. But your project probably maintained by you yourself, it can be whatever you want.
Your isClosestToo method, takes in 2 arguments, which is num and max, both integer, but when you call it, you only takes in one argument.
public int isClosestToo(int num, int max){
int counter = 0;
for(int i = num; i <= max; i++){
counter++
}
return counter;
}
if(isClosestToo(num1) > isClosestToo(num2){
/*do something*/
}
the method name itself is confusing, you can do public int ClosestTo(int[] num,int max) to take and a list of number and return the closest number or do DiffMax(int num) to take in a number and subtract it with the max, in which this case your max must be accessible in the method scope.
public int ClosestTo(int[] num,int max)
{
1.declare a variable to store the closest num
2.for every element in num, if Math.abs(max-num) < closestNum, store num to closestNum
3.return closestNum
}
or
public int DiffMax(int num)
{
1. return Math.abs(max-num) < closestNum
}
then you can do
if(DiffMax(num1) > DiffMax(num2){
/*do something*/
}
this is an option
if((max-int1)>(max-int2) && max-int2>=0){
//do something with int2
}
else if((max-int1)<(max-int2) && max-int1>=0){
//do something with int1
}
else if(max-int1>=0){
//do something with int1
}
else if(max-int2>=0){
//do something with int2
}
else{
//do something if conditions aren't met
}

Categories