java - establishing new variables based on input - java

So, the program calls for a bowling game. Once you ask how many players, every player gets 2 throws to knock down 10 pins (simulated by random numbers). If you knock them all down with the first go, then you get 20 points, if on your second go you get 15 points, other than that score = throw 1 + throw 2.
The tricky part for me has been getting each player to alternate frames (2 throws = 1 frame, up to ten frames per player) while the program keeps track of everyone's score! I thought I had it with this but the randoms just add up ill post the output on the bottom
import java.util.Scanner;
public class Bowling {
public static void main(String [] args){
Scanner input = new Scanner (System.in);
Game aNew = new Game();
int player;
int i;
int j;
int nPlay;
System.out.print("How many players are there?: ");
nPlay = input.nextInt();
for (j = 1; j<= 10; j++) {
for (i = 1; i <= nPlay; i++ ){
player = i; // i tried player i = new Player() but get error "value
aNew.getScore(player); // already used in scope""
}
}
Games class:
import java.lang.Math;
public class Game {
int score = 0;
int player;
int ran1;
int ran2;
public Game() {
}
public int getScore(int player){
ran1 = (int) (9 * Math.random());
ran2 = (int) (((10 - ran1)) * Math.random());
if (ran1 == 10){
score += 20;
} else if (ran1 + ran2 == 10){
score += 15;
} else {
score += ran1 + ran2;
} System.out.println("Player " + player + " score is: " + score + "\n");
System.out.println("ran1: " + ran1 + " ran2: " + ran2);
return score;
}
}
Player class:
public class Player {
/** this class is not doing anything, however i would like for an object to store a score for every player to keep track if that is possible?*/
int score;
public Player (){
int score;
}
}
Output: (suspicious how every time the last player had the highest or I would have never noticed it didn't work!)
How many players are there?: 2
Player 1 score is: 2
ran1: 1 ran2: 1
Player 2 score is: 11
ran1: 8 ran2: 1
Player 1 score is: 16
ran1: 5 ran2: 0
Player 2 score is: 21
ran1: 4 ran2: 1
Player 1 score is: 29
ran1: 8 ran2: 0
Player 2 score is: 35
ran1: 5 ran2: 1
Player 1 score is: 40
ran1: 3 ran2: 2
Player 2 score is: 47
ran1: 6 ran2: 1
Player 1 score is: 56
ran1: 8 ran2: 1
Player 2 score is: 61
ran1: 5 ran2: 0
Player 1 score is: 68
ran1: 7 ran2: 0
Player 2 score is: 77
ran1: 8 ran2: 1
Player 1 score is: 85
ran1: 4 ran2: 4
Player 2 score is: 90
ran1: 4 ran2: 1
Player 1 score is: 97
ran1: 7 ran2: 0
Player 2 score is: 103
ran1: 3 ran2: 3
Player 1 score is: 107
ran1: 4 ran2: 0
Player 2 score is: 114
ran1: 3 ran2: 4
Player 1 score is: 121
ran1: 7 ran2: 0
Player 2 score is: 125
ran1: 0 ran2: 4

Your Player class is currently doing nothing. Fix this by first making accessors and modifiers for your Player.score variable like this. Maybe even give them a name:
public class Player {
int score;
String name;
public Player(String name) { this.name = name; }
public void getName() { return this.name; }
public void setScore(int newScore) { score = newScore; }
public int getScore() { return score; }
}
now your game class should have a collection type of players like
public class Game {
List<Player> players = new List<Player>();
public Game() {
}
public void AddPlayer(Player p) {
players.add(p);
}
public Player getPlayer(int index) { return players.get(index); }
public void playerBowl(Player p) {
ran1 = (int) (9 * Math.random());
ran2 = (int) (((10 - ran1)) * Math.random());
if (ran1 == 10){
p.setScore(p.getScore() +20);
} else if (ran1 + ran2 == 10){
p.setScore(p.getScore() +15);
} else {
p.setScore(p.getScore() + ran1 + ran2);
} System.out.println("Player " + p.getName() + " score is: " + p.getScore() + "\n");
System.out.println("ran1: " + ran1 + " ran2: " + ran2);
}
}
Ill leave the main for you to figure out :D. Sorry if the syntax is a little off, I wrote it in the edit window :/

Seems to me that your troubles start here:
player = i; // i tried player i = new Player() but get error "value
aNew.getScore(player); // already used in scope""
The correct way would be:
Player i = new Player(); //mind the capital!
For the rest: You would probably want to use a List of Players and initialize this list once you know how many players there are. Finally, the getScore function should not modify the score variable in the Game class, but rather the score variable of a Player (with player.score = 20). You need to know your players in your Game class, but you can do this in several ways: pass a player as an argument to getScore, or pass the whole list of players at an earlier point.
All in all, there is quite a bit of code to rewrite for you, but I'm sure playing with this code will be very educational.

Related

A dice game between two players. The player who gets 21 first wins [closed]

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 4 years ago.
Improve this question
There is a game between two players, and the first player who gets 21 points wins.
when both players reach 21 on the same number of rolls, there is a tie.
The points are added up as the dices are rolled.
The format of this should be done as follows.
* GAME 1 *
Roll Player 1 Player 2
1 5 4
2 7 10
3 12 14
4 13 16
5 19 21
player 2 wins!
The code below is what I've tried so far.
I'm stuck because I have no idea how to create a chart like the one above.
If I try to make the chart inside the while loop, it will repeatedly make the chart.
If I try to make the chart outside the while loop, which is after the while loop, it will
execute only when one of the players reach points 21.
Can anyone help me out how to make this code?
import java.util.*;
public class Dice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
System.out.println("How many games do you want to play?");
int games= input.nextInt();
System.out.println(" *** Game 1 *** ");
int sum1=0;
int sum2=0;
while (sum1!=21&&sum2!=21){
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
sum1=+roll1;
sum2=+roll2;
}
if(sum1>sum2){
System.out.println("player 1 wins");
}
else if(sum1<sum2){
System.out.println("player 2 wins");
}
}
}
A few problem
you want to test that sum1 and sum2 are less than 21 not !=
you should use += not =+
Introduced a counter for the rolls
Note
I think you logic is not correct, though as what should happen if both get to 21 on the same throw?
System.out.println(" *** Game 1 *** ");
int sum1=0;
int sum2=0;
int rollNumber = 1;
System.out.println("Roll\tPlayer 1\tPlayer 2");
while (sum1 < 21 && sum2 < 21){
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
sum1 += roll1;
sum2 += roll2;
if (sum1 > 21) sum1 = 21;
if (sum2 > 21) sum2 = 21;
System.out.format("%d\t%d\t%d%n", rollNumber++, sum1, sum2);
}
if(sum1>sum2){
System.out.println("player 1 wins");
}
else if(sum1<sum2){
System.out.println("player 2 wins");
}
}
output
*** Game 1 ***
Roll Player 1 Player 2
1 5 4
2 4 5
3 2 3
4 3 1
5 3 3
6 2 3
7 5 6
player 2 wins
If you want a printout each turn, you need to print inside the while loop. Here would be an example snippet that has such a feature. Of course, this isn't a complete program, and could use some formatting love.
int sum1 = 0;
int sum2 = 0;
int round = 1;
while(sum1 < 21 && sum2 < 21) { // not sure if you noticed this bug in your code..
sum1 += rand.nextInt(6) + 1;
sum2 += rand.nextInt(6) + 1;
System.out.println("Round " + round + " " + sum1 + " " + sum2);
round++;
}

