If the die shows a 6, the player doesn't move at all on this turn and also forfeits the next turn.
To accomplish this, I have tried an integer type warning marker variable for the player and an integer type time counter variable.
If the die shows 6, I want to increment the warning marker variable by 1 during the first run(and have the while loop do nothing), then keep the value at 1 during the second run (while loop will not work), then lower it back down to 0 for the third run of the while loop (so the while loop will work). The marker will stay at zero unless the die shows a 6 again, after which the same process will repeat.
I have a while loop like this:
while the warning marker is equal to 0 {
Do Stuff
if the die shows a 6, the warning marker increases by 1.
the time counter also increases by 1.
}
How do I manipulate the variables to get the result that I need? Or is my partially complete method absolutely off in terms of logic?
Thanks.
Can u tell me if this works for you?
flag=true;
while condition{
if flag==true{
if die == 6
{
flag=false;
continue;}
}
else { Do STUFF }
} else
{
flag==true;
}
}
I think you want to reword this problem.
This is what I understood. You have a warning marker.
You have a loop that checks whether the marker is 0, if it is then you do something.
If the die is a six, you will increase the warning marker. If its new value is 3, then you will reset it to 0. Meanwhile, the time counter is always increasing.
If this is correct, I think you want something like:
int warningMarker = 0;
int timeMarker = 0;
while (true) {
if (die == 6) {
++warningMarker;
if (warningMarker == 3) {
warningMarker = 0;
}
}
if (warningMarker == 0) {
doSomething();
}
++timeMarker;
}
Java is Object-Oriented Pragramming language. Use this feature.
See following pseudocode and let me know if you have problem in undestanding it.
Create a class Player as following:
class Player
{
boolean skipChance = false;
... // Other fields
... //
}
Change your while as following:
while(isGameOn())
{
Player p = getCurrentPlayer();
if( ! p.skipChance)
{
int val = p.throwDice();
if(val == 6)
{
p.skipChance = true;
continue; // control moves to while.
}
// Do stuff
}
else
{
p.skipChance = false;
}
}
Related
This is essentially what i'm doing
while(true) //cant check for zero, there is more to do here
{
int val = 0;
for(SomeObject i : arrayListOfSomeObjects)
{
if(canDoSomething)
{
val++
}
}
if(val == 0)
{
break;
}
else
{
//do stuff with that nonzero value
}
}
It is strange, because the loop wont yield. As in, stop if unsuccessful. I have a proceedure that will keep going until it finishes, if it does not do anything (or does not meet my conditions in that operation) it wont change the value. Meaning that check on "val" should break the loop. But it doesn't. It just going. I have even printed "val" to the console, yet it returns 0.
At the end of that operation, even if the value IS 0, it keeps going!
Your code is correct.. Try the following..
int val = 1;
while(val>0)
{
//Some operation that will change the value IF successful
}
first int val = 0 supposed to be outside the loop because this will cause the value of the variable val always zero
You might need to make sure you are targeting the 'right' loop by adding a label:
label: while(true) //cant check for zero, there is more to do here
{
// ...
if(val == 0)
{
break label;
}
// ...
}
This will ensure that you break out of the while loop in case the check is in another loop or a switch statement. Otherwise, I am sure that something is causing the problem that you didn't show in your example. Beware of unwanted side-effects.
So I am making a game where there are waves of enemies. The Wave class contains an update method that updates all the enemies in an arraylist of enemies contained in the Wave class. The Wave class also has a boolean called beat that decides whether or not the player has beaten the current wave. I am now have been trying however to start the next wave after the player beats the first. All waves in the arraylist start out with their beat variable as true except for the first. There are currently only two waves. I do not know why this is not working. Thank You for any help.
for(int i = 0; i < 1;i++)
{
if(!w.get(i).beat)
w.get(i).update(g2d);
else if(w.get(i).beat)
{
if(i-1 != -1)
{
if(w.get(i-1).beat && w.get(i).beat)
{
w.get(i).beat = false;
}
}
}
}
Your loop will increment i to the next wave after setting the current wave's beat setting to false, and miss calling the update method for that case. It looks like you should either call its update method immediately after setting beat = false, or perform the if test in the opposite order like this:
for(int i = 0; i < numWaves;i++) // upper range should be the number of waves
{
if(w.get(i).beat)
{
if(i>0) // this can be simplified to "if (i>0)"
{
if(w.get(i-1).beat) // no need to check w.get(i).beat here
{
w.get(i).beat = false;
}
}
}
else
w.get(i).update(g2d);
}
I don't know why you'd initialize a wave's beat state to true then set it to false when its turn comes. Why not just initialize all to false since they really haven't been beat yet?
I'm not sure that I understand your code but I can tell you 2 things. First of all, your loop never loops because as soon as the index is 1, it ends without executing the code a second time. Secondly
if(i-1 != -1)
{
if(w.get(i-1).beat && w.get(i).beat)
{
w.get(i).beat = false;
}
}
is always false due to what I said.
So some background information, I'm new to programming and am still learning, so I apologize for my trivial error making. I am making my own text based game just to further practice etc.
Here is the link to everything on dropbox for more context:
https://www.dropbox.com/sh/uxy7vafzt3fwikf/B-FQ3VXfsR
I am currently trying to implement the combat system for my game, and I am running into the issue of the combat sequence not ending when required. The 'combat sequence' is a while loop as follows:
public void startCombat()
{
inCombat = true;
while(inCombat != false)// && herohealth > 0 && monsterhealth > 0)
{
checkAlive();
heroHitMonster();
checkAlive();
monsterHitHero();
}
attackinghero.setHeroHealth(herohealth);
attackedmonster.setMonsterHealth(monsterhealth);
}
where the checkAlive() method is as follows:
public void checkAlive()
{
if(herohealth <= 0)
{
System.out.println("You have died.");
attackinghero.clearInventory();
inCombat = false;
}
else if(monsterhealth <= 0)
{
System.out.println("You have killed the "+attackedmonster.getmonsterName()+"!");
inCombat = false;
combatlocation.removeMonster(attackedmonster.getmonsterName());
}
else
{
//
}
}
I am trying to get it to end the combat sequence when either the 'hero' or 'monster' health become <= 0,
however it is currently finishing the while loop and therefore producing the result of the hero being hit even if he killed the monster in his first hit.
This is what is currently being 'printed to screen'
rat loses 5 health!
You have killed the rat!
Hero loses 1 health!
Any help is much appreciated, thanks in advance.
checkAlive shouldn't be void it should be Boolean and should return inCombat, and in your function startCombat you should do inCombat=checkAlive();
The while loop will only evaluate after both actions. You need a way to break the loop after the hero hits the monster. I would personally change the checkAlive method to return a boolean, and put the hit methods in if statements in the while loop:
if(checkAlive())
{
heroHitMonster();
}
if(checkAlive())
{
monsterHitHero();
}
You should end the loop at the end of the checkAlive instead of changing the boolean value.
If you killed the monster at first hit, you still execute the monsterHitHero() even, if the monster is killed. The function to hit should be conditioned to the life of heroes/monster.
I'm doing my homework, and am stuck on some logic (I think I used that term correctly?). I'm writing an application that shows 12 buttons numbered 1-12, 2 pictures of dice, and a Roll button.
The player rolls the dice (2, 6 sided die) and whatever number(s) he gets, he can use to "cover" some of the twelve numbers. For example, let's say he rolls the dice and gets a 3 and a 5. He gets to choose whether to cover the 3 and the 5, or the total of the two numbers - 8 (Did I mention I'm a math wiz?).
The goal of the game is to cover all the numbers using the least amount of rolls.
The problem I'm having is with, what I believe to be, the if statements:
if (die1 == 3 && die2 == 5) {
player can cover 3 and 5, or 8, but not both
}
Now, I think this works, but if I wrote all this out it would be 36 if statements (give or take zero). Is there an easier way?
By your description I think the player can select die1, die2 or die1 + die2, so to see if the user selected a valid value you need just one if.
if (cover == die1 or cover == die2 or cover == ( die1 + die2)) {
//valid..
}
no if statement needed. player can cover die1 and die2 or die1+die2
This is a good example to use a switch case, IMO.
That'd be 2 switchs which have 6 cases each.
Don't check until the player tries to cover something. By only validating the input you simplify everything down to one if statement.
If you do need to know all possibilities (maybe to show the player possible moves), then ... you still don't need all those if statements. Simply highlight the buttons that match the dice roll and only accept those as input; you'll want to index them in an array or map by their value (e.g. "1") as a way to retrieve them.
You know with two dice you always have three covering options. Presumably elsewhere in code you're going to compare your covered options with numbers. Something like
int[] covered = { die1, die2, die1+die2 };
// ... other stuff
if (comparisonValue > 6) {
// maybe do special stuff since this uses both dice
if (comparisonValue == covered[2]) {
// covered/coverable behavior
} else {
// not
}
} else {
// maybe do special stuff since this only uses one die
if (comparisonValue == covered[0] || comparisonValue == covered[1]) {
// covered/coverable behavior
} else {
// not
}
}
gives you first what's covered, then simple use of it. You could also foreach over the array to do stuff for the covered numbers, ala
for (int c : covered) {
// do stuff with c because it's covered
}
That's fairly fragile, but the flexible answer (e.g., dumping the outcomes into Collection) is way overkill for 6-sided, integer face dice, and the really flexible answer (e.g., accommodating a variable number of dice, specialized combination of faces into outcomes) is like nuclear armageddon for this particular problem.
EDIT for your particular problem, I'd do something like
// start new turn, disable all buttons
// get rolls
int[] coverable = { die1, die2, die1+die2 };
for (int covered : coverable ) {
// enabled covered button
}
If the player can change which of the 1-12 are covered by previous rolls based on a new outcome, well, then you could be in for some fun depending on how much help you want to give them.
I would probably create 2 new objects and use them with a lookup table, like so:
class TossResult{
int firstDie;
int secondDie;
}
Class Coverage{
TossResult tossResult;
int getThirdNumber(){
return tossResult.firstDie + tossResult.secondDie;
}
}
Then on application start-up, populate your map:
HashMap<TossResult, Coverage> lookup = new HashMap<>();
for (int i = 0, i < SIDES_ON_DIE; i++){
for (int j = 0, j < SIDES_ON_DIE; j++){
TossResult tempResult = new TossResult(i,j);
Coverage tempCoverage = new Coverage(tempResult);
lookup.put(tempResult, tempCoverage);
}
}
After a user rolls the dice, create a new TossResult and do a lookup.get(tossResult)
You could also create an array of 12 ints or bools. Initialize all 12 elements (say to 0 or false). Then for each role you can do something lik:
if (false == myArray[die1Value] && false == myArray[die2Value]) {
myArray[die1Value] = true;
myArray[die2Value] = true;
} else if (false == myArray[die1Value + die2Value]) {
myArray[die1Value + die2Value]
} else if (false == myArray[die1Value] || false == myArray[die2Value]) {
if (false == myArray[die1Value]) {
myArray[die1Value] = true;
}
if (false == myArray[die2Value]) {
myArray[die2Value] = true;
}
} else {
// all 12 covered
}
And certainly you can refactor this code some more.
The stated goal "The goal of the game is to cover all the numbers using the least amount of rolls." is not doable, really. The best you can do is to use probabilities to know if, for instance, you should cover on a roll of 1 and 2, a 1 and 2, or 3 first:-)
I've got a bit of an issue with my little program.
I have a JOptionPane asking for a number, and if that number is less than 10, a loop that just continues on and on forever doing what's in it, keeping on asking for numbers. Inside that loop, I call a method, with an int as parameter. In the method, I need to (without altering any of the code in the class that calls the method) find out whether the number I entered is less than 1. If it is, I need to call on another method. That bit's done.
But! The mainloop keeps rolling, so it keeps doing the other stuff in the loop. I need to stop it from doing that, so in the if-statement in the method I need to break that specific iteration of the loop the method is in, and make it go on to a new iteration of the same loop, asking for a new number.
The first class (example):
number=Integer.parseInt( JOptionPane.showInputDialog( "bla bla" ) );
while (number !=- 10) {
themethod(number);
blah
blah
...
}
The called method (example):
public void themethod(int number) {
if (number<1) {
call the other method
break the iteration im in
}
There are a number of things you can do here. Ultimately what you do should depend on your coding style and what you are trying to accomplish.
Option 1 would be some variation of:
for (;;)
{
int number = /* ... */;
myMethod(number);
if (number == -10)
break;
}
You might say, rather subjectively and depending on circumstances, that this is bad, because knowledge of the termination condition is contained in the loop rather than the method doing the "real work". Maybe for your loop that's OK. Maybe in other circumstances (or perhaps with other programmers? This is very much a matter of taste.) you might want to make myMethod make that decision. In general my own personal taste usually leans towards not having scenario knowledge be distributed throughout various methods in source, but in one place.
So most of what I'll write from here on will be how to make myMethod make the decision about whether or not to terminate.
Option 2 - myMethod returns a boolean indicating we should terminate:
for (;;)
{
int number = /* ... */;
if (myMethod(number))
break;
}
boolean myMethod(int number)
{
// TODO - do stuff
return number == -10;
}
But you might say that myMethod already wants to return some other type. I come from very much a C background so the idiom I'm most used to would be the "out parameter". Leading me to option 3:
Option 3 - Out parameter lets caller decide to terminate:
public class CancelIndicator
{
public boolean shouldCancel;
};
CancelIndicator cancel = new CancelIndicator();
while (!cancel.shouldCancel)
{
int number = /* ... */;
myMethod(number, cancel);
}
int myMethod(int number, CancelIndicator cancel)
{
// TODO - do stuff.
cancel.shouldCancel = (number == -10);
return /* ... */;
}
Or maybe you're more a fan of exceptions:
Option 3:
public class CancellationException extends Exception
{
}
try
{
for (;;)
{
int number = /* ... */;
myMethod(numberl);
}
}
catch (CancellationException ex)
{
}
void myMethod(int number) throws CancellationException
{
// TODO - do stuff.
if (number == -10)
throw new CancellationException();
}
As you can see there are a number of options. I'm sure one could spend a whole day talking about different ways to do it. Here is my sample of idioms I have seen - I'll warn you that it's been some time since I've done much in Java so I might not write the most idiomatic code here. :-)
Add a return value indicating that the while should break:
public boolean themethod(int number) {
if(number<1) {
call the other method
return true;
}
return false;
}
Then:
while(number !=-10) {
if(themethod(number)) break;
bla
bla
...
}
Edit: If you can't change the while code, throw an exception from the method:
public void themethod(int number) {
if(number<1) {
call the other method
throw new RuntimeException("Negative Number");
}
}
Wait, so did I get this straight? You have a loop that asks for a number, does something if the number is not -10, and otherwise breaks?
If so, look at this:
while(true) {
number=Integer.parseInt( JOptionPane.showInputDialog( "bla bla" ) );
if(number == -10) {
break;
}
themethod(number);
}
Otherwise, if this is not the case, and you want to break in two cases, the -10 case and the method is false case, you can do this:
Change your method to return a boolean. If it's true, then it doesn't want to break. If it's false then it wants to break, then do this:
while(true) {
number=Integer.parseInt( JOptionPane.showInputDialog( "bla bla" ) );
if(number == -10) {
break;
}
if(!themethod(number)) break;
}
If you really can't edit the loop, then just throw an exception from the method! That will exit your entire program, though. I don't see any other possible way of doing this, however.
Without a return value for themethod(int) and without changing the other class's code, this isn't possible since as it is, there is no return communication. You'll have to change both; it can't be done without changing the logic in the loop.