Related
I am writing a simple game and I am working with java in JFrame. My output looks very bad untill I move the platform at the bottom, it looks like it have not enought update rate untill I press a button update and when I release the key it does the same thing. So this is the complete code with 2 classes:
public class BrickBreaker {
private static final String TITLE = "break ball";
private static final int X = 200, Y = 200, WIDTH = 700, HEIGHT = 600;
public static void main(String[] arg){
JFrame window = new JFrame();
GamePlay gp = new GamePlay();
window.setBounds(X,Y,WIDTH,HEIGHT);
window.setTitle(TITLE);
window.setResizable(false);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(gp);
}
}
public class GamePlay extends JPanel implements KeyListener, ActionListener {
private boolean play = false;
private int score = 0, totalBricks = 21, delay = 10;
private int playerX = 310;
private int ballX = 120, ballY = 350, ballDirX = -1, ballDirY = -2;
private final Timer TIMER;
public GamePlay(){
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
TIMER = new Timer(delay, this);
TIMER.start();
}
public void paint(Graphics g){
//Background
g.setColor(Color.BLACK);
g.fillRect(1,1,700,592);
//Borders
g.setColor(Color.YELLOW);
g.fillRect(0,0,3,592);
g.fillRect(697,0,3,592);
g.fillRect(0,0,697,3);
//Paddle
g.setColor(Color.GREEN);
g.fillRect(playerX, 550, 100, 8);
//Ball
g.setColor(Color.YELLOW);
g.fillOval(ballX, ballY, 20, 20);
g.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
TIMER.start();
if (play){
TIMER.start();
ballX += ballDirX;
ballY += ballDirY;
if(ballX <= 0 || ballX >= 700){
ballDirX = - ballDirX;
}
if(ballY <= 0 || ballY >= 600){
ballDirY = -ballDirY;
}
}
repaint();
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
if(playerX >= 590){
playerX = 590;
}else{
moveRight();
}
}else if(e.getKeyCode() == KeyEvent.VK_LEFT){
if(playerX <= 10){
playerX = 10;
}else{
moveLeft();
}
}
}
private void moveLeft() {
play = true;
playerX -= 20;
}
private void moveRight() {
play = true;
playerX += 20;
}
}
I want to know how to smooth the movement of the ball to be always at the rate of the keypressed state.
First of all there is no need to start the Timer in the ActionListener. You already start the Timer in the constructor.
JFrame updates my screen slow untill I press a key
There is no animation at all when I run the code.
Lets do some basic debugging:
public void actionPerformed(ActionEvent e) {
System.out.println(Play); // basic debugging
What do you see?
Then what happens when you press an arrow key?
Why do you only set the play variable in the moveRight/moveLeft methods?
I am making a java sliding puzzle for my project, and i have managed to crop the images and making it move to a blank space, however i am still puzzled on how to know whether the user got the correct solution or not. i wanted to congratulate the user when he gets the correct pattern.
import java.applet.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class SlidePuzz extends Applet implements MouseMotionListener,MouseListener {
int gridDim = 3;
int animal = -1;
int pieceDim = 0;
int a; int b;
int gapX = -1; int gapY = -1;
int moveX = -1; int moveY = -1;
Image[][] pieces = new Image[7][7];
int[][] placement = new int[7][7];
String [] images = {"mouse","cat","dog"};
String stage = "grid";
Image img;
public void init() {
setSize(420, 420);
addMouseMotionListener(this);
addMouseListener(this);
}
public void paint(Graphics g) {
if(stage=="grid") {
g.setColor(Color.lightGray);
g.fillRect(0,0,60*gridDim,60*gridDim);
g.setColor(Color.white);
g.fillRect(60*gridDim,0,(7-gridDim)*60,420);
g.fillRect(0,60*gridDim,60*gridDim,(7-gridDim)*60);
g.setColor(Color.black);
for (int i=1; i<7; i++) {
g.drawLine(i*60,0,i*60,460);
g.drawLine(0,i*60,460,i*60);
}
g.setColor(Color.black);
g.fillRect(120,0,180,20);
g.setColor(Color.white);
g.drawString("click to choose "+gridDim+"x"+gridDim+" grid", 145, 15);
} else if (stage=="animal") {
g.setColor(Color.white);
g.fillRect(0,0,420,420);
g.setColor(Color.black);
g.drawString("Please click an animal...", 80, 100);
g.setFont(new Font("Courier New", Font.BOLD, 22));
g.drawString("Mouse", 80, 150);
g.drawString("Cat", 80, 200);
g.drawString("Dog", 80, 250);
} else if (stage=="game") {
if (gapX<0) {
g.setColor(Color.white);
g.fillRect(0,0,420,420);
g.setColor(Color.black);
g.setFont(new Font("Courier New", Font.PLAIN, 12));
g.drawString("Loading image...", 120, 50);
tr = new MediaTracker(this);
img = getImage(getCodeBase(), images[animal]+".jpg");
tr.addImage(img,0);
for(int x=0; x<gridDim; x++) {
for(int y=0; y<gridDim; y++) {
pieces[x][y] = createImage(new FilteredImageSource(img.getSource(),
new CropImageFilter(x*pieceDim, y*pieceDim, pieceDim, pieceDim)));
placement[x][y] = (x==gridDim-1 && y==gridDim-1) ? -2 : -1;
tr.addImage(pieces[x][y],0);
}
}
Random r = new Random();
Boolean placed;
for(int x=0; x<gridDim; x++) {
for(int y=0; y<gridDim; y++) {
// if its the gap, no need to draw anything
if (placement[x][y]==-2) break;
// keep looping until piece is selected thats not already drawn
do {
do {
a = r.nextInt(gridDim);
b = r.nextInt(gridDim);
} while (a==gridDim-1 && b==gridDim-1);
placed = false;
for(int c=0; c<gridDim; c++) {
for(int d=0; d<gridDim; d++) {
if(placement[c][d]==a*10+b) placed=true;
}
}
} while (placed);
// draw on the screen and record what's gone here
g.drawImage(pieces[a][b], x*pieceDim, y*pieceDim, this);
placement[x][y] = a*10+b;
}
}
// record where the gap is
gapX = gridDim-1; gapY = gridDim-1;
// a piece needs to be moved
} else if (moveX>=0){
g.setColor(Color.white);
g.fillRect(moveX*pieceDim, moveY*pieceDim, pieceDim, pieceDim);
b = placement[moveX][moveY]%10;
a = (placement[moveX][moveY]-b)/10;
g.drawImage(pieces[a][b], gapX*pieceDim, gapY*pieceDim, this);
placement[gapX][gapY] = a*10+b;
placement[moveX][moveY] = -2;
gapX = moveX; gapY = moveY;
moveX = -1; moveY = -1;
} else {
for(int x=0; x<gridDim; x++) {
for(int y=0; y<gridDim; y++) {
if (placement[x][y]==-2) continue;
b = placement[x][y]%10;
a = (placement[x][y]-b)/10;
g.drawImage(pieces[a][b], x*pieceDim, y*pieceDim, this);
}
}
}
}
}
public void mouseMoved(MouseEvent me) {
if(stage=="grid") {
int mousePos = me.getX()>me.getY() ? me.getX() : me.getY();
int oldGridSize = gridDim;
gridDim = (mousePos/60)+1;
if(gridDim<3) gridDim=3;
if (gridDim!=oldGridSize) repaint();
}
}
public void mousePressed (MouseEvent me) {
int x = me.getX();
int y = me.getY();
if(stage=="grid") {
stage = "animal";
repaint();
} else if(stage=="animal") {
if(x<150 && x>80 && y<150 && y>130) animal=0;
else if(x<150 && x>80 && y<200 && y>180) animal=1;
else if(x<150 && x>80 && y<250 && y>130) animal=2;
if (animal>-1) {
stage="game";
pieceDim = 420/gridDim;
repaint();
}
} else if(stage=="game") {
x /= pieceDim;
y /= pieceDim;
Boolean right = (x-1==gapX && y==gapY);
Boolean left = (x+1==gapX && y==gapY);
Boolean down = (x==gapX && y-1==gapY);
Boolean up = (x==gapX && y+1==gapY);
if (right || left || down || up) {
moveX = x;
moveY = y;
repaint();
}
}
}
public void update(Graphics g) { paint(g); }
public void mouseDragged (MouseEvent me) {}
public void mouseExited (MouseEvent me) {}
public void mouseEntered (MouseEvent me) {}
public void mouseClicked (MouseEvent me) {}
public void mouseReleased (MouseEvent me) {}
}
This code is to a game named brick-breaker. I tried to make the ball change colors when intersecting with the array. I've created an int for the R,G,B values of the custom color, and have these ints be generated on intersect to a number between 1-255
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import java.util.Random;
public class brickbreaker extends Applet implements MouseListener, Runnable, KeyListener
{
Thread main=new Thread(this);
int mouseX, mouseY;
int paddleX = 200, x,y,height,width, ballX = 100, ballY = 400, xChange = 1, yChange = 4, paddleWidth = 150, pageCt = 1, score = 0;
boolean pause = false, gameover=false;
boolean blocks[][] = new boolean [6][10];
int randomR = 255, randomG = 205, randomB = 155;
Random red = new Random();
Random green = new Random();
Random blue = new Random();
Image buffer;
Graphics bufferG;
String input="";
Font font3 = new Font ("Impact",5,50);
Font font4 = new Font ("Impact",5,150);
Font font5 = new Font ("Impact",5,30);
Color randomColor = new Color(randomR,randomG,randomB);
public void init()
{
resize( 1300,700 );
buffer = createImage(this.getWidth(),this.getHeight());
bufferG = buffer.getGraphics();
this.setLayout (null);
this.addKeyListener(this);
this.addMouseListener(this);
this.resize(1400,700);
main.start();
for(int r=0;r<6;r++)
for(int c=0;c<10;c++)
blocks[r][c] = true;
}
public void drawBlocks(Graphics g)
{
for(int r=0;r<6;r++)
for(int c=0;c<10;c++)
if(blocks[r][c])
g.drawRect(100+100*c, 30+30*r, 100, 30);
}
public void run()
{
if (pageCt==1)
{
while(! gameover)
{
if(pause==false)
{
repaint();
ballX = ballX + xChange;
ballY = ballY + yChange;
Rectangle ballRect = new Rectangle (ballX, ballY, 15, 15);
Rectangle paddleRect = new Rectangle (paddleX,650,paddleWidth,10);
Rectangle boundRect = new Rectangle (0,690,1300,10);
for(int r=0;r<6;r++)
for(int c=0;c<10;c++)
if(blocks[r][c])
{
Rectangle blockRect = new Rectangle (100+100*c, 30+30*r, 100, 30);
if(blockRect.intersects(ballRect))
{
blocks[r][c] = false;
yChange *=-1;
score++;
randomR=red.nextInt(255);
randomB=blue.nextInt(255);
randomG=green.nextInt(255);
if (score==60)
pageCt=4;
}
}
if(ballX < 5 || ballX > 1280)
xChange = -1*xChange;
if(ballY < 5 || ballY > 690)
yChange = -1*yChange;
if (ballRect.intersects (paddleRect))
{
yChange = yChange*-1;
//paddleWidth=paddleWidth-3;
}
if (ballRect.intersects (boundRect))
{
pageCt=2;
}
}
repaint();
try
{main.sleep(20);}
catch(Exception e) {}
}
}
}
public void keyPressed(KeyEvent e) // makes applet do something when clicked.
{
int code = e.getKeyCode();
if(code == e.VK_P)
{
if(pause==false)
pause=true;
else
pause=false;
}
if (pause==false)
{
if(paddleX>20)
{
if(code == e.VK_A)
{
paddleX = paddleX-20;
}
}
if(paddleX<1160)
{
if(code == e.VK_D)
{
paddleX = paddleX+20;
}
}
}
}
public void paint(Graphics g) // Outputs on screen
{
if (pageCt==1)
{
bufferG.setColor(Color.black);
bufferG.fillRect(0,0,1300,700);
bufferG.setColor(Color.blue);
bufferG.setColor(Color.black);
bufferG.fillRect(0,0,this.getWidth(),this.getHeight());
bufferG.setColor(randomColor);
bufferG.fillOval(ballX,ballY,15,15);
bufferG.setColor(Color.white);
bufferG.fillRect(paddleX,650,paddleWidth,10);
drawBlocks(bufferG);
bufferG.setFont(font5);
bufferG.drawString("Score : "+score,10,20);
}
if (pageCt==2)
{
bufferG.setColor(Color.black);
bufferG.fillRect(0,0,1300,700);
bufferG.setColor(Color.white);
bufferG.setFont(font4);
bufferG.drawString("You Lose!", 350,400);
}
if (pause==true)
{
bufferG.setColor(Color.white);
bufferG.setFont(font4);
bufferG.drawString("PAUSED",400,350);
}
if (pageCt==0)
{
bufferG.drawString("- Click to begin -",350,350);
}
g.drawImage(buffer,0,0,this);
}
public void update(Graphics g)
{
paint(g);
}
public void mouseClicked (MouseEvent e) {}
public void keyReleased( KeyEvent e){}
public void keyTyped (KeyEvent e){}
public void mousePressed (MouseEvent e)
{
if(pageCt==0)
{
pageCt++;
repaint();
}
}
public void mouseReleased (MouseEvent e) {}
public void mouseEntered (MouseEvent e){}
public void mouseExited (MouseEvent e) {}
}
The color doesn't change because you aren't updating it with the randomly generated values.
randomR=red.nextInt(255);
randomB=blue.nextInt(255);
randomG=green.nextInt(255);
randomColor = new Color(randomR,randomG,randomB); // <- add this line
I made 2 objects that moves with keylisteners. They move correctly, but in the console I receive this error every time I press a button:
Exception in thread "AWT-EventQueue-0"
java.lang.UnsupportedOperationException: Not supported yet. at
CatchMe.CatchMe.keyTyped(CatchMe.java:197)
My code is as follows:
package CatchMe;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class CatchMe extends JFrame implements ActionListener, KeyListener {
private Image dbImage;
private Graphics dbg;
int x = 200, y = 300;
int velX, velY;
int velX1, velY1;
int ScoreB1 = 0;
int ScoreR1 = 0;
Timer tm = new Timer(5, this);
long startTime = System.currentTimeMillis();
long onGoing;
String onG;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) screenSize.getWidth();
int height = (int) screenSize.getHeight();
int recX = (width + 100) / 2, recY = (height + 100) / 2;
public CatchMe() {
setSize(width, height);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
Rectangle r1 = new Rectangle(recX, recY, 25, 25);
Rectangle r2 = new Rectangle(x, y, 25, 25);
g.setColor(Color.BLUE);
g.fillRect(r1.x, r1.y, r1.width, r1.height);
g.setColor(Color.RED);
g.fillRect(r2.x, r2.y, r2.width, r2.height);
g.setColor(Color.BLACK);
g.fillRect(0, 20, 100, 50);
g.fillRect(100, 20, 100, 50);
g.fillRect(200, 20, 50, 50);
g.setColor(Color.YELLOW);
g.drawString("Score of Blue", 5, 40);
String ScoreB = ScoreB1 + "";
g.drawString(ScoreB, 5, 55);
g.drawString("Score of Red", 110, 40);
String ScoreR = ScoreR1 + "";
g.drawString(ScoreR, 110, 55);
g.drawLine(95, 20, 95, 69);
g.drawLine(200, 20, 200, 69);
g.setColor(Color.RED);
onGoing = (System.currentTimeMillis() - startTime) / 1000;
onG = onGoing + "";
g.setColor(Color.YELLOW);
g.drawString(onG, 220, 50);
System.out.println(onGoing);
if (r1.intersects(r2)) {
if (onGoing <= 60 || (onGoing >= 120 && onGoing < 180)) {
g.setColor(Color.BLUE);
g.drawString("Blue Caught You!", 175, 90);
ScoreB1++;
} else if (onGoing >= 240) {
if (ScoreB1 > ScoreR1) {
Font font = new Font("Jokerman", Font.PLAIN, 50);
g.setColor(Color.BLUE);
g.drawString("BLUE WINS", 600, 400);
} else if (ScoreB1 < ScoreR1) {
Font font = new Font("Jokerman", Font.PLAIN, 50);
g.setColor(Color.RED);
g.drawString("RED WINS", 600, 400);
}
} else {
g.setColor(Color.RED);
g.drawString("Red Caught You!", 175, 90);
ScoreR1++;
}
if (onGoing == 245) {
System.exit(245);
}
repaint();
}
}
#Override
public void actionPerformed(ActionEvent e) {
x = x + velX;
y = y + velY;
recY += velY1;
recX += velX1;
if (x < 0) {
velX = 0;
x = 0;
}
if (x > width - 50) {
velX = 0;
x = width - 50;
}
if (y < 0) {
velY = 0;
y = 0;
}
if (y > height - 40) {
velY = 0;
y = height - 40;
}
//Second square
if (recX < 0) {
velX1 = 0;
recX = 0;
}
if (recX > width - 50) {
velX1 = 0;
recX = width - 50;
}
if (recY < 0) {
velY1 = 0;
recY = 0;
}
if (recY > height - 40) {
velY1 = 0;
recY = height - 40;
}
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_LEFT) {
velX = -5;
velY = 0;
}
if (code == KeyEvent.VK_UP) {
velX = 0;
velY = -5;
}
if (code == KeyEvent.VK_RIGHT) {
velX = 5;
velY = 0;
}
if (code == KeyEvent.VK_DOWN) {
velX = 0;
velY = 5;
}
//Second Rect
if (code == KeyEvent.VK_A) {
velX1 = -5;
velY1 = 0;
}
if (code == KeyEvent.VK_W) {
velX1 = 0;
velY1 = -5;
}
if (code == KeyEvent.VK_D) {
velX1 = 5;
velY1 = 0;
}
if (code == KeyEvent.VK_S) {
velX1 = 0;
velY1 = 5;
}
}
#Override
public void keyReleased(KeyEvent e) {
velX = 0;
velY = 0;
velX1 = 0;
velY1 = 0;
}
public static void main(String[] args) {
CatchMe main = new CatchMe();
}
#Override
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
The keyTyped method throws an UnsupportedOperationException because you implemented it this way(or it was automatically generated this way):
#Override
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Whenever a key is typed, this method is called, so it throws an exception.
To fix it, you need to change the body of this method. If you don't want it to do anything, just leave its body empty:
#Override
public void keyTyped(KeyEvent e) {
}
If you want to do something, you should implement this method according to the desired behavior. For example, this implementation prints a message every time a key is typed:
#Override
public void keyTyped(KeyEvent e) {
System.out.println("A key was typed");
}
#Override
public void keyTyped(KeyEvent e) {
}
Will fix it, you were manually throwing exception when keyTyped is called.
Okay so, I've my main class which loads everything in from my framework. What I'm having trouble with now is my collision detection; I've got it so if it hits something, something will happen. I've a method that calls a GameOverUI in the GameScreen class, but I want to use that in my Enemy.class .. I've created a new instance for the object but it's saying its undefined. What I dont get is the class has no definition but a method called GameScreen is defined by (Game game).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import android.graphics.Color;
import android.graphics.Paint;
import com.vaughanslater.framework.Game;
import com.vaughanslater.framework.Graphics;
import com.vaughanslater.framework.Image;
import com.vaughanslater.framework.Input.TouchEvent;
import com.vaughanslater.framework.Screen;
public class GameScreen extends Screen {
enum GameState {
Ready, Running, Paused, GameOver
}
GameState state = GameState.Ready;
// Variable Setup
private static Background bg1, bg2;
private static Robot robot;
public static Heliboy hb, hb2;
private Image currentSprite, character, character2, character3, heliboy,
heliboy2, heliboy3, heliboy4, heliboy5;
private Animation anim, hanim;
private ArrayList tilearray = new ArrayList();
int livesLeft = 1;
Paint paint, paint2;
public GameScreen(Game game) {
super(game);
// Initialize game objects here
bg1 = new Background(0, 0);
bg2 = new Background(2160, 0);
robot = new Robot();
hb = new Heliboy(340, 360);
hb2 = new Heliboy(700, 360);
character = Assets.character;
character2 = Assets.character2;
character3 = Assets.character3;
heliboy = Assets.heliboy;
heliboy2 = Assets.heliboy2;
heliboy3 = Assets.heliboy3;
heliboy4 = Assets.heliboy4;
heliboy5 = Assets.heliboy5;
anim = new Animation();
anim.addFrame(character, 1250);
anim.addFrame(character2, 50);
anim.addFrame(character3, 50);
anim.addFrame(character2, 50);
hanim = new Animation();
hanim.addFrame(heliboy, 100);
hanim.addFrame(heliboy2, 100);
hanim.addFrame(heliboy3, 100);
hanim.addFrame(heliboy4, 100);
hanim.addFrame(heliboy5, 100);
hanim.addFrame(heliboy4, 100);
hanim.addFrame(heliboy3, 100);
hanim.addFrame(heliboy2, 100);
currentSprite = anim.getImage();
loadMap();
// Defining a paint object
paint = new Paint();
paint.setTextSize(30);
paint.setTextAlign(Paint.Align.CENTER);
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint2 = new Paint();
paint2.setTextSize(100);
paint2.setTextAlign(Paint.Align.CENTER);
paint2.setAntiAlias(true);
paint2.setColor(Color.WHITE);
}
private void loadMap() {
ArrayList lines = new ArrayList();
int width = 0;
int height = 0;
Scanner scanner = new Scanner(SampleGame.map);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// no more lines to read
if (line == null) {
break;
}
if (!line.startsWith("!")) {
lines.add(line);
width = Math.max(width, line.length());
}
}
height = lines.size();
for (int j = 0; j < 12; j++) {
String line = (String) lines.get(j);
for (int i = 0; i < width; i++) {
if (i < line.length()) {
char ch = line.charAt(i);
Tile t = new Tile(i, j, Character.getNumericValue(ch));
tilearray.add(t);
}
}
}
}
#Override
public void update(float deltaTime) {
List touchEvents = game.getInput().getTouchEvents();
// We have four separate update methods in this example.
// Depending on the state of the game, we call different update methods.
// Refer to Unit 3's code. We did a similar thing without separating the
// update methods.
if (state == GameState.Ready)
updateReady(touchEvents);
if (state == GameState.Running)
updateRunning(touchEvents, deltaTime);
if (state == GameState.Paused)
updatePaused(touchEvents);
if (state == GameState.GameOver)
updateGameOver(touchEvents);
}
private void updateReady(List touchEvents) {
// This example starts with a "Ready" screen.
// When the user touches the screen, the game begins.
// state now becomes GameState.Running.
// Now the updateRunning() method will be called!
if (touchEvents.size() > 0)
state = GameState.Running;
}
private void updateRunning(List touchEvents, float deltaTime) {
// This is identical to the update() method from our Unit 2/3 game.
// 1. All touch input is handled here:
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = (TouchEvent) touchEvents.get(i);
if (event.type == TouchEvent.TOUCH_DOWN) {
if (event.x > 400) {
robot.jump();
currentSprite = anim.getImage();
robot.setDucked(false);
}
else if (inBounds(event, 0, 350, 65, 65)) {
if (robot.isDucked() == false && robot.isJumped() == false
&& robot.isReadyToFire()) {
robot.shoot();
}
}
else if (event.x < 400
&& robot.isJumped() == false) {
currentSprite = Assets.characterDown;
robot.setDucked(true);
robot.setSpeedX(0);
}
//if (event.x > 400) {
// Move right.
// robot.moveRight();
// robot.setMovingRight(true);
//}
}
if (event.type == TouchEvent.TOUCH_UP) {
if (event.x < 400) {
currentSprite = anim.getImage();
robot.setDucked(false);
}
if (inBounds(event, 0, 0, 35, 35)) {
pause();
}
if (event.x > 400) {
// Move right.
robot.stopRight();
}
}
}
// 2. Check miscellaneous events like death:
if (livesLeft == 0) {
state = GameState.GameOver;
}
// 3. Call individual update() methods here.
// This is where all the game updates happen.
// For example, robot.update();
robot.update();
if (robot.isJumped()) {
currentSprite = Assets.characterJump;
} else if (robot.isJumped() == false && robot.isDucked() == false) {
currentSprite = anim.getImage();
}
ArrayList projectiles = robot.getProjectiles();
for (int i = 0; i < projectiles.size(); i++) {
Projectile p = (Projectile) projectiles.get(i);
if (p.isVisible() == true) {
p.update();
} else {
projectiles.remove(i);
}
}
updateTiles();
hb.update();
hb2.update();
bg1.update();
bg2.update();
animate();
if (robot.getCenterY() > 500) {
state = GameState.GameOver;
}
}
private boolean inBounds(TouchEvent event, int x, int y, int width,
int height) {
if (event.x > x && event.x < x + width - 1 && event.y > y
&& event.y < y + height - 1)
return true;
else
return false;
}
private void updatePaused(List touchEvents) {
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = (TouchEvent) touchEvents.get(i);
if (event.type == TouchEvent.TOUCH_UP) {
if (inBounds(event, 0, 0, 800, 240)) {
if (!inBounds(event, 0, 0, 35, 35)) {
resume();
}
}
if (inBounds(event, 0, 240, 800, 240)) {
nullify();
goToMenu();
}
}
}
}
private void updateGameOver(List touchEvents) {
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = (TouchEvent) touchEvents.get(i);
if (event.type == TouchEvent.TOUCH_DOWN) {
if (inBounds(event, 0, 0, 800, 480)) {
nullify();
game.setScreen(new MainMenuScreen(game));
return;
}
}
}
}
private void updateTiles() {
for (int i = 0; i < tilearray.size(); i++) {
Tile t = (Tile) tilearray.get(i);
t.update();
}
}
#Override
public void paint(float deltaTime) {
Graphics g = game.getGraphics();
g.drawImage(Assets.background, bg1.getBgX(), bg1.getBgY());
g.drawImage(Assets.background, bg2.getBgX(), bg2.getBgY());
paintTiles(g);
ArrayList projectiles = robot.getProjectiles();
for (int i = 0; i < projectiles.size(); i++) {
Projectile p = (Projectile) projectiles.get(i);
g.drawRect(p.getX(), p.getY(), 10, 5, Color.YELLOW);
}
// First draw the game elements.
g.drawImage(currentSprite, robot.getCenterX() - -15,
robot.getCenterY() - -17);
g.drawImage(hanim.getImage(), hb.getCenterX() - 48,
hb.getCenterY() - 48);
g.drawImage(hanim.getImage(), hb2.getCenterX() - 48,
hb2.getCenterY() - 48);
// Example:
// g.drawImage(Assets.background, 0, 0);
// g.drawImage(Assets.character, characterX, characterY);
// Secondly, draw the UI above the game elements.
if (state == GameState.Ready)
drawReadyUI();
if (state == GameState.Running)
drawRunningUI();
if (state == GameState.Paused)
drawPausedUI();
if (state == GameState.GameOver)
drawGameOverUI();
}
private void paintTiles(Graphics g) {
for (int i = 0; i < tilearray.size(); i++) {
Tile t = (Tile) tilearray.get(i);
if (t.type != 0) {
g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY());
}
}
}
public void animate() {
anim.update(10);
hanim.update(50);
}
private void nullify() {
// Set all variables to null. You will be recreating them in the
// constructor.
paint = null;
bg1 = null;
bg2 = null;
robot = null;
hb = null;
hb2 = null;
currentSprite = null;
character = null;
character2 = null;
character3 = null;
heliboy = null;
heliboy2 = null;
heliboy3 = null;
heliboy4 = null;
heliboy5 = null;
anim = null;
hanim = null;
// Call garbage collector to clean up memory.
System.gc();
}
private void drawReadyUI() {
Graphics g = game.getGraphics();
g.drawARGB(155, 0, 0, 0);
g.drawString("Tap to Start.", 400, 240, paint);
}
private void drawRunningUI() {
Graphics g = game.getGraphics();
//g.drawImage(Assets.button, 0, 285, 0, 0, 65, 65);
//g.drawImage(Assets.button, 0, 350, 0, 65, 65, 65);
//g.drawImage(Assets.button, 0, 415, 0, 130, 65, 65);
g.drawImage(Assets.button, 0, 0, 0, 195, 35, 35);
}
private void drawPausedUI() {
Graphics g = game.getGraphics();
// Darken the entire screen so you can display the Paused screen.
g.drawARGB(155, 0, 0, 0);
g.drawString("Resume", 400, 165, paint2);
g.drawString("Menu", 400, 360, paint2);
}
public void drawGameOverUI() {
Graphics g = game.getGraphics();
g.drawRect(0, 0, 1281, 801, Color.BLACK);
g.drawString("GAME OVER.", 400, 240, paint2);
g.drawString("Tap to return.", 400, 290, paint);
}
#Override
public void pause() {
if (state == GameState.Running)
state = GameState.Paused;
}
#Override
public void resume() {
if (state == GameState.Paused)
state = GameState.Running;
}
public GameState getState() {
return state;
}
public void setState(GameState state) {
this.state = state;
}
#Override
public void dispose() {
}
#Override
public void backButton() {
pause();
}
private void goToMenu() {
// TODO Auto-generated method stub
game.setScreen(new MainMenuScreen(game));
}
public static Background getBg1() {
// TODO Auto-generated method stub
return bg1;
}
public static Background getBg2() {
// TODO Auto-generated method stub
return bg2;
}
public static Robot getRobot() {
// TODO Auto-generated method stub
return robot;
}
}
Heres my enemy class too:
import android.graphics.Rect;
public class Enemy {
private int power, centerX, speedX, centerY;
private Background bg = GameScreen.getBg1();
private Robot robot = GameScreen.getRobot();
public Rect r = new Rect(0, 0, 0, 0);
public int health = 5;
private int movementSpeed;
// Behavioural Methods
public void update() {
follow();
centerX += speedX;
speedX = bg.getSpeedX() * 5 + movementSpeed;
r.set(centerX - 25, centerY - 25, centerX + 25, centerY + 35);
if (Rect.intersects(r, Robot.yellowRed)) {
checkCollision();
}
}
private void checkCollision() {
if (Rect.intersects(r, Robot.rect) || Rect.intersects(r, Robot.rect2)
|| Rect.intersects(r, Robot.rect3)
|| Rect.intersects(r, Robot.rect4)) {
GameScreen state = new GameScreen(); // This is where it errors
}
}
public void follow() {
if (centerX < -95 || centerX > 810) {
movementSpeed = 0;
}
else if (Math.abs(robot.getCenterX() - centerX) < 5) {
movementSpeed = 0;
}
else {
if (robot.getCenterX() >= centerX) {
movementSpeed = 1;
} else {
movementSpeed = -1;
}
}
}
public void die() {
}
public void attack() {
}
public int getPower() {
return power;
}
public int getSpeedX() {
return speedX;
}
public int getCenterX() {
return centerX;
}
public int getCenterY() {
return centerY;
}
public Background getBg() {
return bg;
}
public void setPower(int power) {
this.power = power;
}
public void setSpeedX(int speedX) {
this.speedX = speedX;
}
public void setCenterX(int centerX) {
this.centerX = centerX;
}
public void setCenterY(int centerY) {
this.centerY = centerY;
}
public void setBg(Background bg) {
this.bg = bg;
}
}
So here is where it errors:
GameScreen state = new GameScreen(); // This is where it errors
I dont get it, I'm not calling the method GameScreen(Game game) which is defined, but I'm calling the class which isn't. I want to use the drawGameOverUI();.
Sorry for the wall of code.. atleast you can see everthing.
If you define any constructor , default constructor is never used. Please define implementation of GameScreen() or remove the implementation of GameScreen(Game game).
Define a default constructor like this -
public GameScreen() {
super();
// Initialize game objects here
bg1 = new Background(0, 0);
bg2 = new Background(2160, 0);
robot = new Robot();
hb = new Heliboy(340, 360);
hb2 = new Heliboy(700, 360);
character = Assets.character;
character2 = Assets.character2;
character3 = Assets.character3;
heliboy = Assets.heliboy;
heliboy2 = Assets.heliboy2;
heliboy3 = Assets.heliboy3;
heliboy4 = Assets.heliboy4;
heliboy5 = Assets.heliboy5;
anim = new Animation();
anim.addFrame(character, 1250);
anim.addFrame(character2, 50);
anim.addFrame(character3, 50);
anim.addFrame(character2, 50);
hanim = new Animation();
hanim.addFrame(heliboy, 100);
hanim.addFrame(heliboy2, 100);
hanim.addFrame(heliboy3, 100);
hanim.addFrame(heliboy4, 100);
hanim.addFrame(heliboy5, 100);
hanim.addFrame(heliboy4, 100);
hanim.addFrame(heliboy3, 100);
hanim.addFrame(heliboy2, 100);
currentSprite = anim.getImage();
loadMap();
// Defining a paint object
paint = new Paint();
paint.setTextSize(30);
paint.setTextAlign(Paint.Align.CENTER);
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint2 = new Paint();
paint2.setTextSize(100);
paint2.setTextAlign(Paint.Align.CENTER);
paint2.setAntiAlias(true);
paint2.setColor(Color.WHITE);
}
By defining a constructor that accepts an argument you are forcing users to call it.
If you want one without a mandatory game param, define one.