In Java, how to take a character without pressing the enter key? - java

How can I get characters without pressing the Enter key?
Actually I want to build a game so I need to get characters as moves and then do the moves without the Enter key being pressed.

You could add a keyListener if your using swing example of keyListener:
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_UP)
{
//code here
}
else if(keyCode == KeyEvent.VK_DOWN)
{
//code here
}
//etc...
}

For example I am still learning keyListeners as well. but, to make a e.g Rectangle move you could make a private rectangle call it in your paintComponent() rect.fillRect(0,0,10,10) then use the keyListener to check for input.
public void keyPressed(KeyEvent e){
if (rect.getKeyCode() == KeyEvent.VK_S)
if (rect.getKeyCode() == KeyEvent.VK_F)
xa = 2;
if (rect.getKeyCode() == KeyEvent.VK_E)
ya = 2;
if (rect.getKeyCode() == KeyEvent.VK_D)
ya = -2;
}
EDIT: After, reading that you are not using Swing, it would help to provide some code or further expand on the details of what you want the key to do when pressed in your game.

you should take a look at:
System.in.read();
It reads the next byte of data from the input stream.

Related

How do i call a KeyEvent method from one class to another?

After doing a few small things i have decided to try my hand at a text based rpg. I am only using the console as i again am learning still. I am however at this point running into an issue i cant seem to get passed nor find any help on. I have my Game class which holds my main method as well as a few other classes one of which is my Player class. Within my Player class i have this:
public void playerControls(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_W)
{
System.out.println("Up");
}
if (key == KeyEvent.VK_A)
{
System.out.println("Left");
}
if (key == KeyEvent.VK_S)
{
System.out.println("Down");
}
if (key == KeyEvent.VK_D)
{
System.out.println("Right");
}
if (key == KeyEvent.VK_I)
{
System.out.println("Inventory");
}
if (key == KeyEvent.VK_O)
{
System.out.println("Options");
}
if (key == KeyEvent.VK_M)
{
System.out.println("Map");
}
if (key == KeyEvent.VK_C)
{
System.out.println("Character");
}
}
Then inside of my Game class i have within my main method:
//START OF GAME
do
{
player.playerControls(e);
validInput = true;
System.out.println("!!!!!!!!!!enter the intro story here!!!!!!!!!");
} while (gameRun);
}
The problem i am having is that i get an error saying e cannot be resolved to a variable when i run it as null i also throw errors. My question is how do I (like this/also "properly") call the playerControls from my players class into my Game class so that i can run the game and allow user input. Thank you for any answers. Have a great day :)
Instead of having your method require a KeyEvent you can just read the console input.
do {
String input = System.console().readLine();
//Change playerControls(KeyEvent e) to playerControls(String e)
player.playerControls(input);
validInput = true;
System.out.println("!!!!!!!!!!enter the intro story here!!!!!!!!!");
} while (gameRun);
Yes there is a way to do this with a single Char instead of a String, but it is not easy enough in my opinion for a starter.
Now you also would have to change your playerControls-method further:
public void playerControls(String e){
switch(e){
case "Up": system.out.println("Up");
break;
//Do so with all controls
}
Instead of the break which is to stop executing every following case(which will happen if you forget the break) you could use return;.

Adjust Key Pressed So You Cant "Hold" it

Wasn't sure how to word the title.
I have some code for my "space invaders" type game. I made the entire thing just making adjustments. To shoot, i use spacebar. The problem is im able to hold spacebar and it continually shoots. I would rather have to press it multiple times (if i hold it down.. for it not to continually fire) How would i change it?
*here is the code i believe is the source of the problem. If the source is located elsewhere please say so.
private class KeyInputHandler extends KeyAdapter {
private int pressCount = 1;
/**
* key pressed
*/
public void keyPressed(KeyEvent e) {
if (waitingForKeyPress) {
return;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
firePressed = true;
}
}
/**
* Key Released
*/
public void keyReleased(KeyEvent e) {
if (waitingForKeyPress) {
return;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
firePressed = false;
}
}
added code
public class ShotEntity extends Entity {
//vertical speed
private double moveSpeed = -300;
private Game game;
private boolean used = false;
/**
* Create a new shot from the player
*/
public ShotEntity(Game game,String sprite,int x,int y) {
super(sprite,x,y);
this.game = game;
dy = moveSpeed;
}
/**
* Request that this shot moved based on time
*/
public void move(long delta) {
super.move(delta);
if (y < -100) {
game.removeEntity(this);
}
}
//collision
public void collidedWith(Entity other) {
// prevents double kills.
if (used) {
return;
}
// alien killed
if (other instanceof AlienEntity) {
game.removeEntity(this);
game.removeEntity(other);
game.notifyAlienKilled();
used = true;
}
}
}
Listen for two seperate key events. One when the key is pressed, and one when it is released. Now, you make a boolean.
public boolean myBoolean;
When the key is pressed, set the boolean to true (myBoolean==true)and if it is released, set it to false (myBoolean==false).
Now, create a simple if statement:
if(myBoolean==true){ //Key is being held down
//execute this code
//Have nothing be done
}
Thats it!
P.S. If you want, you can have one separate method to clean up the code. This method could just change the value of the boolean:
public void changeValueOfBoolean(Boolean b){
if(b = true){
return false;
}
if(b==false){
return true;
}
}
It's very simple. Let me know if you need any help, and if this was helpful, please mark it as best answer. Feel free to ask me any questions, I am always happy to help!
Clarifications:
Okay, so we have this boolean, right? Now, this boolean essencialy decides whether the key is pressed or not.
Say we press the button:
Because the key is being held down, we make the boolean myBoolean as true. Now, because the user is holding the key down, we want to do nothing, right? That's why we created that if statement:
if(myBoolean==true){ //Key is being held down
//execute this code
//Have nothing be done
}
It says, if the boolean is true, then we won't do anything. Recall, the boolean is true when the key is being held down, remember? So, when the key is held down, the boolean is true, and nothing will be done.
Now, when the user releases the key:
Now, say the user has pressed the key. This will call two listeners. One listener for when the key is pressed and another for when it is released. If the user just presses the key, myBoolean will end as false, since they have let go of the key. Therefore, we can execute some code when myBoolean is false (shooting).
**In summary:
myBoolean is true when when the key is being held down. So, when it is true, we do nothing. myBoolean is false when the user lets go of the key, and there, we shoot the space invaders.**
Simple, just have a Boolean variable which causes the ship to shoot only when it is true. Then set it to true in the space bar is pressed and set it to false when the ship shoots. I can't show you how to implement it in your program as I don't know how your shoot method works. However, if you were to post the method which causes the ship to shoot then, I could show you how to implement it or, you could try your self.

KeyAdapter creating weird boxes

public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
for(GameObject tempObject : handler.object){
if(tempObject.getID() == ObjectID.Player){
if(key == KeyEvent.VK_D){ tempObject.setVelX(0); }
if(key == KeyEvent.VK_A){ tempObject.setVelX(0); }
if(key == KeyEvent.VK_S){ tempObject.setVelY(0); }
if(key == KeyEvent.VK_W){ tempObject.setVelY(0); }
}
}
if(Game.getChat().isWorking()){
Game.getChat().passText(e.getKeyChar(e.getKey));
//.replaceAll("Space", " ").replaceAll("Period", ".").replaceAll("Backspace","").replaceAll("Shift","Shift").replaceAll("Slash","/").replaceAll("comma",",")
}
}
}
This code basically checks when a user releases a key while typing something in the chat box for my game. Then it passes it onto a method that basically sets the text to be rendered in the game to that. This really doesn't matter though, the problem is this:
As you can see, those annoying boxes only appear when I have shift being released.
More code:
KeyInput:
http://pastebin.com/BM8yZ1i6
Game Class:
http://pastebin.com/vViQ23pS
Static Chat:
http: (slash slash) pastebin (dot) com/CgQE7SgN
ChatManager:
http: (slash slash) pastebin (dot) com/yVM5rdUs
Additional info:
when I System out the text that is being typed, the boxes are not boxes, they are question marks instead.

