Untitled
unknown
plain_text
a year ago
3.0 kB
10
Indexable
package javagame;
import java.util.Scanner;
import static java.lang.Math.random;
public class JavaGame {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] choices = new String[3];
choices[0] = "paper";
choices[1] = "scissors";
choices[2] = "rock";
boolean again = false;
// Arrays to store coin rewards
int[] playerCoins = new int[1];
int[] computerCoins = new int[1];
do {
// random index (for the computer)
int rand = (int) (random() * 3);
System.out.print("Enter your choice (paper/scissors/rock): ");
String input = in.nextLine();
System.out.printf("The computer's choice is: %s\n", choices[rand]);
int idx = rand;
for (int i = 0; i < 3; i++) {
if (i == rand) continue;
if (compareStrings(input, choices[i])) idx = i;
}
// Determine the outcome of the game
if (rand - idx == -1 || rand - idx == 2) {
System.out.println("The player wins");
// Generate 2 random numbers as the coin rewards
int playerReward = (int) (Math.random() * 10);
int computerReward = (int) (Math.random() * 5); // computer gets a smaller reward for losing
// Update coin totals
playerCoins[0] += playerReward;
computerCoins[0] += computerReward;
System.out.printf("Player gains %d coins, total: %d\n", playerReward, playerCoins[0]);
System.out.printf("Computer gains %d coins, total: %d\n", computerReward, computerCoins[0]);
} else if (rand == idx) {
System.out.println("Tie");
again = true;
} else {
System.out.println("The Computer wins");
// Generate 2 random numbers as the coin rewards
int playerReward = (int) (Math.random() * 5); // player gets a smaller reward for losing
int computerReward = (int) (Math.random() * 10);
// Update coin totals
playerCoins[0] += playerReward;
computerCoins[0] += computerReward;
System.out.printf("Player gains %d coins, total: %d\n", playerReward, playerCoins[0]);
System.out.printf("Computer gains %d coins, total: %d\n", computerReward, computerCoins[0]);
System.out.println("Oh no! Try again.");
}
} while (again);
}
public static boolean compareStrings(String a, String b) {
int sz1 = a.length(), sz2 = b.length();
if (sz2 != sz1) return false;
for (int i = 0; i < sz1; i++) {
if (a.charAt(i) != b.charAt(i)) return false;
}
return true;
}
}
Editor is loading...
Leave a Comment