Simple Java Game - Moving Icon That Is Controlled Using Keyboard
Apr 1, 2014
I am writing code for a simple java game. The problem I am running into is that I have a moving icon (J button) that is controlled using the keyboard (arrows) and I also have stationary icons (J button). Is there a way to keep the moving icon from passing over the stationary icon? I would like the stationary icon to act like a wall.
I am trying to make a simple platformer game in Java. When I try to move the character I made it only moves over then immediately back
import java.awt.event.KeyEvent; public class UCC { private int xLoc; private int yLoc; private int xSpeed; private int ySpeed; private double gravity; private int size;
try to make a game in this code i am trying to make the basics i have made a mouse it should move the game code is
import java.applet.Applet; import java.awt.*; public class Game extends gameLoop { public void init() { setSize( 854 , 480); Thread th = new Thread (this);
I'm working on a Java 2D game which requires a max of six keys be held down at the same time.
The game is for two players on the same keyboard, playing simultaneously.
However, all three computers I ran the program on only allow a max of three keys held at a time. They all have trouble with reacting to more than three keys being held.
It seems that pressing a new key after three are already held, either cancels some other key-holding or is ignored.
I've been told that this is a hardware issue. Most keyboards can't handle more than three keys held at a time. But a lot of games do require this, and they do not require special gaming-keyboards to run on my computer without problems.
So there has to be a solution that will make the game playable on any standard keyboard.
(I use Key Bindings).
The game's controls:
Player 1
- Rotate sprite and set angle of movement: LEFT arrow
- Rotate sprite and set angle of movement: RIGHT arrow
- Move forward: UP arrow
- Shoot missile: ENTER key
Player 2
- Rotate sprite and set angle of movement: 'A' key
- Rotate sprite and set angle of movement: 'D' key
- Move forward: 'W' key
- Shoot missile: 'T' key
Relevant code:
The Key Bindings part:
Java Code:
// An action for every key-press. // Each action sets a flag indicating the key is pressed. leftAction = new AbstractAction(){ public void actionPerformed(ActionEvent e){ keysPressed1[0] = true;
[Code] .....
This is mostly how reacting to key-presses and key-releases works in my program. When a key is pressed or released, a flag is set. The Board class reades the flags every game-loop cycle and reacts accordingly.
As I said, the program doesn't react correctly to more than 3 keys held at a time, probably because of the keyboard. Is there a way to code a solution?
Okay, gotta be able to move the image when a key is pressed. When I test it, the image moves, but leaves the old image behind.
package Game; import java.awt.Component; import javax.swing.JOptionPane; public class Game { private Grid grid; //holds the grid used to store and display images private int userRow; //keep track of which row the user-controlled image appears in private int msElapsed; //keep track of the total amount of milliseconds that have elapsed since the start of the game
[Code] ....
Here is what I was given on instructions:
Complete the handleKeyPress method. Write the following line of code in the handleKeyPress method to check for a key press:
int key = grid.checkLastKeyPressed();
If the user pressed the up arrow (key == 38), move the user's image up one row (unless the user is already in the top row). Likewise, if the user pressed the down arrow (key == 40), move the user's image down one row (unless the user is already in the bottom row). Either way, make sure to update userRow.
Movement of the image can be accomplished by changing the value of userRow. Study how the initial image is displayed in the game constructor, then
Set the current image location to null
Update userRow to the new location and,
Set the image in the new value of userRow.
You should be able to move the user image up and down, and you should be prevented from moving the image off the screen.
The game is too have two players, each user clicks a button and two dices will roll, if a user rolls a double they win.
firstly I have started with two imageview's and a button I am trying to randomise two images by clicking one button I have managed to randomise one image in one box but I am struggling to randomise both image views here is my code so far.
I recently made a game. But, I want to package it and give it to my friends. I know that I can create a jar of it and add the images to the folder, but what I would absolutely love is for it to just be a picture with the game name and click to run. The second thing is to replace that java icon to an icon of my preference, which I have been told numerous times to do with
I've been at this for a while and I would like to make the Camera in my game follow the player and I know the way to do this would be to move the map and not the player. How would I do this if my map is rendered from a text file using for loops. Here is my code for the map.
package Game; import java.awt.Graphics; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Map {
I have been working on this function and i can't get it to work. It's a little bit complicated so let me first explain what this is about:
1. As a little exam in my studies i have to program a halma console game with KI an stuff.
2. Everything is finished and works except for the Move-Calculation.
3. A Move is a Move from Field a to Field b which a player can perform in one round based on the game rules (Careful: We are not using the standard halma rules, we use different ones).
4. Class Move consists of the Starting Cell where the Figure before the Move stands and a target Cell where the figure will stay on at the Move end. It may include an Array of serveral Cells, the stop cells which the figure passes from start -> target since several jumps can be performed in one Move.
Valid Examples for Moves:
a -> b (From Field a to Field b) d -> f through g,h,i (From Field d to Field f through the Field g,h,i
My Move Calculation where all possible Moves are calculated for a given figure consists of 2 parts. An expand() function which will generate all possible moves (works perfectly) and a jumpFix() function which isn't working properly.
Example:
After expand() I'm getting something like that:
a -> b b -> c c -> d s -> t
This is however not finished, because the first 3 Moves are actually 1 Move. Because the player can Move from a -> d in one turn because those 3 are consecutive Move. The fixed Move would look like that:
a -> d through b,c
jumpFix() is also perfectly working for that situation, however there is one specific situation when it doesn't work. Let's say we have this situation.
a -> b b -> c c -> d b -> e e -> f f -> g s -> t
Then the only valid jumpFix() output would be:
a -> d through b,c a -> g through b,e,f s -> t
However i can not get it to work yet. Note: It definitely needs to be iterative, not rekursive else i would get an StackoverflowError.
This is my current Code of jumpFix():
Java Code:
/** * Takes a look into all calculated moves and finds those which should be seen as one move, but are still considered to be more than one move (several jumps in one move) */
public static List<Move> jumpFix(List<Move> moves) { Set<Move> result = new HashSet<Move>(); Set<Move> remove = new HashSet<Move>(); int lastSize = -1; // repeat action until no moves could be merged while (lastSize != remove.size()) {
[Code] ....
How to implement the special case where a Move splits into 2 or more branches and jumpFix() able to handle this case.
When I ran the methods "go1,go2,go3" separately without clicking on the menu , all of them worked well. by separately I mean, when I closed the program changed the source code from "go1;" to "go2" and go3. But when I click on the "change ball" and then "1 ball" or any thing, all I get is a new frame which is blank. And the old frame freezes.
I am using libgdx and box2d to try to make a simple cannon game.
When I have the cannonball collide with another object I want to delete that object and have it stop calling all of it's functions. It doesn't seem like I can have it delete itself, and the contactListener has a reference to the cannonball and other object, but if I set either to null, it seems the original reference still exists and the object isn't deleted.
I don't know how to write a code to pong ball, when it touch red block.
public class bounc2 extends JPanel implements ActionListener,KeyListener{ double x = 0,y=0,velX=3,velY=3; double x2 = 5,y2=145,velX2=0,velY2=0; double x3= 473,y3=145,velX3=0,velY3=0; Timer t = new Timer(5,this); public bounc2(){ setBackground(Color.GREEN);
I am making a very simple 2D array game where the player is asked what size they would like the game board to be. After entering, it displays the board and the player 'P' starts at index [0][0]. After that, they are asked for an action, which can be "up", "down", "left", "right", or "exit". I will be including some extra later (like a treasure at the end, or random obstacles), but for now this is what the game consists of.
I was instructed to "do nothing" when/if the player attempts to go out of bounds. I am trying to simply print an error, such as "Out of bounds! Try again.", then prompt the player again for an action. I even tried to make a boolean method to catch it, but to no avail.
I don't want the exception to occur at all. I just simply want the error message to print to the player and ask for another action. I would prefer not to use try/catch, or try/catch/finally since I already tried that and it still gave the exception error.This program consists of two classes. I will show the class containing the main first, then the client-server type class second.
import java.util.Scanner; public class Driver { public static void main(String[] args) { World world = new World(); boolean keepPlaying; keepPlaying = true; boolean isOutOfBounds; isOutOfBounds = false; int height = 0; int width = 0; int x = 0; int y = 0;
Here is my problem to solve : Find the smallest value Write an application that finds the smallest of several integers. Assume that the first value read specifies the number of values to input from the user.
I do not even know where to begin other than creating a scanner for the user input. But how do I take that user inputed number to create the loop?
how to display a jpg image on a through a Jlabel. I am sure it is a simple error but I am still new to GUI's. line 31 to 35 you can see the ImageIcon and file wrapped in the JLabel. I verified its in the correct location and file name, but usually fails (i thought) when it is not correct.
I'm trying to create a switch statement inside of a counter controlled (while) loop that asks for an input of...
"How many characters would you like to convert?"
Then you type in a number > 0, and then it should convert letters into the "1337" equivalent.
This is an example on what it should do.
How many characters would you like to convert? 5 Enter character #1 to convert: ! !- Enter character #2 to convert: $ $- Enter character #3 to convert: # #- Enter character #4 to convert: * *- Enter character #5 to convert: , , -
Whenever i try to run the program, i only get the- How many characters would you like to convert- i input 5 but then nothing else prints..
My codes..
System.out.print ( "How many characters would you like to convert?: " );
int convertCounter = 1; char ch; ch = input.next().charAt(0); while (convertCounter > 0) switch ( ch ){
I developed a simple java gui . On running a frame opens with 5 buttons and each button opens another frame when selected. There are no errors and frames open and close as required however i see that only the main program frame has the icon and title that i assigned and the frames bieng called through the buttons have the default frame with java icon and no title although it's been specified in the code of these called frames. When these called frames are executed individually though the program the title and icon are displayed.
Basically I have a program that paints a simple object image. There are 5 of these objects altogether and different classes and methods have been set up to do this and this works correctly. The program currently also asks the user if they would like to change the colour of this object shape, and which shape they would like to change (user inputs a number 1-5) then the program will change the colour of this shape.
But the new task is for the user to input a number (1-5) to which shape they would like to MOVE position of. Hhow this would be done? Would there need to be different methods for changePositionX, changePositionY? The user needs to input the X and Y co ordinates and then this will move the selected shape to its NEW position in the current JFRAME.
I have a class that works only when in the default package. If I move the class to a package I receive UnsatisfiedLinkError.
This is the class in the default package(this works fine):
[code] public class CsharpConsumer { private native int reigsterAssemblyHandler(String str); public CsharpConsumer() { String dir = System.getProperty("user.dir"); System.load(dir+"dllscardJNICsharpBridge.dll"); int reigsterAssemblyHandler = reigsterAssemblyHandler(dir+"dllscard"); } } [/code]
If at the top of this class I add "package DLLUtils;"
the error is "Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError:
I want to write a java program which displays to get the GPA of a student as a keyboard input. Then display the class of the degree according to the following criteria using a switch-case statement (if-else statements cannot be used). If the user insert an invalid gpa you should display a message Invalid GPA.
gpa ≥ 3.50 First Class Hons 3.49 ≥ gpa ≥ 3.00 Upper Second Class Hons 2.99 ≥ gpa ≥ 2.50 Lower Second Class Hons 2.49 ≥ gpa ≥ 2.00 Pass 2.00 ≥ gpa Fail
Here is my code:
import java.io.*; public class q7 { public static void main(String[] args) { InputStreamReader ISR=new InputStreamReader(System.in); BufferedReader BR=new BufferedReader(ISR);
[code]...
.But when I use Command console to run this it says: 1111.jpg. I also wanna know is there another way to do this with switch- case statements.
I have been following a 2d side scroller tutorial in java and have got the basics working, I changed the code a bit to make it so that the tiles and background are always moving, this worked as i intended.Within the character class:
if (speedX < 0) { centerX += speedX; } if (speedX == 0 || speedX < 0) { bg1.setSpeedX(0); bg2.setSpeedX(0);
[code]....
I wanted a way to make it so that if the character moves left, the tiles + background move slower. I am having issues with variable scope and setters/getters. Within the main game class, I have the code:
case KeyEvent.VK_LEFT: character.moveLeft(); character.setMovingLeft(true); break;
How can i include an if statement within the tile class that reads whether the character is moving left (determined from a keyPressed event in the main game class) and adjusts the speed of the tiles accordingly?I want to write something to the effect of:
I'm learning about the printf command, and when I have it, it is not letting me ad an input. Here is my quick little program:
import java.util.Scanner; public class TestingPrintF { public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in);
[Code] ....
The first section works good, but when i move down to the second part it just automatically finishes without letting me enter a phrase.
I'm just starting to learn Java GUI. I'm trying to make a simple GUI that will update dynamically but having trouble ending the loop correctly.The Currently I've got the GUI updating and stopping, but the Test class method loop does not terminate correctly, it continues to count.
import java.awt.*; // Using AWT container and component classes import java.awt.event.*; // Using AWT event classes and listener interfaces import java.util.Timer; import java.util.TimerTask;