Java2D games: How to handle keyboard correctly?

I found a very good tutorial about how to create games with Java2D. In this tutorial there is a section called 'Moving sprites' that shows how to move a little spacecraft image on the screen. I was playing with the craft and realized that it was "blocking" on screen sometimes. After some tests and thinking about the problem I found out that the blocking problem was happening because when you use the arrows of the keyboard sometimes you press Left and Right at same time for example, and this blocks the movement.
So my question is: how do I handle this kind of keyboard event - when you are pressing LEFT button keep pressing it and then press RIGHT button - so the character movement is not blocked?
I think this is very common to happen because when you are playing you switch from left to right but for an instant you are pressing left and right at the same time.
You can do this in multiple ways. One way is to use booleans in your program.
You can set booleans to true when you press a certain key and to false when you release them. ie:
int x,xSpeed;
boolean movingLeft = false;
boolean movingRight = false;
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){
movingLeft = true;
}
if(key == KeyEvent.VK_RIGHT){
movingRight = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){
movingLeft = false;
}
if(key == KeyEvent.VK_RIGHT){
movingRight = false;
}
}
public void moving(){
if(movingLeft){
x -= xSpeed;
}
if(movingRight){
x += xSpeed;
}
}
Ok let's look at this code. Because we're using the 'else if' you either move right, or you move left. I haven't test this code so not quite sure if this will work :)
Let me know what you think and good luck!

Need help with pressing multiple keys in java

I'm trying to code a game similar to Mario in Java and am having problems with making the dude jump while he is running. What the below code ends up doing is, as the user is holding down right and presses the jump button, Mario basically stops running and jumps, so its like the user has let go of right and pressed jump.
public void keyPressed(KeyEvent e) {
// here I keep track of what buttons the user pressed
int keyCode = e.getKeyCode();
if(keyCode == 37)
pressedKeys[0] = true;
else if(keyCode == 39)
pressedKeys[1] = true;
else if(keyCode == 68)
pressedKeys[2] = true;
// after I see what the user has pressed an action is carried out
Thread t = new Thread(this);
t.start();
}
public void performAction()
{
// depending on what the user has pressed a certain action is performed
if(pressedKeys[2]==true)
{
// changes the coordinates of the character itself
// done in another thread so the background can continue
// moving as the user holds down a direction
Thread t = new Thread(mcControl);
t.start();
}
if(pressedKeys[0]==true)
{
changeSprite();
bg.moveImageForward();
}
if(pressedKeys[1]==true)
{
changeSprite();
bg.moveImageBackward();
}
}
public void run() {
performAction();
}
if(keyCode == 37)
Not related to your problem, but NEVER use code like that. Most people don't know what that magic number means.
The better way to do this is to use:
if(keyCode == KeyEvent.VK_???)
Now your code is self documenting.
You want to take a look at How to Write a Key Listener. The KeyEvent object has several methods for learning what modifier keys and mouse buttons were pressed at the time the event was generated.

Categories

Resources