Creating a lottery draw method

Hello.
I'm working on a lottery system in a game that I'm working on.
My goal is to get a player randomly based on their amount input and the total value of the lottery pot at the moment of the drawing. E.G Pot is 100k, Player1 has put in 10k, and Player2 has put in 20k, meaning Player 1 has 1/10 chance of winning and Player2 has a 2/10 chance of winning.
totalPot, this is the total value of the pot
randomNR, this is a random number generation
userInput, this is the total input that the user has put into the lottery.
player, this is the player who inputted the amount above
I have already tried this:
public static void drawLottery() {
int totalPot = lotteryPot - 250;
int randomNR = Misc.randomInt(0, lotteryPot);
List<Player> keys = new ArrayList<Player>(lotteryEntries.keySet());
Collections.shuffle(keys);
for(int i = 0; i < totalPot;) {
for (Player o : keys) {
i += lotteryEntries.get(o);
if (i >= randomNR) {
System.out.println("Winner: " + o.getUsername() + " -> Random number: " + randomNR);
}
break;
}
break;
}
}
But that just caused the same player to be drawn over and over again.
I don't know what to do and help would be greatly appreciated.
You can iterate over all the lottery entries and keep a cumulative total. The first time the cumulative total exceeds the winning number is the player that has won.
For example:
Player 1: 20
Player 2: 30
Player 3: 50
Player 4: 10
The winning number is chosen to be 51. The cumulative total starts at 20. This is not greater than 51, so player 1 has not won. Then we increment to 50. Not greater than 51, player 2 has not won. Then we increment to 100 which greater than 51 so player 3 has won.
public static Player getWinner(int winningNumber, Map<Player, Integer> lotteryEntries)
{
int cumulativeProbability = 0;
for (Map.Entry<Player, Integer> entry : lotteryEntries.entrySet())
{
cumulativeProbability += entry.getValue();
if (cumulativeProbability >= winningNumber)
{
return entry.getKey();
}
}
throw new RuntimeException("Winning number not within total pot size");
}
Use the pot to ponderate your random choice. Pick a number inside the pot. define a range in the pot for every player. If the picked number is in the range, this player is the winner.
For example, the pot is 30. Player 1 put 10 and player 2 put 20. You pick a random number between 0 and 30. Let's say random gives us 23. The range corresponding to player 1 is 0 to 10 and the range corresponding to player 2 is 10 to 30. Then player 2 has won.
This should look like this :
//pick a random number inside the pot
Random rand = new Random();
int randNum = rand.nextInt(totalPot);
//Define the pot range corresponding to a player
int rangeStart = 0;
int rangeEnd = 0;
//go through all enties (all players)
for(Entry entry : lotteryEntries.entries()) {
//Define the range corresponding to this player
value = entry.getValue()
rangeStart = rangeEnd;
rangeEnd += value;
//If the picked random num is in the range, this player is the winner
if( randNum >= rangeStart && randNum < rangeEnd) {
System.out.println("Winner: " + entry.getKey().getUsername()):
System.out.println("randNum: " + randNum);
break;
}
}

