Counter only adds once - java

I have a simple hangman game that has a Jlabel that is supposed to show how many times the word was guessed right. It uses a simple counter wins++ and will show up properly after the first win but any after won't work. The counter won't add more so do I need to use a loop in some way?
if (word.equals(dashes.toString()))
{
wordOutput.setText("You Win!");
wins++; //add 1 to win counter
winsOutput.setText("Wins: " + wins);
}
Seems like this should be simple but I don't know what's wrong

I think you made the win variable as a local, which will get its initial stage after every execution, make the win variable outside of the method and you can also make it static.
public class Hangman {
// here is the variable..
private int wins = 0;
// Here are your other methods..
public void processGame(){
}
}
By the way, it will also works fine without static if your game does not have more than one classes etc. Give it a try with static and without it, but the main point is initializing it outside of the class.

Related

Java: Continue with Label

public static void main(String[] args) {
// TODO code application logic here
int b=10;
int a= 5;
jmp0:
while (b> 10)
{ if (a>5)
continue jmp0;
else
continue jmp1;
}
jmp1: System.out.print("Zulfi");
}
}
I have a question related to above code. Is using “continue jmp0” same as just using “continue;” in the above code and “continue jmp1;” is giving an error because "jmp1" is outside the block?
continue isn't a jump that you can use to go anywhere. It will just move the execution of the code to the start of the loop you have labelled.
Labels are only used to mark loops you'll want to continue to or break from later. Not random lines of code you want to jump to. So yeah, your jmp1 label is totally out of scope
If you want to use continue with label then your label must be a loop label.

Dealing with a specific rule of a card game

