game state manager cannot be resolved in my gamestate package - java

Im a 2d java platform developer. I need help with the gamestate manager. Im making a death sequence and would simply like to reroute the game back to the menu upon dying. My code is currently this (do keep In mind I have a gamestate manager aswell as a game state of course, and I use java eclipse.):
public void hit(int damage) {
if(flinching) return;
health -= damage;
if(health < 0) health = 0;
if(health == 0) dead = true;
if (dead == true) gsm.setState(GameStateManager.MENUSTATE);
flinching = true;
flinchTimer = System.nanoTime();
Please help

Related

My program suddenly stops receiving keyboard inputs

This is my first question so I'll just get straight to it.
I've been developing a little 2D platformer game in Java using the Eclipse Neon IDE. I've been able to overcome any issues I've encountered so far except for the one I'm about to tell you.
As game controls usually go, I've set up the WASD keys for movement and the SPACEBAR for jumping. The character I control does respond to the key inputs so I know that this code works, but for some reason after the program has been running for about 3 minutes or so, the character stops receiving key inputs and I get this error:
java.awt.AWTEventMulticaster.keyPressed(Unknown Source)
I've tried fiddling with the code to see if I could fix it myself, but I can't figure out what's causing the problem.
Here's the relevant section of code from my Player class. You probably don't need to pay attention to any of the variables in the keyPressed() and keyReleased() methods, but just the methods themselves:
public void keyPressed(KeyEvent keyID) { //This method checks to see which keys the user has pressed
int key = keyID.getKeyCode();
if (debug == false && key == KeyEvent.VK_F1) {
debug = true;
}
else if (debug == true && key == KeyEvent.VK_F2) {
debug = false;
}
if (death == false) {
if (key == KeyEvent.VK_SPACE && jumping == false) {
//Player.key = 2;
velY = ySpeed;
jumping = true;
Sound.playSound("audio/playerJump.wav");
}
else if (key == KeyEvent.VK_D && rightIntersect == true) {
velX = 0;
lastKeyPressed = 'D';
Player.key = 1;
}
else if (key == KeyEvent.VK_D && rightIntersect == false) {
velX = xSpeed;
lastKeyPressed = 'D';
Player.key = 1;
}
if (key == KeyEvent.VK_A) {
velX = -xSpeed;
lastKeyPressed = 'A';
Player.key = -1;
}
}
else if (key == KeyEvent.VK_R && death == true) {
for (int i = 0; i < GameFrame.getPlayerList().size(); i++) {
Player p = GameFrame.getPlayerList().get(i);
GameFrame.removePlayer(p);
GameFrame.addPlayer(new Player(GameFrame.xPosStart, GameFrame.yPosStart));
death = false;
GameFrame.level = 1;
GameFrame.mainTimer.setInitialDelay(0);
GameFrame.mainTimer.start();
}
}
}
public void keyReleased(KeyEvent keyID) { //This method checks to see which keys the user has released
int key = keyID.getKeyCode();
if (key == KeyEvent.VK_A || key == KeyEvent.VK_D) {
Player.key = 0;
velX = 0;
}
}
And here's the code for my KeyAdapt class that the Player class references:
public class KeyAdapt extends KeyAdapter {
Player p;
public KeyAdapt (Player player) {
p = player;
}
public void keyPressed (KeyEvent keyID) {
p.keyPressed(keyID);
}
public void keyReleased (KeyEvent keyID) {
p.keyReleased(keyID);
}
Again, this code does work. It just suddenly stops working after the program has been running for a certain amount of time.
Does anyone know what might be causing this issue?
(If more information is needed, I can provide the entire code for the Player class).
Does anyone know what might be causing this issue?
It is not possible to say given the code you have shown us.
I suggest that you add some debugging code. For example, add something to keyPressed that logs the event received, and the state of variables such as death, jumping etcetera.
You say:
I get this error:
java.awt.AWTEventMulticaster.keyPressed(Unknown Source)
That looks like part of a line from a stacktrace, not an error message. If this is a stacktrace, you need to show us the entire trace including the exception at the beginning.
Finally, you should not do this:
if (death == false) {
The correct way to write that is:
if (!death) {
It is more concise, but more importantly it is less fragile. Imagine if you had mistyped your version as:
if (death = false) {
One character difference. Easy to overlook. And it completely changes the meaning of the statement. It is a bad idea to use == and != to test boolean variables.
None of code that you showed us breaks because of this, but this bad habit could be used elsewhere in your code, and that might be the source of your problem.

Android - Retro Squash Game - racket/screen sides collision

I am reading "Learning Java by Building Android Games" and in a Retro Squash Game example I don't know how to implement collision detection for the racket. The movement of the racket uses onTouchEvent. I have tried to implement an if statement but it deosn't get checked until the next touch event- so it doesn't work properly. Please help.
//Event that handles in which direction is the racket moving according to where is the user touching the screen
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
//gets the movement action without the pointers(ACTION_MASK) ??? -U: handles multitouch
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
//what happens if user touches the screen and holds
case MotionEvent.ACTION_DOWN:
//if the screen was touched on the right side of the display than move the racket right
if (motionEvent.getX() >= (screenWidth / 2) && racketPosition.x <= screenWidth) {
racketIsMovingLeft = false;
racketIsMovingRight = true;
} else if (motionEvent.getX() < (screenWidth / 2) && racketPosition.x >= 0) {
racketIsMovingLeft = true;
racketIsMovingRight = false;
} else {
racketIsMovingLeft = false;
racketIsMovingRight = false;
}
break;
//when the user lets go of the screen the racket immediately stops moving
case MotionEvent.ACTION_UP:
racketIsMovingLeft = false;
racketIsMovingRight = false;
break;
}
return true;
}
Ok. I have found the solution. I wasn't looking at the right piece of code - sorry. I have edited the piece which is responsible for changing the racketPoint.x of the racket. Here it is:
public void updateCount() {
//change the racket position according to the movement
if (racketIsMovingRight && (racketPosition.x+racketWidth/2)<=screenWidth) {
racketPosition.x += racketSpeed;
}
if (racketIsMovingLeft && (racketPosition.x-racketWidth/2)>=0) {
racketPosition.x -= racketSpeed;
}
//rest of the code

JFrame skipping some repaint() calls

I'm making a snake game and I've encountered an error.
I have tried two different loops: thread.sleep and Timer.schedule.
I have gotten the same problem.
It will be working fine, but at random intervals, it will start to skip every other frame for 6-10 frames.
In case I wasn't clear, 1 frame is
#Override public void paintComponent(Graphics G){...}
being called. (I have also tried paint)
This has occurred in some other games I've created, but not all. What can I do to fix it?
Here's a full copy of the code:
https://github.com/jnmcd/Snake/blob/master/Code.java
EDIT: I've done some debugging. It appears that the it's not a problem with the paint. The JPanel doesn't always update. What can I do to fix it?
I found what I needed to do. I had to add a revaidate() after the repaint().
Also In the checkKillCollisions you have to break the loop right after you found the losing condition.
Also if the game ends it keeps on showing the error message[Dialog] for which there i no end.So I have created a flag gameOver to check is game is over or not in Snake Class
static Boolean gameOver = false;//Defined in Snake Class
public void checkKillCollisions() {
boolean lose = false;
for (int i = 1; i < Snake.segments.size(); i++) {
if (Snake.segments.get(i).x == x && Snake.segments.get(i).y == y) {
lose = true;
break;//Have to do this
}
}
if (x >= 60 || x < 0 || y >= 60 || y < 0) {
lose = true;
}
if (lose) {
Snake.window.popUp("You Lose");
}
Snake.gameOver = lose;//Will set the gameOVer flag in Snake class
}
And I've modified the Loop class to stop running right after the gameOver flag is set to true
class Loop extends TimerTask {
#Override
public void run() {
if (!Snake.gameOver) {
Snake.updates();
Snake.window.render();
} else {
System.out.println("Game Over");
cancel();
Snake.window.dispose();
}
}
}

Track best move from Minimax

I know this kind of question has been asked before, but i was unable to solve my doubts.
I have a simple Othello Engine (it plays very well actually), that uses the class below to get the best move:
import java.util.*;
import java.util.concurrent.*;
public class MinimaxOthello implements Runnable
{
private CountDownLatch doneSignal;
private int maxDepth;
private int calls;
private OthelloMove bestFound;
private OthelloBoard board;
private static float INFINITY = Float.MAX_VALUE/1000;
private boolean solve = false;
private Comparator<OthelloMove> comparator = Collections.reverseOrder(new MoveComparator());
public MinimaxOthello (OthelloBoard board, int maxDepth, CountDownLatch doneSignal, boolean solve)
{
this.board = board;
this.bestFound = new OthelloMove();
bestFound.setPlayer(board.getCurrentPlayer());
this.maxDepth = maxDepth;
this.doneSignal = doneSignal;
this.solve = solve;
}
public OthelloMove getBestFound()
{
return this.bestFound;
}
public void run()
{
float val = minimax(board, bestFound, -INFINITY, INFINITY, 0);
System.out.println("calls: " + calls);
System.out.println("eval: " + val);
System.out.println();
doneSignal.countDown();
}
private float minimax(OthelloBoard board, OthelloMove best, float alpha, float beta, int depth)
{
calls++;
OthelloMove garbage = new OthelloMove();
int currentPlayer = board.getCurrentPlayer();
if (board.checkEnd())
{
int bd = board.countDiscs(OthelloBoard.BLACK);
int wd = board.countDiscs(OthelloBoard.WHITE);
if ((bd > wd) && currentPlayer == OthelloBoard.BLACK)
{
return INFINITY/10;
}
else if ((bd < wd) && currentPlayer == OthelloBoard.BLACK)
{
return -INFINITY/10;
}
else if ((bd > wd) && currentPlayer == OthelloBoard.WHITE)
{
return -INFINITY/10;
}
else if ((bd < wd) && currentPlayer == OthelloBoard.WHITE)
{
return INFINITY/10;
}
else
{
return 0.0f;
}
}
if (!solve)
{
if (depth == maxDepth)
return OthelloHeuristics.eval(currentPlayer, board);
}
ArrayList<OthelloMove> moves = board.getAllMoves(currentPlayer);
if (moves.size() > 1)
{
OthelloHeuristics.scoreMoves(moves);
Collections.sort(moves, comparator);
}
for (OthelloMove mv : moves)
{
board.makeMove(mv);
float score = - minimax(board, garbage, -beta, -alpha, depth + 1);
board.undoMove(mv);
if(score > alpha)
{
alpha = score;
best.setFlipSquares(mv.getFlipSquares());
best.setIdx(mv.getIdx());
best.setPlayer(mv.getPlayer());
}
if (alpha >= beta)
break;
}
return alpha;
}
}
I have a bestFound instance variable and my doubt is, why a have to call
OthelloMove garbage = new OthelloMove();
and pass it along? The code works, but it seems very weird to me!
Is there a 'better' way to get the best move or the Principal Variation?
I really not a recursion expert, and this is very very hard to debug and visualize.
Thanks!
**PS: You can clone it at https://github.com/fernandotenorio/
It looks like you can get rid of the best parameter to minimax, thereby eliminating the need for garbage, and then replace best with this.bestFound. Only set bestFound's attributes if depth = 0.
You can get the principal variation by making this.bestFound an initially empty list. Before the moves loop, create a new move. In the if (score > alpha) part, set its attributes the same as you do now. Push the move to the list right after the loop. The principal variation will then be the reverse of the list.
If it's important, here are some changes you can make to improve the multi-threadability of your class:
Instead of storing the bestFound list as an instance variable, make it a local variable in run and add it as a parameter to minimax
Make Board.makeMove not modify the board, but instead return a new instance of the board with the move applied. You can implement that by cloning the board and applying your move code to the clone instead of mutating this. Then, pass the cloned board to the next invocation of minimax.
The second argument of minimax is used to return the best move.
The business with garbage is used to keep the best move for each turn separate. With the code you've provided, this is not important. But if you wanted to produce a sequence of moves from the current board to the end of the game, you would need to have them be separate move objects.
Using a separate best-move object for each turn allows you to do a number of tricks with threading. First, you might want to limit the thinking time of the Othello AI. Tracking the best move separately at each level means that you always have the best move so far available. It also means that you could cache the best move for a board and look that up in future minimax searches.
Second, you might want to search for the best move in parallel, and this is trivial to implement when each minimax call is independent.

Collision detection with bitmap Android

Alright, so i cant figure out how to make this rpg game im working for android have collision.
I draw the map on the screen in a drawable portion that the character is located in. I move the character by a 64 amount across the screen and when it hits the bounds of the screen it will then move the map and look like the character is moving across the map. It stop when the map hits the end it doesnt move the screen any more. What im trying to do is figure out a away to check if my character is in a certain bitmap and not let it pass through. Here is the code for my player moving, and the map itself. The character and the tiles are bitmaps.
Anything else needed to allow you to help me better comment and i will post more and how it works.
Edit:
sp.yp and sp.xp is the position of the character on screen.
This Draw the map to the screen:
public void draw(Canvas canvas){
//How many tiles are on the screen length times width
for(int x = 0; x <= 31;x++){
for(int y = 0; y <= 17;y++){
switch(Map[Mapx + x][Mapy + y]){
case 0:
canvas.drawBitmap(BLOCK_ROCK, x*32,y*32,null);
break;
case 1:
canvas.drawBitmap(BLOCK_OCEAN, x*32,y*32,null);
break;
case 2:
canvas.drawBitmap(BLOCK_GRASS, x*32,y*32,null);
break;
case 3:
canvas.drawBitmap(BLOCK_ROCK, x*32,y*32,null);
break;
case 4:
canvas.drawBitmap(BLOCK_FLOWER, x*32,y*32,null);
break;
}
}
}
}
This is the movment of the player, these methods are called when person hits the keypad i have drawn to the screen:
public void Down(){
if(sp.yp == 512){
if(w.Mapy == w.mapheight - 17 - 1){
}else{
w.Mapy +=1;
}
}else{
sp.setYd(64);
sp.update();
sp.setYd(0);
}
}
public void Left(){
if(sp.xp == box.xMin + 32){
sp.isRight = false;
if(w.Mapx == 0){
}else{
w.Mapx -=1;
}
}else{
sp.isRight = false;
sp.setXd(-64);
sp.update();
sp.xd = 0;
}
}
public void Jump(){
if(sp.yp == 64){
if(w.Mapy == 0){
}else{
w.Mapy -=1;
}
}else{
sp.setYd(-64);
sp.update();
sp.setYd(0);
}
}
public void Right(){
if(sp.xp == 992){
sp.isRight = true;
if(w.Mapx == w.mapwidth - 31 - 1){
}else{
w.Mapx +=1;
}
}else{
sp.isRight = true;
sp.setXd(64);
sp.update();
sp.xd = 0;
}
}
You should look into a game engine to handle this type of thing. There are several that are easy to import into your project and provide a great deal of functionality so you can work on designing the game and media resources more. Trust me, you probably don't want to code the whole engine.
Check
AndEngine - http://www.andengine.org/
Libgdx - http://code.google.com/p/libgdx/
I suggest AndEngine because there is a great app of simple examples you can use to experiment with. You can find it on:
code.google.com/p/ andengineexamples/
(no space in the address... sorry couldn't post more than two links)

Categories