At the moment , when I hit F or f :
private static final char FILL_POLYGON_LOWERCASE = 'f';
private static final char FILL_POLYGON = 'F';
#Override
public void keyTyped(KeyEvent keyEvent)
{
PolygonFiller polyFiller = new PolygonFiller();
char key = keyEvent.getKeyChar();
switch(key)
{
/**
* Fill the polygons
*/
case FILL_POLYGON:
{
if (greenLightForFilling == true)
{
fillPolygon(polyFiller);
System.out.print("called");
}
break;
} // end FILL_POLYGON
case FILL_POLYGON_LOWERCASE:
{
if (greenLightForFilling == true)
{
fillPolygon(polyFiller);
}
break;
}
...
}
The program goes into fillPolygon(polyFiller); .
Meaning , when I hit for the first time f , I go into fillPolygon() .
How can I go into some other method , for example other() , when I hit f or F again ?
Thanks
So the thing is, if you click f/F you goto fill polygon, and pressing f/F again will call other().
This can be a classic case of Stateful Class.
Have an attribute in this at class level.
And on entering f/F check the value and increment it by one.
And on entering f/F again, check the value and increment it by one.
Before each increment you should check whether,
//Am assuming that there are more than two functions, else could use boolean
if (value == 1) {
fillpolygon();
}
else if (value == 2) {
other();
}
else if (value == 2) {
some_other();
}
Remember the entry point will be a single function, from there the flow is delegated based on checks similar to this.
Hope this helps.
Store the previously used button in a variable like 'currentCommand' and 'previousCommand'. Everytime you detect a new input you put current to previous and store the new one in the current member.
Or maybe if you want more than the last two key pressed use a stack.
How can I go into some other method, for example other(), when I hit f or F again ?
You need to introduce a boolean flag.
This is a very simple example of a state machine.
Related
Disclaimer: I'm really new at this and I apologize in advance if:
1) my question has already been asked (I've tried searching and had a lot of trouble finding what I needed)
or 2) if I'm not asking the question correctly.
Basically, I'm trying to make a game where pressing the spacebar triggers a sort of "super-power" that will perform a set of actions just once. Afterwards, if they try to press it again, it'll run up some sort of dialogue box that says their one-time super-power has already been used.
What I have:
try {
Key move = canvas.getLastKey();
int space = 0;
if(move == Key.SPACE) {
if (space == 0) {
space = 1;
}
if (space == 2){
JOptionPane.showMessageDialog(null, "superpower already used");
}
}
if( space == 1 ) {
//action here
canvas.resetKey();
space = 2;
}
}
Right now, the super-hero action is on an endless loop but if I reset the key here:
if(move == Key.SPACE) {
if (space == 0) {
space = 1;
canvas.resetKey();
}
the user can just use the super-power over and over again. Any help would be appreciated!
In the third line, you have written int space=0 so your variable is constantly reset to 0...
You have to initialize it elsewhere (the beginning of your program is a good place for any global variable).
You should consider moving int space = 0, outside of the try block. I suppose your try block gets invoked repeatedly, so you should declare this variable under a global scope.
I am currently making a text adventure game in Java, but I have come across a problem:
I need the value of a String variable to change each time the value of a particular int variable changes.
I want the program to perform this task (then continue where it left off) each time the value of an int variable changes:
if (enemyposition == 1) {
enemyp = "in front of you";
}
else if (enemyposition == 2) {
enemyp = "behind you";
}
else if (enemyposition == 3) {
enemyp = "to your left";
}
else if (enemyposition == 4) {
enemyp = "to your right";
}
else {
enemyp = "WOAH";
}
Thanks! :D
You could make the code much shorter using an array.
String[] message = {"WOAH", // 0
"in front of you", // 1
"behind you", // 2
"to your left", // 3
"to your right"}; // 4
enemyp = (enemyposition > 0 && enemyposition < 5) ? message[enemyposition] :
message[0];
The question you're asking sounds like it might be answerable by creating a class to hold the enemyposition integer. Add a "setter" method to your class to set the integer. You can write your setter method so that when the integer is set, it also sets up a string. Then write a "getter" method to retrieve the string. That's one common way of making sure two variables change together.
public class EnemyPosition {
private int enemyposition;
private String enemyp;
public void setPosition(int n) {
enemyposition = n;
enemyp = [adapt your code to set this based on the position]
}
public String getEnemyp() {
return enemyp;
}
}
I'm sure there are a lot of details missing, but you get the idea. Then instead of int enemyposition in the rest of your code, use EnemyPosition enemyposition = new EnemyPosition(), and use the setPosition method instead of assigning to it.
That's not the only solution (an array or Map that maps integers to strings may be good enough), but it's one OOP way to do things.
I wasn't too sure what to title this question, apologies in advance. I currently have a value of say 50 stored in the BidderArray. I want to be able to increase that 50 by any given number entered into a text field.
So say I want to add 10 to the existing 50, it will return 60. Currently when I add the 10 the 50 is replaced by 10 instead of adding the two together. I understand why my code is doing this but haven't been able to find any tutorials or hints on what I should be doing instead.
Here is the code:
package abc;
import java.awt.*;
public class Funds extends javax.swing.JFrame {
int i = 0;
Bidder bidbal = new Bidder();
/** Creates new form Funds */
public Funds() {
initComponents();
}
private void addActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int f = 0;
boolean validEntries = true;
try{
f = Integer.parseInt(amount.getText());
Bidder.BidderArray.get(i).setRegFee(f);
} catch (Exception error) {
validEntries = false;
amount.setBackground(Color.red);
}
if (validEntries) {
Bidder.exportBidder();
Home home = new Home();
home.setVisible(true);
this.dispose();
}
}
}
You aren't actually adding anything
Bidder.BidderArray.get(i).setRegFee(f);
is apparently just setting something to f, you have to get the current value, add to it, and then put it back. But this is just a guess as we don't have enough actual code to know what you are doing wrong.
You have to get the current fee, add the value, and then set the fee:
f = Integer.parseInt(amount.getText());
Bidder.BidderArray.get(i).setRegFee( f + Bidder.BidderArray.get(i).getRegFee() );
Or you could add a new method the Bidder class that adds to the fee:
class Bidder
{
//...
public void addToRegFee( int amount )
{
this.regFee += amount;
}
}
f = Integer.parseInt(amount.getText());
Bidder.BidderArray.get(i).addToRegFee( f );
f = Integer.parseInt(amount.getText());
Bidder.BidderArray.get(i).setRegFee(f);
Here, it seems like you're getting the user's input (f), and just set the array's element value to it. What it sounds like you want to do is to take that input (f), and the array's element existing value, combine (read: add) them, before setting the element's value to that new combined value.
In pseudo-code, this is what you're doing:
f := get user's input
setValue(f)
What you need to do:
f := get user's input
g := get current value
setValue(f + g)
You must add it to your old value:
//Add old to new (Unless you have a different method set for get like
//getRegFee (Not sure how bidder is implemented))
Bidder.BidderArray.get(i).setRegFee(Bidder.BidderArray.get(i) + f);
I just got a task asking me to do repeated addition from 1 to 21, as follows :
1,4,6,9,11,14,16,19,21
and get the total.
I tried this code but it returned to be a +2 addition, and it even bypass the prerequisite of bil<=21
public class test
{
public static void main(String[]args)
{
int bil=1;
long total=0;
boolean mult = true;
for(bil=1; bil<=21;bil++)
{
if(mult=true)
{
bil+=1;
mult=false;
}
else if(mult=false)
{
bil+=2;
mult=true;
}
System.out.println(bil);
total=total+bil;
}
System.out.println("----+");
System.out.println(total);
}
}
(if it's TL;DR)
Basically the request is 1+4+6+9+11+14+16+19+21=?
I can't seem to get these code to work, please help me?
EDIT : Thanks guys I got it now :D
You need boolean mult = false; so that the first time the loop runs, bil is incremented by 3 and not 2.
First, you are not comparing your boolean with ==. Therefore, every time the for() loop executes, the first block will be the one that enters since mult = true will always store true in mult... and then qualify that if() block to run.
If this assignment wasn't intentional, then you need to change it to == and also put some logic in your loop to toggle mult appropriately.
Basically when it runs through the first loop it only adds one because of the state of the boolean but also there should be an == operator to check instead of just an =
Try this:
for (bil = 1; bil < 21; bil++) {
if (bil % 2 == 0) { // If bil is divisible by 2, then add 2
bil += 2;
continue;
}
bil += 3;
}
i'm using the keyboard class from the LWJGL and am currently using
if(Keyboard.isKeyDown(Keyboard.KEY_A))
{
//move left
}
else if(Keyboard.isKeyDown(Keyboard.KEY_D))
{
//move right
}
if i have the 'a' key down then the 'd' key it will move right but if i have the 'd' key down then the 'a' key it will still continue to move right due to the "else" part.
i've tried it without the else and just letting them both run but if both keys are press there is no movement
im looking for a piece of code that allows me to only take the input from the last key that was pressed.
i also need to be able to move up and down (using 'w' and 's') so the solution can't stop other keys from working, only 'a' or 'd'.
thanks. Alex.
Use Keyboard.getEventKeyState to determine the current event, followed by Keyboard.getEventKey to determine which key this is. Then, you need to make sure you disable repeat events via Keyboard.enableRepeatEvents. Maintain state for the current movement, changing based on these events, and every tick move accordingly. Something like the following, as quick sketch:
Keyboard.enableRepeatEvents(false);
...
/* in your game update routine */
final int key = Keyboard.getEventKey();
final boolean pressed = Keyboard.getEventKeyState();
final Direction dir = Direction.of(key);
if (pressed) {
movement = dir;
} else if (movement != Direction.NONE && movement == dir) {
movement = Direction.NONE;
}
...
/* later on, use movement to determine which direction to move */
In the above example, Direction.of returns the appropriate direction for the pressed key,
enum Direction {
NONE, LEFT, RIGHT, DOWN, UP;
static Direction of(final int key) {
switch (key) {
case Keyboard.KEY_A:
return Direction.LEFT;
case Keyboard.KEY_D:
return Direction.RIGHT;
case Keyboard.KEY_W:
return Direction.UP;
case Keyboard.KEY_S:
return Direction.DOWN;
default:
return Direction.NONE;
}
}
}
Idk if this is still going to help you, but you could lock the key that was first pressed until it is let up. I'd suggest putting this variable outside of the methods (if I remember correctly, it's called a field) so it can be accessed through any class and isn't reinstantiated every time update is called. That would look something like this:
boolean isHorizontalLocked = false;
String lockedKey = null;
After that, write something like this in the update method:
if (!isHorizontalLocked) {
if (input.isKeyDown("KEY_A")) {
isHorizontalLocked = true;
lockedKey = "A";
}
else if (input.isKeyDown("KEY_D")) {
isHorizontalLocked = true;
lockedKey = "D";
}
else {
isHorizontalLocked = false;
}
}
else if (isHorizontalLocked) {
if (lockedKey == "A") {
if (input.isKeyDown("KEY_A")) {
//move left
}
if (!input.isKeyDown("KEY_A")) {
lockedKey = null;
isHorizontalLocked = false;
}
}
else if (lockedKey == "D") {
if (input.isKeyDown("KEY_D")) {
//move right
}
if (!input.isKeyDown("KEY_D")) {
lockedKey = null;
isHorizontalLocked = false;
}
}
}
I think this should work, but if anyone finds an error, let me know and I'll fix it.