I am working on a card game and I'm facing a problem regarding the gameplay. So basically the rules of the game are that who finishes the hand first gets placed first, second second and so on. I am keeping a list of the players in a List<Player, and if one finishes I just skip the turn from him (checks if >= 1 cards in hand), until 1 player is left. Now, the rule is that if one finishes with an unbeatable card/move or everyone else passes for example, the turn should be to the next player and he is free to make a move. I've been struggling and haven't found a proper solution yet. How to achieve this?
I am currently saving the waste (last played list of cards) cards into a List<Card>, and I am keeping a Player instance lastPlayed for the last playing player, and a Player instance hasTurn for the current player on turn.
The turns are shifted in this method inside the Game class:
public void determineNextPlayerTurn()
{
if(playersLeft() > 1)
{
int i = players.indexOf(hasTurn) + 1;
if(i == 4)
i = 0;
hasTurn = players.get(i);
if(hasTurn.isPlaying())
{
if(!isHumanTurn())
{
display.disableButtons();
AI temp = (AI)players.get(i);
temp.onPlayerTurn(this);
}
else
display.enableButtons();
}
else
{
determineNextPlayerTurn();
}
}
else
newGame(0);
The method of AI that is called when it is an ai's turn:
public void onPlayerTurn(Game game)
{
selectCardsToPlay(game.getWaste(), game.getLastPlayedPlayer());
if(getSelectedCards().isEmpty())
{
game.determineNextPlayerTurn();
}
else
{
if(Moves.canBePlayed(getSelectedCards(), game.getWaste(), this, game.getLastPlayedPlayer()))
{
playMove(game);
game.determineNextPlayerTurn();
}
else
game.determineNextPlayerTurn();
}
}
While for the user, nothing is called as the determineNextPlayerTurn() is called within the ActionListener of the playing buttons (Play, Pass).
Note: Currently like this, if the scenario occurs with the human last playing there will be a stackoverflow for the reason that every ai is doing a Pass. Every other code is fine for now, but I need help with implementing a simple solution to that specific case, and if I am doing something wrong I am open.
Why don't you have a counter for the number of "passes" that are executed and then compare that to the number of players. If the passes are equal to the number of players - 1 then that would mean that following player should be free to make a move. Also what is an "unbeatable move" if there is such a thing then wouldn't you be able to classify the turn as that and then attach a boolean that checks the player for whether or not they have made one of these types of moves?

Methods not pulling through - Read Running Loop on Java Method, didn't fix my code

So I am a student. I am taking my first class in Java. I am sure my code is horrible, but please don't beat me up, I am really trying to learn. I have read quite a few method questions and adjusted my code according the the suggestions on this website. The closest post to my problem is Running Loop on Java Method. I adjusted my code according to the suggestions in this post, along with a few others. That said, it did not fix my problem. My methods are not pulling through properly.
Can anyone help? It will not pull any of the Boolean code into the main and I am not sure if the Boolean is pulling my methods correctly. Intro runs properly. Below is my code (edited down to include main and bool code only):
public static void main(String[] args)
{
intro(); // This works
while (repeat()) //This does not work
;
}//end Main
//None of this is being called
public static boolean repeat()
{
//Assign Variables
char calculate, calculateCS, repeat;
double inchCircle, inchSphere, radiusCS, volume, volumeSphere, area, areaCircle;
String shape;
//Initialze Variables
calculate = 1;
area = 1;
volume = 1;
inchCircle = 1;
inchSphere = 1;
shape = "";
//Ask if user wants to repeat
System.out.print("Do you want to calculate anouther round object (Y/N): ");
if (!takeInput().equalsIgnoreCase("y"))
{
System.out.println("Thank you for using the Round Object Calculator. Goodbye. ");
return false;
}
else
{
printCircleSphere(shape);
if (!printCircleSphere(shape).equalsIgnoreCase("c"))
{
printRadiusC(inchCircle);
printCircle(area);
}
else if (!printCircleSphere(shape).equalsIgnoreCase("s"))
printRadiusS(inchSphere);
printSphere(volume);
}
return true;
}//end repeat

Java Method not working constantly

I have a text based game that I am making. It is a RPG style where the user is given options linked to numbers and they have to choose a number. Now my problem is that when running the program. A certain method, Decision(), only works certain times. The method is in a superClass while it is being called in the subclass. in the subclass, It works the first time, but not necessarily the second. Also, when I copy the decision method from the superclass into the subclass its starts working, but the next time it is called, it stops. Here is what I've tried and the results. I've included the decision method and where it is being called.
Decision Method:
public int decision(String question, int length, String[] choices){
int[] numbers = new int[length];
int iterator = 1;
for(int i = 0; i < length; i++){
numbers[i] = iterator;
iterator++;
}
boolean done = false;
while(!done){
//print("Test");
print("");
print(question);
String options = "";
for(int i = 0; i < numbers.length; i++){
options = (options + numbers[i] + " - " + choices[i] + " ");
}
print(options);
boolean univSet = true;
int entry = 1;
while(univSet){
if(univInt != 0){
univSet = false;
entry = univInt;
univInt = 0;
//print("testing");
}
}
if(entry == 23){
help();
}else{
for(int i = 0; i < numbers.length; i++){
if(entry == numbers[i]){
done = true;
univInt = 0;
return entry;
}
}
print("Invalid Number, Try again");
print("");
univInt = 0;
}
}
return (Integer) null;
}
Chapter1 Class (Where it's being called:
public class Chapter1 extends Story implements Serializable {
Player player;
public Chapter1(Player player){
this.player = player;
}
public void engage() {
// TODO Auto-generated method stub
player.chapter = 1;
save(player.name);
sPrint("Welcome to Chapter 1");
print("You wake up in a lighted room with white walls.\nA fresh breeze is coming through the window yet the air smells rotten.");
print("You jolt up suddenly. You don't remember anything about how you got here. You've even forgotten who you are.");
print("You look down at your white shirt, there is a streak of blood across the top.\nYou are wearing a nametag that says: " + player.name + ".");
print("You're sitting in a chair but there are no restraints. You decide to get up and look around");
cur = decision("What do you do?", 2, new String[]{"Try the door", "Look out the window"});
print(cur + "");
if(cur == 1){
print("You walk over to the door and try and open it, it is unlocked.\nYou walk through and are welcomed by a cold and poorly lit hallway");
}else{
print("You walk to the window and look outside. You see a huge barren field. You can make out a humanoid like structure.\nYou call out yet the figure doesn't move.");
print("You decide to try the door. It's unlocked so you walk through into a cold dimly lit hallway.");
}
print("You see a dull knife on the floor as well as a door on the end of the hallway");
cur = decision("What do you do?", 2, new String[]{"Go to the door", "Take the knife"});
if(cur == 2){
print("You pick up the knife.");
addWeapon("Kitchen Knife", player);
}else{
print("You walk down the hallway to the door when suddenly the door opens and out comes a zombie.\nIt Lunges for your shoulder. You are caught by surprise and it bites into your skin and you are infected");
gameOver();
}
print("You continue to walk down the hall when suddenly a hideous creature lunges out from the door.\nYou jump back and prepare yourself for a battle.");
battle("Zombie", 5, 2, player);
sPrint("I see that you have succeeded in your first encounter with the undead.\nI congratulate you but you have a long way to go. Remember, I am your only way to learning about your past. \nNow, make your way down to the bottom of the tower. I will help you where I see fit along the way.");
print("You look around and see that the lights have brightened up. The zombie has been mutilated by your Kitchen Knife. \nYou don't know where the voice came from but you are scared. Behind the zombie's original hiding spot you see a staircase.\nYou follow it down, onto what seems to be..the 11th floor.");
print("");
print("Please input 'complete' to continue");
pause();
sPrint("Chapter 1 complete");
}
Now in this class, engage() is being called to run this chapter. And decision is being called where you see it, as well as in the battle() method(the battle method loops a couple times and decision() is called every loop.
Originally, both Decision and battle are in the superclass, but not in the sub class. This results in the first decision method in the class to be called, but not the second. In the second, it stops at the loop checking the value of univInt.
When I put the decision method into the sub class, It passes the first two but it fails to get past the first one in the battle method for the same reason.
When I put both the decision and battle method into the sub class, it has the same result as just putting decision.
Finally if I put battle in the sub class but not decision it only passes the first two again.
In the project I have one variable named cur that holds the integer value of whatever decision returns. I reuse it for every decision. I don't know if that has anything to do with it. This really doesn't make sense to me how whether the methods are in the same class, or inherited would matter at all if they are the same method.
I am ready to clarify anything and I hope someone is able to understand what is going wrong.
EDIT:
univInt is being set to another number other than 0 outside of decision. thats why it works some times. It is a swing class and a method in a superclass sets univInt to whatever is in a TextField when a button is pressed so with that while loop I try to constantly check to see univInt has been changed from 0
It seems like your "univInt" is a class member, not a local variable, and you do not reinitialize it when entering the function. Thus it won't be changed back to allow the program to enter the if-statement you mention.

Making a player move on 2D array game grid

I am creating a game using a 10x10 2D array. The player starts at the top left hand corner indicated as "P" and the objective is to get the player to avoid obstacles to get to the treasure indicated as "T" located in the lower right corner.
How would I go about making the player move about the grid using commands Up/Down/Left/Right?
Would I use a for loop to count through the elements in the array to designate the move?
Here is what I have so far:
import java.util.Scanner;
import java.util.Random;
public class Adventure {
public static void main(String[] args) {
char grid[][]= new char[10][10];
Scanner move = new Scanner(System.in);
System.out.println("Here is the current game board:");
System.out.println("-------------------------------");
for(int i=0; i<grid.length; i++) {
for(int j=0; j<grid.length; j++) {
double random = Math.random();
if(random <=.05) {
grid[i][j]='*';
}
else if(random > .06 && random <= .15) {
grid[i][j]='X';
}
else {
grid[i][j]='.';
}
grid[0][0]='P';
grid[9][9]='T';
System.out.print(grid[i][j]);
}
System.out.println("");
}
System.out.print("Enter your move (U/D/L/R)>");
}
}
you should keep track of the current position of the player and just update those variables.
initial values would be (0,0) as you said.
int px = 0;
int py = 0;
when a move is made, update the variables accordingly:
grid[px][py] = <empty cell>;
switch (move) {
case 'u': py += 1; break;
case 'r': px += 1; break;
...
}
grid[px][py] = 'P';
of course you shouldn't just updated the values "blindly", you should insert some validation logic to follow the rules of the game:
if (grid[px][py] != <obstacle> )
// update player coordinates...
Looks like you're using row-major ordering, judging from the way your board prints out. Based on that, here's what you'll need to do:
First, you need to store the player's position somewhere. Right now it's hardcoded to 0,0.
Second, you need to read in the player's move. That will have to happen in a loop, where you get a move, check if the move is allowed, perform the move, and display the results.
Third, you need to be able to calculate the new position based on the move. Up means row -= 1. Right means column += 1. Etc.
Given the new coordinates, you need to make sure the move is valid. At the very least, you have to stop them from walking off the board, but you may also prevent them from entering a square with an obstacle, etc.
Once you know that the move is valid, you have to update the variables you're storing the current coordinates in.
At the end of the loop, you'll need to redraw the board.
That's the basic gist of it. Right now you are doing everything in main(), and that's okay, but if it were me I would start to split things out into separate methods, like InitializeBoard(), GetNextMove(), CheckIfMoveIsValid(int r, int c), and so on. That way, main() becomes a high-level view of your game loop, and the guts of the different operations are compartmentalized and more easy to deal with. This will require storing off things like your game board into class variables rather than local variables, which should actually make things like obstacle detection easier than it would be currently.
All of the above answers are great. Here are a few suggestions I would make:
Instead of a char two-dimensional array, I would make a custom object, such as Space, and define a two-dimensional array of Spaces (eg, Space[][]). There are a few reasons for this:
You can define a space in a variety of ways (rather than just 1 character). For example, Space[i][j].hasTreasure() can return a boolean to let you know whether or not you found the treasure.
If you want to add functionality later, its as easy as adding an attribute to your Space class. Again, you are not limited to one character here.
More to your question of movement, I would also recommend a few things. Similar to redneckjedi's suggestion of a CheckIfMoveIsValid() method, I would pass the grid and move direction as parameters and return a boolean. To ensure that you do not end up with ArrayIndexOutOfBounds issues, I would also suggest adding a row/column of walls on each side. I would widen the grid out to 12x12 and put a strip of obstacle-type blocks around the outside. This will ensure that you cannot step outside of the grid as hitting a wall will always return 'false' on a valid move.

Categories