Attempting to roll two dice randomly and add the sums till it reaches twentyone

I am trying to code a program that rolls two dice randomly, adds them together, and keeps doing that until it reaches 21. If it reaches 21 it wins but if it hits over 21 it loses.
This is what I have so far, it would be great if I could have some assistance on how to get the dice rolling properly. I am a beginner in java so still trying to understand the syntax.
import java.util.Random;
public class TwentyOne{
public static void main(String[] args) {
int dice1;
int dice2;
welcome();
rollingDice(int dice1,int dice2);
}
public static void welcome() {
System.out.println("Welcome to the game of Twenty-One! FEELING LUCKY?! goodluck!");
}
public static int rollingDice(int dice1, int dice2) {
dice1 = (int)(Math.random()*6 + 1);
dice2 = (int)(Math.random()*6 + 1);
int sum = dice1 + dice2;
return sum;
}
}
As #KamalNayan stated above, you need to loop rollingDice until you are at or above 21, and there is no need to pass int agruments in to the rollingDice method since the rolled die values are generated within the scope of that method. Some printing of what's going on also helps to demonstrate what's going on during runtime:
public static void main(String[] args) {
welcome();
int total = 0;
while (total < 21) {
total += rollingDice();
};
System.out.println("Total for all rolls was: " + total);
if (total == 21) {
System.out.println("You win!");
}
else {
System.out.println("You lose.");
}
}
public static void welcome() {
System.out.println("Welcome to the game of Twenty-One! FEELING LUCKY?! goodluck!");
}
public static int rollingDice() {
int dice1 = (int) (Math.random() * 6 + 1);
int dice2 = (int) (Math.random() * 6 + 1);
int sum = dice1 + dice2;
System.out.println(String.format("dice1: %d dice2: %d for a total: %d", dice1, dice2, sum ));
return sum;
}
Here the output from a won game:
Welcome to the game of Twenty-One! FEELING LUCKY?! goodluck!
dice1: 4 dice2: 1 for a total: 5
dice1: 1 dice2: 4 for a total: 5
dice1: 1 dice2: 3 for a total: 4
dice1: 6 dice2: 1 for a total: 7
Total for all rolls was: 21
You win!
Process finished with exit code 0

