Problem with Class scope, how should I resolve this? - java

I started my first java project and I get stuck in class scope. I cant initiate below code:
if (guessAttemts = MaxGuesses) {
System.out.println("Sorry you used all your nine chances. Game Over.)
I will be appreciate if someone will help me to clarify what I doing wrong with that code: This NewGame class look like below.
class NewGame {
GuessAttempts GuessAttempts = new GuessAttempts();
private String WordToGuess;
private String CorrectGuesses;
private String misses;
int guessAttempts;
int MAX_Guesses = 9;
public NewGame(String WordToGuess) {
this.WordToGuess = WordToGuess;
CorrectGuesses = "";
misses = "";
guessAttempts = 0;
}
public boolean UserGuessing(char letter) {
boolean isHit = WordToGuess.indexOf(letter) != -1;
if (isHit) {
CorrectGuesses += letter;
} else {
misses += letter;
}
guessAttempts =+ 1;
return isHit;
}
if (guessAttemts = MaxGuesses) {
System.out.println("Sorry you used all your nine chances. Game Over.");
}
}

To compare to values, you should use ==.
That means that your if-statement should look so:
if (guessAttemts == MaxGuesses) {
System.out.println("Sorry you used all your nine chances. Game Over.");
}

Related

Need to make a Counter using enum ordinals

I need to make a counter array for a Rock Paper Scissors game but can not figure out how to make user input call the enum, and i need to make the moves for the game a counter for them to be used and compared to.
This is my enum
public enum Moves {
Rock(1),
Paper(2),
Scissors(3),
Lizard(4),
Spock(5), ;
private int countOf = 0;
private int moveVal;
private ArrayList<Moves> movesList = new ArrayList<>();
Moves(int moveVal) {
}
public int getmoveVal() {
return moveVal;
}
public int getCountOf() {
for(Moves moveList : Moves.values()) {
countOf++;
}
return countOf;
}
And this is my class that would call it
public static void main(String[] args) {
RockPaperScissorGame rsg = new RockPaperScissorGame(3);
Moves move[] = Moves.values();
int playerMove = 0;
for(int i = 0; i < move.length; i++) {
}
boolean continueGame = true;
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
while(continueGame)
{
System.out.println(rsg.moveChoices());
System.out.println("Enter Move:(1,2,3,4 or 5):");
playerMove = keyboard.nextInt();
rsg.playRound(move);
System.out.printf("AI %s!%n", rsg.getAIOutcome().toString());
System.out.printf("Player %s!%n", rsg.getPlayerOutcome().toString());
System.out.println(rsg.moveOutcome());
System.out.println(rsg.currentScore());
if(rsg.isGameOver())
{
System.out.println(rsg.currentWinTotal());
System.out.println("Do you want to Play Again(1 - Yes , 2 - No):");
int answer = keyboard.nextInt();
if(answer == 2)
{
continueGame = false;
}
else
{
rsg.reset();
}
}
}
You can iterate through values to find a Move matching that moveVal:
public Move fromMoveVal(int moveVal) {
for (Move m : Move.values()) if (m.moveVal == moveVal) return m;
return null;
}

Java - <identifier> required/illegal start of expression [duplicate]

This question already has answers here:
Java instance variable declare and Initialize in two statements
(5 answers)
Closed 8 years ago.
I'm running into some trouble with a Java assignment. I'm not sure what I'm doing wrong, but it's telling me that I need an identifier and that the lines are an illegal start of an expression when I try to add() to an ArrayList.
Here's my code, the offender starts at printStrat.add("1. Tit-For-Tat\n"); :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.lang.Math;
public class PDGame
{
private static ArrayList<boolean> rcrd = new ArrayList();
private static Gamestat globalStats = new Gamestat();
private String[] rslt = new String[] {
"You and your partner remain silent\n",
"Your partner testifies against you and you remain silent\n",
"You testify against your partner and he remains silent\n",
"You both testify against each other\n" };
private ArrayList<String> printStrat = new ArrayList<String>();
printStrat.add("1. Tit-For-Tat\n");
printStrat.add("2. Tit-For-Two-Tats\n");
printStrat.add("3. Tit-For-Tat with forgiveness\n");
private int strat = 1;
private int npcPrison = 0;
private int pcPrison = 0;
public PDGame()
{
//there is no need for a scanner to read if I won't be doing
// anything with it, so I did not implement it
}
public String playRound(int decision)
{
boolean myMove;
if(strat == 1) { //Tit-for-Tat
if(rcrd.size() < 1) //if first move
myMove = false;
else //set npc move to last player's move
myMove = rcrd.get(rcrd.size()-1);
}
else if(strat == 2) { //Tit-for-Two-Tats
if(rcrd.size() < 2) //if first move
myMove = false;
else if(rcrd.get(rcrd.size()-1) == true && rcrd.get(rcrd.size()-2) == true)
myMove = true; //if player betrayed last two times, betray
else //otherwise, forgive
myMove = false;
}
else if(strat == 3) {
int ran = (int)(Math.random()*100+1);
if(rcrd.size() < 1) //if first move,forgive
myMove = false;
else if(ran < 50) //if ran > 75, act normally
myMove = rcrd.get(rcrd.size()-1);
else //if ran = 1-50, forgive
myMove = false;
}
if(decision == 1) {
if(myMove == false) {
result = rslt[0];
npcPrison = 2;
pcPrison = 2;
}
else if(myMove == true) {
result = rslt[1];
npcPrison = 1;
pcPrison = 5;
}
rcrd.add(false);
}
else if(decision == 2) {
if(myMove == false) {
result = rslt[2];
npcPrison = 5;
pcPrison = 1;
}
else {
result = rslt[3];
npcPrison = 3;
pcPrison = 3;
}
rcrd.add(true);
}
globalStats.update(pcPrison,npcPrison);
globalStats.setDate();
return result;
}
public ArrayList<String> getStrategies()
{
return printStrat;
}
public void setStrategy(int strategy)
{
strat = strategy;
globalStats.setStrategy(strategy);
}
public GameStat getStats()
{
return globalStats();
}
public String getScores()
{
String scores = "Your prison sentence is: " + pcPrison + "\n";
scores += "Your partner's prison sentence is " + npcPrison + "\n";
return scores;
}
}
Any and all help is appreciated.
You cannot put code (except assignments) straight under a class declaration - it should be put in a method, constructor or anonymous block. One way to solve this would be to move your calls to printStrat.add to the constructor:
public class PDGame
{
/* snipped */
private ArrayList<String> printStrat = new ArrayList<String>();
public PDGame()
{
printStrat.add("1. Tit-For-Tat\n");
printStrat.add("2. Tit-For-Two-Tats\n");
printStrat.add("3. Tit-For-Tat with forgiveness\n");
}
/* snipped */
}

How to get input without pressing enter every time?

I made a simple game(well not really a game yet) in which the player can move in a room 4x20 characters in size. It runs in console.
But in my game loop I want to be able to move around in the room without pressing enter every time I want to move. The player should be able to press w/a/s/d and have the screen update instantly, but I don't know how to do that.
public class Main{
public static void main(String[] args){
MovementLoop();
}
public static void MovementLoop(){
Scanner input = new Scanner(System.in);
int pos=10, linepos=2;
String keypressed;
boolean playing = true;
while(playing == true){
display dObj = new display(linepos, pos);
dObj.drawImage();
keypressed=input.nextLine();
if(keypressed.equals("w")){
linepos -= 1;
}
else if(keypressed.equals("s")){
linepos += 1;
}
else if(keypressed.equals("a")){
pos -= 1;
}
else if(keypressed.equals("d")){
pos += 1;
}
else if(keypressed.equals("q")){
System.out.println("You have quit the game.");
playing = false;
}
else{
System.out.println("\nplease use w a s d\n");
}
}
}
}
public class display{
private String lines[][] = new String[4][20];
private String hWalls = "+--------------------+";
private String vWalls = "|";
private int linepos, pos;
public display(int linepos1, int pos1){
pos = pos1 - 1;
linepos = linepos1 - 1;
}
public void drawImage(){
for(int x1=0;x1<lines.length;x1++){
for(int x2=0;x2<lines[x1].length;x2++){
lines[x1][x2]="#";
}
}
lines[linepos][pos]="O";
System.out.println(hWalls);
for(int x2=0;x2<lines.length;x2++){
System.out.print(vWalls);
for(int x3=0;x3<lines[x2].length;x3++){
System.out.print(lines[x2][x3]);
}
System.out.println(vWalls);
}
System.out.println(hWalls);
}
}
The answer is simple
You can't do that
Because command line environment is different from swing, as swing can do such a thing as it deals with events and object, whereas, command line have no events.
So, maybe it's a right time to leave command line.

How do I run a (pseudo)main method with an applet?

I'm a beginner/intermediate java programmer that is attempting to code something that is "out-of-my-league". The program is supposed to judge a boxing/MMA match in real time by pressing keys that correspond to different scoring values. I've figured out that I need a KeyListener, and the only way I've found to use that is with an applet.
The problem I've run into is the only cues I have to print out a score come from keyPresses and keyReleases. I want the score to print EVERY second, along with the time. I'm made a clock function and can print every second using another class with a main method, but I don't know how to do this in the applet.
Here's what I have so far:
import java.applet.Applet;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.*;
public class KeyPressTwo
extends Applet
implements KeyListener{
private long t;
private ArrayList<Integer> keysDown = new ArrayList<Integer>();
private double controlOnlyValue = 1; //Stores the score per second for control only
private double threateningValue = 2.5; //Score for threatening with strikes, i.e. landing sig strikes, or sub attempts
private double damagingValue = 4; //Score for doing significant damage and dominating hea
private static double redTotal = 0; //Stores fighter score
private static double blueTotal = 0;
private static boolean firstRun = true;
private static boolean start = false;
private static boolean releasePressed = false; //Tells KeysReleased method when to wipe keysDown list
private static long roundBeganAt = 0; //System time when the round began 5
private static String redName;
private static String blueName;
public void init(){
this.addKeyListener(this);
//If names aren't hardcoded in, get them when the program is run
if (redName == null){
redName = JOptionPane.showInputDialog("Enter the red corner fighter's name.");
blueName = JOptionPane.showInputDialog("Enter the blue corner fighter's name.");
}
}
public void paint(){
setSize(500,500);
}
#Override
public void keyPressed(KeyEvent e) {
if(!keysDown.contains(e.getKeyCode()))
keysDown.add(e.getKeyCode());
//Starts the timer, don't print anything until started
if(keysDown.contains(KeyEvent.VK_SPACE)){
start = true;
roundBeganAt = System.currentTimeMillis();
}
//If it's been more than 1s
if(nextStep()){
//If space has been pushed
if(start){
if(keysDown.contains(KeyEvent.VK_Z) || keysDown.contains(KeyEvent.VK_NUMPAD1)){
redTotal += controlOnlyValue;
}
if(keysDown.contains(KeyEvent.VK_X) || keysDown.contains(KeyEvent.VK_NUMPAD4)){
redTotal += threateningValue;
}
if(keysDown.contains(KeyEvent.VK_C) || keysDown.contains(KeyEvent.VK_NUMPAD7)){
redTotal += damagingValue;
}
if(keysDown.contains(KeyEvent.VK_COMMA) || keysDown.contains(KeyEvent.VK_NUMPAD3)){
blueTotal += controlOnlyValue;
}
if(keysDown.contains(KeyEvent.VK_M) || keysDown.contains(KeyEvent.VK_NUMPAD6)){
blueTotal += threateningValue;
}
if(keysDown.contains(KeyEvent.VK_N) || keysDown.contains(KeyEvent.VK_NUMPAD9)){
blueTotal += damagingValue;
}
System.out.print("\n" +redName +": " +redTotal +" \t" +blueName +": " +blueTotal +"\t\t" +time());
releasePressed = true;
}
}
}
//Prints time since start (e.g. 2:05)
private static String time() {
String minutes = "";
String seconds = "";
int sRaw; //Gets time directly from system, will go above 60
int s; //Gets time from sRaw, (0 - 59)
sRaw = (int)((System.currentTimeMillis() - roundBeganAt))/1000;
s = sRaw%60;
minutes = Integer.toString(sRaw/60);
if(s < 10)
seconds = "0" +Integer.toString(s);
else seconds = Integer.toString(s);
return minutes +":" +seconds;
}
//Returns true if it's been more than1s since the last time it ran
public boolean nextStep() {
if(firstRun){
t = System.currentTimeMillis();
firstRun = false;
return true;
}
if(System.currentTimeMillis() > t + 1000){
t = System.currentTimeMillis();
return true;
}else
return false;
}
public void printList(){
for(int i : keysDown)
System.out.print(i +" ");
System.out.println();
}
#Override
public void keyReleased(KeyEvent e) {
if(releasePressed){
keysDown.clear();
releasePressed = false;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
Maybe something along these lines would work for you:
Thread timerOutputThread = new Thread(new Runnable(){
public boolean running = true;
public void run(){
output();
}
private void output(){
try {
Thread.sleep(1000);
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("PRINT THE SCORE HERE");
if(running){
output();
}
}
});
timerOutputThread.start();
Stick that code wherever you want the Thread timer to be started, and then fill in that spot where it says "PRINT THE SCORE HERE".
I've figured out that I need a KeyListener,.."
Or preferably key bindings.
..and the only way I've found to use that is with an applet.
Where on Earth did you hear that?!? It is definitely wrong. Start using a JFrame for this app. and it will work better because focus will be more reliable.

Client/Server communication - Guess my animal game

I have to make a simple text based game using multi threading. I have chosen to do a guess my animal game. A server will pick a random animal and give out clues and the client has to guess what the animal is within three clues.
However, if the animal is guessed correct, the program just goes to the next clue. I dont understand where i have gone wrong?
The other problem is when the client says y to a new game, it just repeats the same animal. It won't change.
I know it is just the protocol class i need to fix. Please help! I have cried with frustration over this program.
Here is a copy of my protocol class:
public class KKProtocol {
private static final int WAITING = 0;
private static final int ASKNAME = 1;
private static final int SENTCLUE = 2;
private static final int SENTCLUE2 = 3;
private static final int SENTCLUE3 = 4;
private static final int ANOTHER = 5;
private static final int NUMANIMALS = 4;
private int state = WAITING;
private int currentAnimal = (int) (Math.random() * 6); // number of first joke
private String[] clues = {"I like to play", "I like to scratch", "I eat salad", "I annoy you in the morning"};
private String[] clues2 = {"Love walks", "House pet", "garden pet", "I fly everywhere"};
private String[] clues3 = {"Woof", "Meow", "I live in a hutch", "Tweet Tweet"};
private String[] answers = {"Dog",
"Cat",
"Rabbit",
"Bird",};
private String[] name = {};
public String processInput(String theInput) {
String theOutput = null;
// System.out.println("Welcome to my animal guessing game");
if (state == WAITING) {
theOutput = clues[currentAnimal];
state = SENTCLUE;
} else if (state == SENTCLUE) {
if (theInput.equals(answers[currentAnimal])) {
theOutput = "Correct...Your Score is 1....Want to play again? (y/n)";
state = ANOTHER;
} else {
theOutput = clues2[currentAnimal];
state = SENTCLUE2;
}
} else if (state == SENTCLUE2) {
if (theInput.equals(answers[currentAnimal])) {
theOutput = "Correct...Your Score is 2....Want to play again? (y/n)";
state = ANOTHER;
} else {
theOutput = clues3[currentAnimal];
state = SENTCLUE3;
}
} else if (state == SENTCLUE3) {
if (theInput.equals(answers[currentAnimal])) {
theOutput = "Correct...Your Score is 3....Want to play again? (y/n)";
state = ANOTHER;
} else {
theOutput = ("it's" + answers[currentAnimal] + " you fool! Want to play again? (y/n)");
state = ANOTHER;
}
} else if (state == ANOTHER) {
if (theInput.equalsIgnoreCase("y")) {
if (currentAnimal == (NUMANIMALS - 1)) {
currentAnimal = 0;
}
theOutput = clues[currentAnimal];
// else
currentAnimal++;
state = SENTCLUE;
} else {
theOutput = "Bye.";
state = WAITING;
}
}
return theOutput;
}
}
If you need to see the other classes please just ask.
Debug the program and set a break point before your first if clause. How do the variables look like? I suppose you've made a trivial error somewhere in your code which will reveal itself while observing what your program actually does.
You could also paste some of your client code here so that someone could understand what is happening. From the comments I understood that nobody quite got how you use the Protocol class.

Categories