import java.util.Random;
import java.lang.Math;
import java.lang.String;
public class GameOfNim
{
private int min,max;
private int turn;
private int firstturn;
private int stupid;
private int smart;
private int computer;
private int user;
private int first;
private int pile;
public GameOfNim(int min, int max ){
pile=(int)(Math.random()*max+min);
smart=(int)(Math.random()*100);
stupid=(int)(Math.random()*100);
System.out.println("Pile size is "+pile);
firstturn=(int)(Math.random()*100 + 1);
computer=0;
user=1;
if(firstturn>50)
{
firstturn=user;
}
else
{
firstturn=computer;
}
firstturn=turn;
}
public void play()
{
if(smart>50)
{
System.out.println("Computer is playing smart");
}
else
{
System.out.println("Computer is playing stupid");
}
if(firstturn==user)
{
System.out.println("You go first");
}
else
{
System.out.println("Computer goes first");
}
turn = firstturn;
while(pile-1>0)
{
if(turn==user)
{
String take = "How many marbles do you want to take away?";
System.out.println(take);
int take2 = Integer.parseInt(take);
while(take2>(int)(pile/2))
{
System.out.println("Only take away half or less from the pile");
take = "How many marbles do you want to take away?";
take2= Integer.parseInt(take);
}
pile= pile-take2;
System.out.println("There are "+pile+" marbles left");
turn=computer;
}
else
{
if(smart>50)
{
pile -= smartTake();
}
else
{
pile -= stupidTake();
}
turn = user;
}
}
}
private int smartTake()
{
int x = (int)(Math.random())*2-1;
int sMarbles= (int)Math.pow(2,x);
while (sMarbles > (.5 * pile) || sMarbles==0)
{
x = (int)(Math.random())*2-1;
sMarbles = (int)Math.pow(2,x);
}
System.out.println("The computer took away " + sMarbles +" marbles");
return sMarbles;
}
private int stupidTake(){
int stMarbles = pile/2;
while (stMarbles > (.5*pile) || pile==0)
{
stMarbles = pile/2;
}
System.out.println("The Computer took away " + stMarbles +" marbles");
return stMarbles;
}
}
this is my game of nim class
public class Project5
{
public static void main(String args[])
{
String k = "yes";
String str;
Scanner console = new Scanner(System.in);
System.out.print("Enter the minimum number of marbles in your pile: ");
int min = console.nextInt();
System.out.print("Enter the maximum number of marbles in your pile: ");
int max= console.nextInt();
GameOfNim game = new GameOfNim(min, max);
game.play();
System.out.println( " Thank you and good bye!");
}
}
and this is my driver class
for some reason everytime i run it it goes all the way to the point where it says "Computer goes first" then nothing else happens. im assuming its stuck in a loop but i cant seem to find out why. any help will be appreciated
Related
In this code I am writing here the user inputs whether or not they would like to choose heads or tails in a coinflip game. I would like to keep a tally of how many times heads appears or tails appears and output it each time it changes. After hours of trying and searching I cannot figure it our perfectly so if someone could let me know what I could utilize let me know.
import java.util.Random;
import java.util.Scanner;
public class CoinToss {
private enum Coin {
Head, Tail
}
public static void main(String[] args) {
CoinToss game = new CoinToss();
game.startGame();
}
private void startGame() {
Scanner scanner = new Scanner(System.in);
Coin guess;
while (true) {
System.out.print("Enter your guess whether the coin will be heads or tails. Type 1 for heads, 2 for tails, or 3 to quit: ");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("3")) {
break;
} else if (choice.equalsIgnoreCase("1")) {
guess = Coin.Head;
} else if (choice.equalsIgnoreCase("2")) {
guess = Coin.Tail;
} else {
System.out.println("Please select either heads tails or quit.");
continue;
}
Coin toss = tosscoin();
if (guess == toss) {
System.out.println("You guessed correctly!");
} else {
System.out.println("You guessed incorrectly");
}
}
scanner.close();
}
private Coin tosscoin() {
Random r = new Random();
int sideup = r.nextInt(2);
if (sideup == 1) {
return Coin.Head;
} else {
return Coin.Tail;
}
}
}
You can for example add two fields in your CoinToss class. Like int heads and int tails. Initialize them with 0 in the startGame() method. Then, in the tosscoin() method:
if (sideup == 1) {
heads++;
return Coin.Head;
} else {
tails++;
return Coin.Tail;
}
You can access these fields in the startGame() method and do whatever you want with them.
You could as well define these two variables directly in the startGame() method and increment them based on the type of Coin which you get from the tosscoin() method.
Below code should work. everytime it tosses, it stores the current value in a variable and compares it next time with the toss value.
import java.util.Random;
import java.util.Scanner;
public class CoinToss {
private static int headCounter;
private static int tailCounter;
private static int previousToss;
private enum Coin {
Head, Tail
}
public static void main(String[] args) {
CoinToss game = new CoinToss();
game.startGame();
}
private void startGame() {
headCounter = 0;
tailCounter = 0;
previousToss = 0;
Scanner scanner = new Scanner(System.in);
Coin guess;
while (true) {
System.out.print("Enter your guess whether the coin will be heads or tails. Type 1 for heads, 2 for tails, or 3 to quit: ");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("3")) {
break;
} else if (choice.equalsIgnoreCase("1")) {
guess = Coin.Head;
} else if (choice.equalsIgnoreCase("2")) {
guess = Coin.Tail;
} else {
System.out.println("Please select either heads tails or quit.");
continue;
}
Coin toss = tosscoin();
if (guess == toss) {
System.out.println("You guessed correctly!");
} else {
System.out.println("You guessed incorrectly");
}
}
scanner.close();
}
private Coin tosscoin() {
Random r = new Random();
int sideup = r.nextInt(2);
Coin currentGuess;
if (sideup == 1) {
headCounter++;
currentGuess = Coin.Head;
} else {
tailCounter++;
currentGuess = Coin.Tail;
}
checkIfFlipped(sideup);
return currentGuess;
}
static void checkIfFlipped(int currentToss) {
if (currentToss != previousToss) {
if (currentToss == 0) {
System.out.println("Coin fliped from head to tail");
} else {
System.out.println("Coin fliped from tail to head");
}
}
previousToss = currentToss;
}
}
I'm trying to make a turn based fighting game in Java Eclipse. Right now there's nothing wrong with my code but I just needed help figuring out a way to add multiple attacks to each of my characters in the game.
This is my main method
public class Main {
public static Random generator = new Random();
public static void main(String[] args) {
String answer = "yes";
while(answer.equals("yes")) {
Character player1 = new Wraith();
Character player2 = new Paladin();
Scanner charInput = new Scanner(System.in);
System.out.println("Player1, Choose your character");
String choice = charInput.nextLine();
if(choice.equals("Paladin")) {
player1 = new Paladin();
}
if(choice.equals("Wizard")) {
player1 = new Wizard();
}
if(choice.equals("Wraith")) {
player1 = new Wraith();
}
System.out.println("Player2, Choose your character");
String choice2 = charInput.nextLine();
if(choice2.equals("Paladin")) {
player2 = new Paladin();
}
if(choice2.equals("Wizard")) {
player2 = new Wizard();
}
if(choice2.equals("Wraith")) {
player2 = new Wraith();
}
//player1.name = input("Player1 pick your character(Paladin, Wraith, Wizard)", charInput);
//player2.name = input("Player2 pick your character(Paladin, Wraith, Wizard)", charInput);
System.out.println(player1.name + " vs. " + player2.name);
System.out.println(player1.health + " vs. " + player2.health);
while (player1.isAlive() && player2.isAlive()) {
System.out.println(player1.name + ": " + player1.health);
System.out.println(player2.name + ": " + player2.health);
int damage;
damage = player1.attack(player2);
System.out.println(player1.name + " hits " + player2.name + " for " + damage);
damage = player2.attack(player1);
System.out.println(player2.name + " hits " + player1.name + " for " + damage);
}
if(player1.isAlive()) {
System.out.println(player1.name + " wins!");
} else if (player2.isAlive()) {
System.out.println(player2.name + " wins!");
} else {
System.out.println("It's a draw!");
}
}
}
private static String input(String string, Scanner charInput) {
return null;
}
}
This is one of my character classes
public class Wizard extends Character {
public int dexterity = 25;
public static Random generator = new Random();
public Wizard(){
super();
this.name = "Wizard";
this.strength = 10;
this.defense = 8;
this.health = 95;
}
public int attack(Character target){
boolean criticalHit =Main.generator.nextInt(150) < dexterity;
int damage = this.strength * 2;
if(criticalHit){
damage *= 2;
System.out.println("*** Critical Hit ***");
}
int damageDealt = target.takeDamage(damage);
return damageDealt;
}
}```
And this is my main character class
public class Character {
public String name;
public int strength;
public int health;
public int defense;
public int takeDamage(int damage){
int damageTaken = damage - this.defense;
this.health -= damageTaken;
return damageTaken;
}
public int attack(Character target){
int damage = this.strength * 2;
int damageDealt = target.takeDamage(damage);
return damageDealt;
}
public boolean isAlive(){
return health > 0;
}
}```
also I'm new to coding and stack overflow so and suggestions on how to make my posts make more sense or something like that is much appreciated
nice implemention of a battle system.
when a Character performs an attack you choose which attack that should be and execute:
public int attack(Character target){
AttackMode mode = determineAttackMode(target); // the charater chooses what kind of attack he will execute during this attack
switch(mode){
case AttackMode.DOUBLESTRIKE: return attackDoubleStrike(target);
case AttackMode.BURST: return attackBurst(target);
default: return attackDefault(target); // your previously implemented method attack(target)
}
}
The AttackMode is an Enum class:
enum AttackMode {DEFAULT, DOUBLESTRIKE, BURST}
i'm not sure how double damage is dealt, so this is a guess here
public int attackDoubleStrike(Character target){
int firstStrike = attackDefault(target);
int secondStrike = attackDefault(target);
return firstStrike + secondStrike;
}
I had to make a code where the user guesses the number the computer picks. I need to also use Boolean value true or false to tell the user if the user is correct or not. I tried using if else statement, but I have not learned that in Java yet. This is what I have so far:
import java.util.*;
public class RandomGuessMatch
{
public static void main(String[] args) {
boolean right = true;
int MAX = 5;
int MIN = 1;
int guess;
int random;
Scanner ask = new Scanner(System.in);
System.out.println("Input your guess between 1 through 5.");
guess = ask.nextInt();
random = MIN + (int)(Math.random() * MAX);
System.out.println("Your guess was " + guess);
System.out.println("The random number was " + random);
if (right =
}
}
You have to read about if else in java. That is conditional statements.
It is like if you want to perform something when some condition is true, else if the condition is not satisfied it will execute else part.
if(condition) {
//Some task
} else {
// some task
}
Like you can add if else in your code.
import java.util.*;
public class RandomGuessMatch
{
public static void main(String[] args) {
boolean right = true;
int MAX = 5;
int MIN = 1;
int guess;
int random;
Scanner ask = new Scanner(System.in);
System.out.println("Input your guess between 1 through 5.");
guess = ask.nextInt();
random = MIN + (int)(Math.random() * MAX);
System.out.println("Your guess was " + guess);
System.out.println("The random number was " + random);
if (guess == random) {
right = true;
} else {
right = false;
}
System.out.println(right);
}
}
You should google more, for such a simple question. For example.
Anyway:
If the variable right is a Boolean:
if (right) {
// do something
}
I am supposed to be writing the game of nim. I am having trouble finding out how to fix the compile error
cannot find symbol - method getPlayer()
Also, is this the only problem you see? Or are there other issues that would cause this program to fail to compile or work properly.
import java.util.Scanner;
import java.util.Random;
public class Nim {
private int n;
private int compMode;
private int numberLeft;
private int numberTaken;
private boolean whoseTurn;
private String inputName;
private String name;
private String play;
private boolean yes;
Scanner in = new Scanner(System.in);
Random num = new Random();
public void setState() {
numberLeft = 100;
numberTaken = numberLeft;
}
public String getPlayer() {
inputName = in.next("");
inputName = name;
return name;
}
public void getCompPlay() {
compMode = num.nextInt(2);
if (compMode == 0) System.out.println("The computer is in smart mode");
if (compMode == 1) System.out.println("The computer is in random mode");
}
public void playGame() {
if (whoseTurn == true) {
System.out.println(name + "It is your turn...");
System.out.printf("Please enter the number you wish to take from the pile (Must be less than " + (numberLeft / 2) + "): ");
numberTaken = in.nextInt();
numberLeft -= numberTaken;
System.out.println("The number left is " + numberLeft);
whoseTurn = false;
}
if (whoseTurn == false) {
System.out.println("It is the computer's turn...");
if (compMode == 0) {
numberLeft = smartComputer(numberLeft);
System.out.println("The number left is " + numberLeft);
}
if (compMode == 1) {
numberLeft -= num.nextInt(numberLeft / 2);
System.out.println("The number left is " + numberLeft);
}
whoseTurn = true;
return;
}
if (yes == true) {
}
if (numberLeft <= 1) {
if (whoseTurn = false) {
System.out.println("You Win!");
} else {
System.out.println("You're horrible...you lost to a computer.");
}
}
if (numberLeft <= 1) {
if (whoseTurn = false) {
System.out.println("You Win!");
} else {
System.out.println("you lost to a computer.");
}
}
}
public static int smartComputer(int num) {
int power = 2;
while (power < num) {
power *= 2;
}
power /= 2;
num = power - 1;
return num;
}
public boolean playAnother() {
System.out.println("/nPlay Again? (y/n)");
play = in.next("");
if (play.equalsIgnoreCase("y")) return true;
else return false;
}
public void displayTotals() {}
}
And here is my Tester
public class NimTester {
public static void header() {
System.out.println("Eric Magnusson");
System.out.println("AP Comp Sci");
System.out.println("Game of Nim (P6.16)");
}
public static void main() {
Nim nim = new Nim(getPlayer(), getCompPlay());
do {
nim.setState();
nim.playGame();
nim.printWinner();
} while (playAnother());
nim.displayTotals();
}
}
Your class either has no specific Constructor, or it is not shwon in your code. To learn more about Construcotrs, please read the documentation here. To put it simple, a Constructor is a method that allows the JVM to organize the memory and initialize the object.
The default object constructor is a non-argument constructor that sets each child variable the default value.
Example:
Class Car{
public Car(){
System.out.print("car is built.");
}
}
Car aCar = new Car();
What you have is Nim nim = new Nim(getPlayer(), getCompPlay()); therefore your Nimclass has to have a public Nim(String x, String y) method.
Another problem with the code shown is, you are using an object method to create the object...
Either the method has to be static (read about it here), or it has to not depend on the object you are creating. To simplify your program, just save that value before using it in a variable, then use that variable in the object construction. Or even create a staic method like: public static String getJohn(){return "John"}, and then your code will work past that point.
Other issues with the code are related to readability, please read on Java Naming conventions, on how to name your variables, they will help maintenance, as well as allow other programmers to assist you.
As of now my highscore list is only sorted by number of guesses. I would like entries with identical number of guesses to also be sorted by time in ms, in descending order. Tried searching and found some similar Q's but couldn't really find a solution. Any pointers will be greatly appreciated! Feel free to comment on other parts of my code as well!
import java.util.*;
public class Game {
private static ArrayList<highScore> score = new ArrayList<highScore>();
private class highScore implements Comparable<highScore> {
int guessCount = 0;
double playerTime = 0;
String playerName;
public highScore (int guessCount, double playerTime, String playerName) {
this.guessCount = guessCount;
this.playerTime = playerTime;
this.playerName = playerName;
}
public String toString() {
String scoreList = (this.playerName + "\t\t" + this.guessCount + "\t\t" + this.playerTime);
return scoreList;
}
public int compareTo(highScore hs) {
if (((Integer)this.guessCount).compareTo(((Integer)hs.guessCount)) > 0)
return 1;
else
return -1;
}
}
public static void main(String [] args) {
boolean playGame = true;
Scanner scan = new Scanner(System.in);
Game g = new Game();
while(playGame) {
g.start();
System.out.println("\nPlay again?");
String s = scan.nextLine();
if (s.equalsIgnoreCase("n")) {
System.out.print("Quitting...");
playGame = false;
}
}
}
public void start() {
int number = (int) (Math.random() * 1001 );
int guess = -1;
int guessCount = 0;
String guessStr, playerName;
String quit = "quit";
Scanner scan = new Scanner(System.in);
boolean play = true;
System.out.print("Welcome to the greatest guessing game of all time!" +
"\nGuess a number between 1-1000!" +
"\nType \"quit\" to quit.");
long startTime = System.currentTimeMillis();
System.out.println("\nDEBUG, nr is: " + number);
while (guess != number && play) {
try {
System.out.print("\nEnter your guess: ");
guessStr = scan.nextLine();
if (guessStr.equalsIgnoreCase("quit")) {
play = false;
System.out.println("Quitting...");
return;
}
guess = Integer.parseInt(guessStr);
if (guess <= 1 || guess > 1000) {
System.out.println("Invalid guess, won't count, try again!");
}
if (guess < number) {
System.out.println("Too low, try again!");
guessCount++;
}
if (guess > number) {
System.out.println("Too high, try again!");
guessCount++;
}
}
catch(NumberFormatException e) {
System.out.println("Sorry, only numbers. Try again!");
}
catch (InputMismatchException ex) {
System.out.println("Sorry, only numbers. Try again!");
}
}
if (guess == number) {
long endTime = System.currentTimeMillis();
long gameTime = endTime - startTime;
System.out.println("Nice, the correct number is " + number + "!");
System.out.print("You nailed it after " + (int)(gameTime)/1000 + " seconds and " + guessCount + " tries!");
System.out.println("\nEnter your name!");
playerName = scan.nextLine();
score.add(new highScore(guessCount, gameTime, playerName));
Collections.sort(score);
System.out.println("Name ------- Guesses -------- Time in ms");
for (highScore h: score) {
System.out.println(h);
}
}
}
}
You just need to modify your compareTo method to consider the equality case also. And then move to the next comparison: -
public int compareTo(highScore hs) {
if (this.guessCount == hs.guessCount) {
return (new BigDecimal(this.playerTime)).compareTo(
new BigDecimal(hs.playerTime)
} else {
return Integer.valueOf(this.guessCount).compareTo(
Integer.valueOf(hs.guessCount));
}
}
The compareTo() method of highScore has to be implemented as below
public int compareTo(highScore hs)
{
if (((Integer)this.guessCount).compareTo(((Integer)hs.guessCount)) > 0)
return 1;
else
{
if(this.guessCount == hs.guessCount)
{
if(this.playerTime > hs.playerTime)
{
return 1;
}
else
{
return -1;
}
}
return -1;
}
}
- Whenever you need to sort on the basis of more than 1 attributes, go for java.util.Comparator Interface.
- Use the compare() method of Comparator<T> along with Collections.sort(List l, Comparator c) to sort you list.