How to count a variable using a for loop?

I'm designing a program that simulates a game of dice. The code calculates the total points get each round and the player that wins each round.
I am trying to get the overall number of wins and the total points. I tried using a for loop in the main class but I wasn't sure how to implement it in this problem.
Round 1:
player 1 3 1 5 points: 9
player 2 2 6 6 points: 14
Winner is player 2
Round 2:
player 1 3 6 5 points: 14
player 2 2 3 2 points: 7
Winner is player 1
Round 3:
player 1 3 3 6 points: 12
player 2 5 4 6 points: 15
Winner is player 2
.
Total wins: player 1-->1/ player 2-->2
Total points: player 1-->35/ player 2-->36
Main class
import java.util.Scanner;
public class Game {
// ------------------- FIELDS ------------------------
// Create instance of Scanner class
public static Scanner input = new Scanner(System.in);
// variables
public static ThreeDiceScorer thrdiesc;
public static int diceArray [];
// ------------------ METHODS ------------------------
public static void main(String[] args) {
int rounds; // input by user
int players; // input by user
System.out.print("Please input number of rounds (grater or equal than 0) --> ");
rounds = input.nextInt();
System.out.print("\n");
System.out.print("Please input number of players (grater or equal than 2) --> ");
players = input.nextInt();
System.out.print("\n");
for (int r = 0; r < rounds; r++) { // loop for number of rounds
int max = 0;
int max_p = 0;
System.out.println("Round " + (r+1) + ": ");
for (int p = 0; p < players; p++) { //loop for players
int diceArray[] = new int[3];
for (int i = 0; i < diceArray.length; i++) { // loop for dice Array (data of Array)
diceArray [i] = 1 + (int)(6 * Math.random());
}
// Create new ThreeDice and calculator instances
thrdiesc = new ThreeDiceScorer(diceArray [0], diceArray [1], diceArray [2]);
//Calculate
thrdiesc.calcTotalPoints();
thrdiesc.printResult(p, r);
if (thrdiesc.total > max) {
max = thrdiesc.total;
max_p = p;
}
}
System.out.println("Winner is player " + (max_p + 1) + "\n");
}
System.out.println("Total wins: " );
System.out.println("Total points: " );
}//end Main Method
} // end Class
Calculation class
public class ThreeDiceScorer {
public static int total;
public int die1;
public int die2;
public int die3;
public ThreeDiceScorer(int s1, int s2, int s3) {
die1 = s1;
die2 = s2;
die3 = s3;
}
public void calcTotalPoints() {
int sumOfDice = die1 + die2 + die3;
total= sumOfDice;
}
public void printResult(int p, int r) {
System.out.println("player " + (p + 1) + " " + die1 + " " + die2 + " " + die3 + " " + "points: " + total);
}
}
I tried using a for loop in the main class but I wasn't sure how to implement it in this problem.
I would say, do one thing at a time. Test your implementation and once you confirmed that it is working, then move on. The sequential steps to reach your goal would be:
Steps
Implement dice rolling for one player first. (Can do it in a method)
Call the above implemented method for 2nd player's dice roll.
Decide winner
Once steps 1-3 were implemented correctly, enclose steps 1-3 within a loop (preferable a for-loop for this particular case)
//Example:
int numOfRounds = 3; //can receive this from user input
for(int x=0; x<numOfRounds; x++){
rollDice(playerOne);
rollDice(playerTwo);
decideWinner(playerOne, playerTwo);
}
Once steps 1-4 is tested and working fine. Implement the display of total score:
//Example:
int numOfRounds = 3; //can receive this from user input
for(int x=0; x<numOfRounds; x++){
rollDice(playerOne);
rollDice(playerTwo);
decideWinner(playerOne, playerTwo);
}
displayFinalScore();
Total score and total wins can be stored in a very simple Player class which looked like this:
public class Player{
private String name;
private int totalScore;
private int totalWins;
}
Dynamic Multi-player
I tried to keep the solution as short and simple as possible for your understanding. But if you want the program to dynamically take in n number of players. The same program flow still applies.
In step 4, you can do it as:
int numOfPlayers = 2; //can receive this from user input
ArrayList<Player> players = new ArrayList<Player>();
for(int x=0; x<numOfPlayers; x++)
numOfPlayers.add(new Player("Player " + (x+1)));
for(int x=0; x<numOfRounds; x++){
for(int y=0; y<players.size(); y++) //iterate through all players
rollDice(players.get(y));
decideWinner(players); //decide the winner from all the players
}
There are many ways to solve this, I would add two counters like int count = 0 and increment them: one every time there is a victory (for ex.: if(victory) { c++ })and the other through the expression count = count + points.
Remember to implement these ints at the beginning or the for loop will reset count1 and count2 to 0.

