How to randomize two players to "X" and to "O? - java

I'm making a tic tac toe game and I have randomily assign player 1 one to either "X" or "O" and same with player 2. I have no clue how to start the code
It should make player one either X or O and make player 2 whatever is left over from player 1

You can generate a random number between for example 0 and 1 by using a random object or the Math.Random() function.
Based on the random number you can select via if and else, which letter "X"/"O" the first player will get.
The second player can then be assigned what is left.
Have look on Math.Random:
Math.random() explanation

public class RandomTicTacToeSymbols {
public static void main(String args[]) {
String[] symbols = {"X" , "O"};
int randomIndex = (int) Math.round( Math.random());
String playerOneSymbol = symbols[randomIndex];
String playerTwoSymbol = symbols[(randomIndex+1) % 2];
System.out.println(String.format("Player 1 -> %s - Player 2 -> %s", playerOneSymbol, playerTwoSymbol) );
}
}

Related

Java, two objects, one cannot be resolved in methods, other can

Having an issue with two objects I've declared. One is working fine, the p1, while the other, p2, cannot be resolved as a symbol of my methods.
The two objects are located in main, while the methods are located in a Player class. I've tried moving variables and the objects around, but to no avail, as it causes other issues with scope.
Is this an issue with a scope? But then why is one object seen in the methods and one isn't? New to the whole object-oriented stuff as well, and it's throwing me for a loop.
The error is "cannot resolve symbol 'p2' "
The below code is the main method so far, then one of the methods that have the p2 error.
Thank you in advance for any assistance.
public static void main(String[] args) {
Player p1 = new Player(name1); // instantiation of player 1 object; given first player's name
Player p2 = new Player(name2); // instantiation of player 2 object; given second player's name
}
public void attack1(Player p1) { // first method in which player 2 attacks player 1
Random rnd = new Random(); // instantiation of new random object
int dmg = rnd.nextInt(26) - 1; // setting of variable dmg to = a random number between 0 and 25
if (dmg >= 0 && dmg <= 15) { // if statement checking if dmg is between 0 and 15
p1.health = p1.health - dmg; // if dmg is between 0 and 15, reduce value from player 1 health
System.out.printf("%s attacked %s and %s's health is now %d.", p2.name, p1.name, p1.name, p1.health); // print to screen results of attack1
} else if (dmg > 15) { // if dmg value is greater than 15, player 2 misses player 1
System.out.printf("%s attacked %s and missed.", p2.name, p1.name); // print to screen results of missed attack1
}
The problem is that p2 is not defined in the scope of the function attack1. Either pass both p1 and p2 to attack1 or make p1 and p2 instance variables of your class.
public void attack1(Player p1, Player p2) { // first method in which player 2 attacks player 1
Random rnd = new Random(); // instantiation of new random object
int dmg = rnd.nextInt(26) - 1; // setting of variable dmg to = a random number between 0 and 25
if (dmg >= 0 && dmg <= 15) { // if statement checking if dmg is between 0 and 15
p1.health = p1.health - dmg; // if dmg is between 0 and 15, reduce value from player 1 health
System.out.printf("%s attacked %s and %s's health is now %d.", p2.name, p1.name, p1.name, p1.health); // print to screen results of attack1
} else if (dmg > 15) { // if dmg value is greater than 15, player 2 misses player 1
System.out.printf("%s attacked %s and missed.", p2.name, p1.name); // print to screen results of missed attack1
}
As a side note, I would suggest that you remove attack1 and (presumably) attack2 and instead write a method public void attack(Player source, Player target) to reduce the amount of duplicated code.
public void attack(Player source, Player target) {
Random random = new Random();
int damage = random.nextInt(26) - 1;
if(damage >= 0 && damage <= 15) {
target.health -= damage;
System.out.printf("%s attacked %s and %s's health is now %d.", source.name, target.name, target.name, target.health);
} else if(damage > 15) {
System.out.printf("%s attacked %s and missed.", source.name, target.name);
}
}

How do I populate an array with randomly distributed symbols?

Newbie programmer here, using Java 8. I'm trying to build a PacMan game and am working on the method that builds the grid. My opening comments for the program tell you everything you need to know. I'm stuck on trying to connect the random # generator's variable to printing an equal # of cookies ("O"), and fill the rest of the array with dots (".").
/**
* This program is meant to get dimensions for a 2D array from the player.
* A grid is then displayed to player's specs filled with dots and cookies.
* The cookies must compose 20% of the total grid and be randomly
* distributed. The user will then be offered a menu of options to either
* turn left or right, or move, or exit the game. The player's choice moves
* "PacMan" around grid to eat cookies. The grid must be displayed throughout
* the game showing changes as player continues moves. If a cookie is eaten,
* a statement is printed that indicates a cookie was eaten and adds 1 to
* your score. At the end of the game, it tracks the number of moves it took
* to eat all the cookies.
*/
import java.util.Scanner;
public class PacManGame
{
public static void main(String[] args)
{
int X, Y; //Variables for number of grid rows X, and columns Y
Scanner input = new Scanner( System.in );
System.out.println();
System.out.print( "Enter the number of rows you would like in your game grid: " );
X = input.nextInt();
System.out.println();
System.out.print( "Enter the number of columns you would like in your game grid: " );
Y = input.nextInt();
System.out.println();
buildGrid(X, Y); // Calls buildGrid method
} // Closes main method
public static void buildGrid(int X, int Y) // Method for actually building the grid
{
int gameGrid [][] = new int [X][Y]; // Array built from user's input for dimensions
int totalGridSize = X * Y; // Gets the total grid size
double cookieTotal = totalGridSize * (.2); // Calculates the 20% of cookies that will be on grid
int theCookies = (int)(cookieTotal*Math.random())+1; //Assigns the randomly generated number
int i, j, k = 0; // Initialize loop counters
for (i = 0; i < X; i++)
{
for (j = 0; j < Y; j++)
{
gameGrid[X][Y] = k;
k++;
System.out.print("." + ("O" * theCookies)); // I know I can't do this, but how to fix?
}
}
} // Closes buildGrid method
} // Closes PacManGame class
It's better to exchange the array coordinates, so that first goes Y, then X. You may keep in your array 1 for cookie and 0 for the rest. To put cookieTotal of cookies you may use the following code:
new Random().ints(0, totalGridSize).distinct().limit(cookieTotal)
.forEach(pos -> gameGrid[pos/X][pos%X] = 1);
Here we generate random numbers from 0 to totalGridSize-1 and get cookieTotal distinct from it. After that we translate these numbers to the coordinates and set the corresponding array element.
To print the gaming field, you need to translate 0 to '.' and 1 to "O":
for (int[] row : gameGrid)
System.out.println(IntStream.of(row).mapToObj(val -> val == 1 ? "O" : ".")
.collect(Collectors.joining()));
Here's the complete body of your buildGrid:
int gameGrid[][] = new int[Y][X];
int totalGridSize = X * Y;
int cookieTotal = totalGridSize / 5;
new Random().ints(0, totalGridSize).distinct().limit(cookieTotal)
.forEach(pos -> gameGrid[pos / X][pos % X] = 1);
for (int[] row : gameGrid)
System.out.println(IntStream.of(row).mapToObj(val -> val == 1 ? "O" : ".")
.collect(Collectors.joining()));

How to display a certain string for an integer?

I have to make a Poker Dice game for class. I am able to successfully random five numbers 1 to 6 (to resemble rolling a die five times). However, I need to show "Nine" for 1, "Ten" for two, etc. I am using an array to hold the numbers. I can't seem to figure out how to assign a string output for each int.
public static void main(String[] args) {
int[] player = new int[5];
String[] cards = new String[] {"Nine", "Ten", "Jack", "Queen", "King", "Ace"};
System.out.println("User: " + playerHand(player, cards));
}
public static String playerHand(int[] player, String[] cards) {
String hand = "";
for (int i = 0; i < player.length; i++) {
player[i] = (int) (Math.random() * (6 - 1) + 1);
hand += player[i] + " ";
}
return hand;
}
You've put your strings in an array, so you just add an element from the array to your hand string:
hand += cards[player[i]] + " ";
There is, however, still a problem with your code. You obtain the random numbers as follows:
player[i] = (int) (Math.random() * (6 - 1) + 1);
You probably expect this to be a number from 1 to 6. However, Math.random() returns a double from 0 (inclusive) to 1 (exclusive). That means that player[i] will never be assigned 6. This error kind of solves another error: since Java arrays are zero-based, the element with index 6 does not exist. (Thus, if 6 would have been chosen, your program would have aborted with an error message.) But still, the number 0 and thus the word "Nine" will never appear in your solution. So you have to change the two lines to:
hand += cards[player[i] - 1] + " ";
and
player[i] = (int) (Math.random() * 6 + 1);
respectively.
Consider making the cards array a static class member; then you don't need to pass the array to the playerHand method as an argument.
You might use a switch block
switch(array[i]){
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
etc...

How do I keep my random match generator from repeating? [duplicate]

This question already has answers here:
Non repeating random numbers
(2 answers)
Closed 8 years ago.
I've made a random wrestling match generator that I've adapted from a random phrase generator from a textbook. I'd like to know how to make it so the same name isn't done twice on the same run. Can't have The Crusher vs. The Crusher, right?
public class matchOMatic {
public static void main (String [] args) {
String [] wordListOne = {"The Crusher", "The Main Man", "The Macho-man, Randy Savage", "The Nature Boy, Rick Flare", "Batista", "Hollywood Hulk Hogan", "Vader", "The Undertaker", "Stone Cold Steve Austin" };
String [] wordListThree = {"The Crusher", "The Main Man", "The Macho-man, Randy Savage", "The Nature Boy, Rick Flare", "Batista", "Hollywood Hulk Hogan", "Vader", "The Undertaker", "Stone Cold Steve Austin"};
int oneLength = wordListOne.length;
int threeLength = wordListThree.length;
int rand1 = (int) (Math.random() * oneLength);
int rand3 = (int) (Math.random() * threeLength);
String phrase = wordListOne[rand1] + " and in the opposite corner is his opponent, " + wordListThree[rand3];
System.out.print("In this corner we have " + phrase);
System.out.println("!");
}
}
Very simple solution for this!
Just put this after you give values to rand3 and rand2:
while(rand3 == rand1) {
rand3 = (int) (Math.random() * threeLength);
}
This will keep choosing a new value for rand3 until the values are different!
I hope this helps. Good luck with your program :)
The cleanest solution is to store the names in an ArrayList rather than an array of strings, shuffle the list, and iterate through in pairs to create matches. Shuffling a list of length N is O(N), and this is guaranteed to not produce duplicates across the scheduled matches.
You could pick the next one ( or the one before) if the random turns out to be the same.
if ( rand3 == rand1 )
rand3 = (rand3 +1) % threeLength
Edit:
As noted below this creates bias which is not good.
other possible solution is not to include the first randomly picked index in the next random roll
// -1 because we are not including the same pick
int rand3 = (int) (Math.random() * ( threeLength-1) );
// fix the index because we haven't actually removed it from the array
if (rand3 >= rand1)
rand3 = (rand3 +1) % threeLength

Rework blackjack game

I'm trying to create a blackjack game, where the player starts off with 2 cards, and then asked if he/she would like to have another card (user input: yes or no), if yes, another card is added to the total. if no, the game just terminates.
Here is a sample output I'm trying to get:
And this is what I have so far (It's probably wrong in terms of the placement):
import java.util.Scanner;
public class BlackJackGame {
public static void main(String[] args) {
int randomnum1 = (int) (1 + Math.random() * 10);
int randomnum2 = (int) (1 + Math.random() * 10);
int randomnum3 = (int) (1 + Math.random() * 10);
int total;
char anotherCard = 'y';
Scanner input = new Scanner(System.in);
System.out.println("First cards: " + randomnum1 + ", " + randomnum2);
total = randomnum1 + randomnum2;
System.out.println("Total: " + total);
while (anotherCard != 'n')
{
System.out.print("Card: " + randomnum3);
System.out.print("Do you want another card? (y/n): ");
anotherCard = input.next().charAt(0);
}
}
}
Tips and reworking the source code will be highly appreciated.
As Far as card games go, there are 52 cards in a deck, and I'm assuming there's one deck.
If you want it to be a fair game, then you have to keep that in mind.
But if you just want output to look correct, you just have to avoid getting more than 4 aces, 2's, 3's, and 4's.
One way to achieve this would be to make an int array of size 52 with 4 of each card. I suppose Ace would be 1 and 10,J,Q,K would be 10, so there would be 16 10's.
Get a random number between 0 and 51 to get the index of the array you want to use. Once you use that index, set the value of that array = -1, and always check for -1 before using that index, and if it is -1, get another random value.
int [] deck = size 52 array with 4 of each card.
int random = get random number between 0 and 51.
while(deck[random] == -1){
random = get random number between 0 and 51.
}
int card1 = deck[random]
deck[random] = -1;
something like that.. I just did that quickly, hopefully you get the idea.
Here are the tips you requested:
You need to introduce a variable to keep track of your sum. For example, you could initialize it with: int sum = randomnum1 + randomnum2; and keep adding the next card to it inside the loop: sum += randomnum3;
You need to generate randomnum3 inside the while loop. This way, you will get a different card every time. Basically, you have to call the random function every time you generate a card, not just once. Otherwise the value of randomnum3 will be unchanged and you will get the same card over and over.
To exit when you get to 21, you would have to use if and possibly break within the loop, once you have added the current card to the sum: if(sum > 21) { break; }
Alternatively, you can set the value of anotherCard to 'n' instead of using a break
You should keep track of which cards the user has already gotten if you want to simulate an actual deck. This is not technically necessary for the program you appear to be writing though.
Here are a few simple improvements for you to look over. I'll leave it like this as part of the joy of learning to program is in the discovery. As a next step I'd suggest generating a dealers hand and then seeing if the player can beat it. Good luck!
public static void main(String[] args) {
int card1 = (int) (1 + Math.random() * 10);
int card2 = (int) (1 + Math.random() * 10);
int total = card1 + card2;
System.out.println(String.format("First cards: %d & %d. Total %d", card1, card2, total));
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("Do you want another card? (y/n): ");
char anotherCard = input.next().charAt(0);
while (anotherCard != 'n' && total < 21) {
int nextcard = (int) (1 + Math.random() * 10);
total += nextcard;
System.out.println(String.format("You drew a %d. Your total is now %d", nextcard, total));
if (total > 21) {
System.out.println("You busted!");
} else {
System.out.print("Do you want another card? (y/n): ");
anotherCard = input.next().charAt(0);
}
}
}

Categories