Dynamic Programing to solve subset of given sum

Given the following Input
10 4 3 5 5 7
Where
10 = Total Score
4 = 4 players
3 = Score by player 1
5 = Score by player 2
5 = Score by player 3
7 = Score by player 4
Output should print the index of players who's score equal to 10. So for given above output it should print 1 4 or 2 3 because player 1 + player 4 score adds up to 10 and so does the scores by player 2 and player 3. I do not need to PRINT BOTH or ALL combinations. I just want to print any one combination that works.
For INPUT : 8 3 2 2 4 OUPUT : 1 2 3 since scores of player 1 player 2 and player 3 equal the total score of 8
So i have been reading Dynamic programing tutorials and videos for past week and also got help on stack overflow to fix my initial code.
Following is what i have so far
public boolean findSolution(int[] scores, int total) {
int W = total;
int players = scores.length;
boolean[][] myArray = new boolean[players + 1][total + 1];
for (int player = 0; player <= players; player++) {
myArray[player][0] = true;
}
for (int score = 1; score < total; score++) {
myArray[0][score] = false;
}
for (int player = 1; player <= players; player++) {
for (int score = 1; score <= total; score++) {
myArray[player][score] = myArray[player - 1][score];
if (score >= scores[player - 1]) {
myArray[player][score] = myArray[player - 1][score
- scores[player - 1]]
|| myArray[player][score];
}
}
}
return myArray[players][W];
}
This logic creates 2d array and does exhaustive search to see if the combination for a given total is possible and will return true if it is and false if it is not. Now i am having trouble printing the indexes of the players that make it true. So would highly appreciate if someone can help me print the index of a set of players who's score equals the total. I dont NEED TO PRINT all combinations.
Also please ask any question if you don't understand as i am not native English speaker.
Ok, so after you have created and updated boolean array myArray.
We will iterate from the last player to the first player, checking if we can use the current player in our final result
int currentScore = total;//Maintain the current score.
for(int i = lastPlayer ; i >= 0; i--){
}
Inside the for loop, to check if this current i player is belong to our final set of player, we need to check if there exists a solution for currentScore - score of i player
if (currentScore >= scores[i] && (i == 0 || myArray[i - 1][currentScore - scores[i]]) {
//Update current score
currentScore -= scores[i];
//Print name of the player.
System.out.println("Player " + i);
}

Categories