Android Game - set time limit to 30 seconds - java

I'm working on a simple Android game.
When you press play, a timer counts down from 30, and once the timer hits zero, I want to call the function goToGameOver(). I can't seem to get a Handler working properly so I tried out the standard Timer class and it's not even close to real-time.
Also, as the timer counts down, I'd like to pass the time remaining into a global variable x every second, so that I can paint it onto the screen in a separate method.
Any thoughts on how I can best approach this? Thanks!
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
x = millisUntilFinished / 1000;
}
public void onFinish() {
goToGameOver();
} }.start();
EDIT:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Looper;
import com.name.framework.Game;
import com.name.framework.Graphics;
import com.name.framework.Image;
import com.name.framework.Input.TouchEvent;
import com.name.framework.Screen;
// Creates live game screen
public class GameScreen extends Screen {
enum GameState {
Running, Paused, GameOver
}
GameState state = GameState.Running;
// Instance variables
Random r = new Random();
int z = r.nextInt(16);
private int score = 0;
int count = 0;
private Runnable run;
public GameScreen(Game game) {
super(game);
Assets.paint = new Paint();
Assets.paint.setTextSize(30);
Assets.paint.setTextAlign(Paint.Align.LEFT);
Assets.paint.setAntiAlias(true);
Assets.paint.setColor(Color.BLACK);
}
// Check if touch coordinates fall in certain range
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;
}
#Override
public void update(float deltaTime) {
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
// Call appropriate update method based on game state
if (state == GameState.Running)
updateRunning(touchEvents, deltaTime);
if (state == GameState.Paused)
updatePaused(touchEvents);
if (state == GameState.GameOver)
updateGameOver(touchEvents);
}
// Responds to in-game interaction
private void updateRunning(List<TouchEvent> touchEvents, float deltaTime) {
final Handler hand = new Handler();
run = new Runnable() {
#Override
public void run() {
if(count == 30) { //will end if count reach 30 which means 30 second
goToMenu();
}
else
{
count += 1; //add 1 every second
hand.postDelayed(run, 1000); //will call the runnable after 1 second
}
}
};
hand.postDelayed(run, 1000);
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = (TouchEvent) touchEvents.get(i);
if (event.type == TouchEvent.TOUCH_DOWN) {
switch(z) {
// Blue is correct
case 0:
case 1:
case 2:
case 3:
if (inBounds(event, 125, 150, 250, 100)) {
Assets.pop.play(0.8f);
score += 1;
z = r.nextInt(16); }
else if (inBounds(event, 425, 150, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
else if (inBounds(event, 125, 300, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
else if (inBounds(event, 425, 300, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
break;
// Green is correct
case 4:
case 5:
case 6:
case 7:
if (inBounds(event, 125, 150, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
else if (inBounds(event, 425, 150, 250, 100)) {
Assets.pop.play(0.8f);
score += 1;
z = r.nextInt(16); }
else if (inBounds(event, 125, 300, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
else if (inBounds(event, 425, 300, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
break;
// Red is correct
case 8:
case 9:
case 10:
case 11:
if (inBounds(event, 125, 150, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
else if (inBounds(event, 425, 150, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
else if (inBounds(event, 125, 300, 250, 100)) {
Assets.pop.play(0.8f);
score += 1;
z = r.nextInt(16); }
else if (inBounds(event, 425, 300, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
break;
// Yellow is correct
case 12:
case 13:
case 14:
case 15:
if (inBounds(event, 125, 150, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
else if (inBounds(event, 425, 150, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
else if (inBounds(event, 125, 300, 250, 100)) {
Assets.bad.play(0.8f);
score -= 5;
z = r.nextInt(16); }
else if (inBounds(event, 425, 300, 250, 100)) {
Assets.pop.play(0.8f);
score += 1;
z = r.nextInt(16); }
break;
}
// Pause button
if (inBounds(event, 750, 0, 50, 50)) {
Assets.pop.play(0.8f);
Assets.theme.pause();
state = GameState.Paused;
}
}
// Prevents score from becoming negative
if (score < 0) {
score = 0;
}
}
}
// Responds to pause menu interaction
private void updatePaused(List<TouchEvent> touchEvents) {
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if (event.type == TouchEvent.TOUCH_UP) {
// Resume button
if (inBounds(event, 125, 150, 250, 100)) {
Assets.pop.play(0.8f);
Assets.theme.play();
state = GameState.Running; }
// Restart button
else if (inBounds(event, 425, 150, 250, 100)) {
Assets.pop.play(0.8f);
Assets.theme.play();
nullify();
state = GameState.Running; }
// Mute button
else if (inBounds(event, 125, 300, 250, 100)) {
Assets.pop.play(0.8f);
}
// Menu button
else if (inBounds(event, 425, 300, 250, 100)) {
Assets.pop.play(0.8f);
//Assets.theme.seekBegin(); // not sure if I should do this
Assets.theme.play();
nullify();
goToMenu(); }
}
}
}
// Responds to game over interaction
private void updateGameOver(List<TouchEvent> touchEvents) {
}
#Override
public void paint(float deltaTime) {
Graphics g = game.getGraphics();
g.clearScreen(16777215);
g.drawImage(Assets.score, 20, 430);
g.drawImage(Assets.blue, 125, 150);
g.drawImage(Assets.green, 425, 150);
g.drawImage(Assets.red, 125, 300);
g.drawImage(Assets.yellow, 425, 300);
g.drawString(""+ score, 135, 465, Assets.paint);
//g.drawString(""+x, 750, 430, Assets.paint);
// Adds text to array and draws random one
ArrayList<Image> colors = new ArrayList<Image>();
colors.add(Assets.blueInBlue);
colors.add(Assets.blueInGreen);
colors.add(Assets.blueInRed);
colors.add(Assets.blueInYellow);
colors.add(Assets.greenInBlue);
colors.add(Assets.greenInGreen);
colors.add(Assets.greenInRed);
colors.add(Assets.greenInYellow);
colors.add(Assets.redInBlue);
colors.add(Assets.redInGreen);
colors.add(Assets.redInRed);
colors.add(Assets.redInYellow);
colors.add(Assets.yellowInBlue);
colors.add(Assets.yellowInGreen);
colors.add(Assets.yellowInRed);
colors.add(Assets.yellowInYellow);
if (state == GameState.Running) {
g.drawImage(colors.get(z), 0, 0);
}
// Calls the appropriate function to draw the UI based on game state
if (state == GameState.Running)
drawRunningUI();
if (state == GameState.Paused)
drawPausedUI();
if (state == GameState.GameOver)
drawGameOverUI();
}
// Draws in-game UI
private void drawRunningUI() {
Graphics g = game.getGraphics();
g.drawImage(Assets.pause, 750, 0);
}
// Draws pause menu UI
private void drawPausedUI() {
Graphics g = game.getGraphics();
g.drawARGB(155, 0, 0, 0);
g.drawImage(Assets.paused, 0, 0);
g.drawImage(Assets.resume, 125, 150);
g.drawImage(Assets.restart, 425, 150);
g.drawImage(Assets.mute, 125, 300);
g.drawImage(Assets.returnToMenu, 425, 300);
}
// Draws game over UI
private void drawGameOverUI() {
}
// Pause function
#Override
public void pause() {
if (state == GameState.Running)
state = GameState.Paused;
}
// Resume function
#Override
public void resume() {
if (state == GameState.Paused)
state = GameState.Running;
}
#Override
public void backButton() {
pause();
}
private void goToGameOver() {
game.setScreen(new MainMenuScreen(game));
}
// Resets timer and score
private void nullify() {
score = 0;
// Calls garbage collector to clean up memory
System.gc();
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
}

I would recommend handler for this even though you said that you've tried it, but i think you did not implement it correctly.
Here is the implementation and it work great on mine.
final Handler hand = new Handler();
run = new Runnable() {
#Override
public void run() {
if(count == 30) { //will end if count reach 30 which means 30 second
goToGameOver();
}
else
{
count += 1; //add 1 every second
hand.postDelayed(run, 1000); //will call the runnable after 1 second
}
}
};
hand.postDelayed(run, 1000);
Make sure that count and handler are global fields.

Related

Stuck on moving paddle

For my class I need to create a one player pong game. We need to use what we've learned so its simple code and the problem is, while the "while loop" is running, my Keydown thread doesn't seem to work. My teacher isn't helpful at all so that's why i'm here. Please help by only using methods and such that are used in my program.
I've tried moving the ball code into a run thread but i can never seem to actually get that thread running.
public class PongGame extends Applet {
int startup = 0;
int x = 400;
int y = 500;
int x2 = (int) (Math.random() * (600 + 1));
int y2 = (int) (Math.random() * (600 + 1));
int xVelocity = 1;
int yVelocity = 1;
int x2Velocity = 1;
int y2Velocity = 1;
int curry = 700;
int currx = 600;
int counter = 2;
#Override
public void init() {
setSize(1440, 900);
setBackground(Color.black);
setFont(new Font("Helvetica", Font.BOLD, 36));
}
#Override
public boolean keyDown(Event evt, int key) {
startup = startup + 1;
repaint();
if (key == Event.RIGHT) {
currx += 10;
}
if (key == Event.LEFT) {
currx -= 10;
}
if (currx == 1400) {
currx = 10;
}
if (currx == 20) {
currx = 1399;
}
repaint();
return false;
}
public void run(Graphics g) {
startup = 0;
while (counter > 0) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
}
x += xVelocity;
y += yVelocity;
g.setColor(Color.blue);
g.fillRect(currx, curry, 300, 25);
g.setColor(Color.red);
g.fillOval(x, y, 30, 30);
for (int j = 0; j < 20000000; j++);
g.setColor(Color.black);
g.fillOval(x, y, 30, 30);
//Bounce the ball off the wall or paddle
if (x >= 1400 || x <= 0) {
xVelocity = -xVelocity;
}
if (y >= 800 || y <= 0) {
yVelocity = -yVelocity;
}
if (((y == 675)) && ((currx <= x) && (currx + 300) >= x)) {
yVelocity = -yVelocity;
y = y - 10;
repaint();
}
}
}
public void paint(Graphics g) {
if (startup == 0) {
g.setColor(Color.white);
g.drawString("Welcome To PONG", 0, 100);
g.drawString("Created by Caden Anton", 0, 200);
g.drawString("copyright May 3rd, 2019 ©", 0, 300);
g.drawString("Press any key to continue", 0, 400);
}
if (startup == 1) {
g.setColor(Color.white);
g.drawString("RULES:", 0, 100);
g.drawString("Press the arrwow keys to move the paddle", 0, 200);
g.drawString("Your objective is to keep the ball from touching the ground", 0, 300);
g.drawString("Once the ball hits the ground you lose the game", 0, 400);
}
if (startup >= 2) {
//Input Run thread start here.
}
}
}

Detecting if a 2D Graphics fill Rect is in another fillRect(eclipse)

private JPanel contentPane;
private KeyListener myKeyListener;
JLabel lblUp;
JLabel lblMiddle;
JLabel lblDown;
JButton btnStart;
JLabel lblScore;
int lblu = 0;
int x = 0;
int y = 50;
int u = 1;
int w = 1;
int rxx = 0;
int ryy = 0;
int s = 0;
Timer timer;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game_1 frame = new Game_1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Game_1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblScore = new JLabel("0");
lblScore.setHorizontalAlignment(SwingConstants.CENTER);
lblScore.setForeground(Color.GREEN);
lblScore.setBounds(388, 0, 46, 14);
contentPane.add(lblScore);
addKeyListener(this);
}
public void keyPressed(KeyEvent arg0) {
Graphics pen = this.contentPane.getGraphics();
int maxh = contentPane.getHeight();
int maxw = contentPane.getWidth();
if(y < 0){
y = maxh -50;
}
if(y > maxh-45){
y = 0;
}
if (arg0.getKeyCode() == KeyEvent.VK_UP) {
if(u ==0){
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
y = y - 10;
pen.setColor(Color.GREEN);
pen.fillRect(x, y, 50, 50);
pen.setColor(Color.BLACK);
pen.fillRect(x - 50, y, 50, 50);
x = x + 1;
if (x >= maxw) {
pen.fillRect(x - 30, y, 50, 50);
x = 0;
}
}
} else if (arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
if(u ==1){
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
Timer timer = new Timer(100, this);
timer.start();
u = 0;
}else if(u ==0){
x = x +10;
}
} else if (arg0.getKeyCode() == KeyEvent.VK_DOWN) {
if(u ==0){
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
pen.setColor(Color.BLACK);
y = y+ 10;
if (x >= maxw) {
pen.fillRect(x - 30, y, 50, 50);
x = 0;
}
}
} else if (arg0.getKeyCode() == KeyEvent.VK_LEFT) {
if(u ==0){
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
pen.setColor(Color.BLACK);
x = x- 10;
if (x < 0) {
pen.fillRect(x - 30, y, 50, 50);
x = maxw;
}
}
}
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
public void run() {
}
#Override
public void actionPerformed(ActionEvent arg0) {
Graphics pen = this.contentPane.getGraphics();
int maxh = contentPane.getHeight();
int maxw = contentPane.getWidth();
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
pen.setColor(Color.GREEN);
pen.fillRect(x, y, 50, 50);
pen.setColor(Color.BLACK);
pen.fillRect(x - 50, y, 50, 50);
x = x + 1;
if (x >= maxw) {
pen.fillRect(x - 30, y, 50, 50);
x = 0;
}
if(w ==1){
Random r = new Random();
int ry = r.nextInt(maxh - 0) + 100;
int rx = r.nextInt(maxw - 0) + 100;
rxx = rx;
ryy = ry;
pen.setColor(Color.RED);
pen.fillRect(rx, ry, 10, 10);
w = 0;
}
pen.setColor(Color.RED);
pen.fillRect(rxx, ryy, 10, 10);
if(x-50 <= rxx && x > rxx && y > ryy && y-50 <= ryy){
s ++;
System.out.println("PUNKT");
pen.setColor(Color.BLACK);
pen.fillRect(rxx, ryy, 10, 10);
w = 1;
}
}
}
here is the Problem: it only detects that they touch in the left top >corner(the wrong code is at the end, the last if)
you can start the game by pressing the Right arrow Button on you're Keyboard.Moving upwards: up Key on you're Keyboard.Moving downwards:down Key on your're Keyboard.The right Button also lets you move to the right, the left Button to the left.Picture of the Game
I want, that the Rect detects that it touches the other in every part
of it, not only in the left top corner
Let's assume you've got first rect with: x1, y1, width1, height1 and second rect with x2, y2, width2, height2. The first rect touched the second in every part of it (so the second one is contained in the first one) when x1 <= x2 && x2+width2 <= x1+width2 && y1 <= y2 && y2+height <= y1+height
so
if (x1 <= x2 && x2+width2 <= x1+width2 && y1 <= y2 && y2+height <= y1+height) {
// the second rect is contained in the first rect
}
So I finally fixed it. For those who are interested, here is the fixed part of the code:
if (x+d >= x2 && x <= x2 && y+d >=y2 && y <= y2) {
s++;
d = d + s*10;
System.out.println("PUNKT");
pen.setColor(Color.BLACK);
pen.fillRect(x2, y2, 10, 10);
w = 1;
if (s == 10) {
JOptionPane.showMessageDialog(frame, "Achievement get: " + s + "Punkte!");
}

Constant Input Received in Processing Despite Lack of Input - Java

I have been working in Java for the past week, and I am taking an online/offline course where we work with Processing. This code is supposed to create a rocket that would fly around the screen based on the input of the user. However, it always flies backwards, and the only way to prevent it from flying backwards is to press forward. Even then, it only stands still. Through some testing, we have found out that the movingBackward variable is constantly triggered, but there seems to be no reason for it. My teacher and I are stumped, and any and all suggestions/advice are greatly appreciated.
package processing2;
import processing.core.PApplet;
public class Processing2 extends PApplet
{
private static final long serialVersionUID = 1L;
public float rotationAmount = 180;
public boolean rotateLeft = false;
public boolean rotateRight = false;
public float speed = 10;
public float x = 400;
public float y = 350;
public boolean moveForward = false;
public boolean movingBackward = false;
public boolean moving = false;
public void setup()
{
size(800, 700);
}
public void draw()
{
background(255, 255, 255);
move();
changeRotation();
translate(x, y);
rotate(rotationAmount);
drawRocketShip();
}
public int rocketX = 0;
public int rocketY = 0;
public void drawRocketShip()
{
stroke(0, 149, 185);
fill(0, 149, 185);
rect(rocketX, rocketY, 75, 50);
triangle(rocketX + 75, rocketY + 1, 100, rocketY + 25, rocketX + 75, rocketY + 49);
fill(255, 255, 255);
ellipse(rocketX + 60, rocketY + 25, 30, 15);
stroke(0, 149, 185);
strokeWeight(3);
fill(255, 255, 255);
triangle(rocketX + 25, rocketY, rocketX - 15, rocketY - 25, rocketX, rocketY);
triangle(rocketX + 25, rocketY + 50, rocketX - 15, rocketY + 75, rocketX, rocketY + 50);
if(moving)
{
fill(255, 0, 0);
noStroke();
triangle(rocketX - 10, rocketY + 10, rocketX - 30, rocketY + 25, rocketX - 10, rocketY + 40);
}
}
public void keyPressed()
{
if(key == 'a')
{
rotateLeft = true;
}
if(key == 'd')
{
rotateRight = true;
}
if(key == 'w')
{
moveForward = true;
moving = true;
}
if (key == 's');
{
movingBackward = true;
moving = true;
}
}
public void keyReleased()
{
if(key =='a')
{
rotateLeft = false;
}
if(key == 'd')
{
rotateRight = false;
}
if(key == 'w')
{
moveForward = false;
moving = false;
}
if (key == 's');
{
movingBackward = false;
moving = false;
}
}
public void move()
{
if(moveForward)
{
x += speed * cos(rotationAmount);
y += speed * sin(rotationAmount);
}
if(movingBackward);
{
x += -speed * cos(rotationAmount);
y += -speed * sin(rotationAmount);
}
}
public void changeRotation()
{
if(rotateLeft)
{
rotationAmount -= .08;
if(rotationAmount < 0)
{
rotationAmount = 2 * PI;
}
}
if(rotateRight)
{
rotationAmount += .08;
if(rotationAmount > 2* PI)
{
rotationAmount = 0;
}
}
}
}
if(movingBackward);
you are effectively telling java to do nothing if movingBackward is true. As a result, it will treat the curly braces after as a simple block that has no particular syntactic effect and is always processed. Remove the semicolon and it should work.
Same issue at both instances of
if (key == 's');
I personally prefer placing opening braces on the same line as the if (or try, catch, else, etc...), which makes mistakes like these easier to spot. That's preference though.

Java: Displaying Positions correctly in Tortoise vs. Hare Applet

I'm currently working on a Project that shows a tortoise vs. hare race in real-time as an Applet. A random number is chosen, and the animals either move forward, backward, or not at all based on that number. My problem is getting the animals to be seen in real-time. It currently displays the images at their starting positions, and says who wins. Any pointers on how to get this done would be great.
my code:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
import java.awt.Font;
public class Project2 extends Applet
{
Image tortoise, hare;
Image scaledTortoise, scaledHare;
final int tortoiseYPos = 50, hareYPos = 400, SQUARE = 20, END = 1200;
int tortoiseXPos = 180, hareXPos = 180;
public void init()
{
tortoise = getImage(getDocumentBase(), "tortoise.gif");
hare = getImage(getDocumentBase(), "hare.gif");
scaledTortoise = tortoise.getScaledInstance(20, 50, Image.SCALE_SMOOTH);
scaledHare = hare.getScaledInstance(20, 50, Image.SCALE_SMOOTH);
}
public void paint(Graphics field)
{
drawField(field);
drawMoves(field);
field.setFont(new Font("Times New Roman", Font.ITALIC, 72));
//Display winner when they get to the finish line
if(tortoiseXPos >= END)
{
field.drawString("Tortoise Wins!!", 650, 240);
}
else if(hareXPos >= END)
{
field.drawString("Hare Wins!!", 650, 240);
}
}
public void drawField(Graphics field)
{
setBackground(Color.green);
Font f = new Font("Times New Roman", Font.BOLD, 48);
field.setFont(f);
field.drawString("Tortoise", 0, 75);
field.drawString("Hare", 0, 425);
//fill alternating black and white rectangles
field.setColor(Color.black);
int x = 180;
for(int i = 0; i < 50; i++)
{
field.fillRect(x, 50, SQUARE, 50);
field.fillRect(x, 400, SQUARE, 50);
x += (SQUARE);
}
field.drawImage(scaledTortoise, 180, tortoiseYPos, this);
field.drawImage(scaledHare, 180, hareYPos, this);
}
public void drawMoves(Graphics s)
{
while(tortoiseXPos < END && hareXPos < END)
{
int move = (int)(Math.random() * 10);
tortoiseMoves(move); hareMoves(move);
s.drawImage(scaledTortoise, tortoiseXPos, tortoiseYPos, this);
s.drawImage(scaledHare, hareXPos, hareYPos, this);
delay(); delay(); delay();
}
}
public void tortoiseMoves(int move)
{ //Moves for Tortoise, 180 is start, 1200 is finish
if(move <= 5)
{
tortoiseXPos += (3 * SQUARE);
}
else if(move <= 8)
{
tortoiseXPos += SQUARE;
}
else if(move <= 10)
{
tortoiseXPos -= (6 * SQUARE);
}
if(tortoiseXPos < 180)
{
tortoiseXPos = 180;
}
if(tortoiseXPos > END)
{
tortoiseXPos = END;
}
}
public void hareMoves(int move)
{ //Moves for Hare, 180 is start, 1200 is finish
if(move <= 2)
{
hareXPos += (9 * SQUARE);
}
else if(move <= 5)
{
hareXPos += (SQUARE);
}
else if(move <= 6)
{
hareXPos -= (12 * SQUARE);
}
else if(move <= 8)
{
hareXPos -= (2 * SQUARE);
}
else if(move <= 10)
{
hareXPos = hareXPos;
}
if(hareXPos < 180)
{
hareXPos = 180;
}
if(hareXPos > END)
{
hareXPos = END;
}
}
public void delay()
{
for(int i = 0; i <= 90000000; i++)
{
}
}
}
I should note that I am not familiar with and should not be using java swing, as I am only supposed to be using awt.
The problem is with your delay function. Entering a loop keeps the applet running your code and it does not get a chance to render the display between moves. If you allow the Thread that your applet is running in to sleep, then that gives it a chance to display as it runs.
public void delay()
{
try {
Thread.sleep(100);
} catch (Exception e) {}
}

My Java Tortoise and Hare Applet will not run

I am trying to create/simulate a tortoise vs. hare race. A random number generator is used to make the competitors move....the possible moves being :a distance of 3 squares right, 1 square right, 6 squares left, 9 squares right, 1 square right, 12 squares left, 2 squares left, fall asleep. The course is plotted with 50 squares of positions with each player having their own respective lanes and starting at position 1. My problems is that the applet compiles, but does not run when I try to open the html file in the browser. Am I on the right track? How do I get this to run....and when it runs, properly?
import java.awt.*;
import java.applet.*;
public class Project2 extends Applet
{
Image tortoise, hare;
int tortX = 250, hareX = 250;
final int tortY = 100, hareY = 300, WIDTH = 15, HEIGHT = 50;
int turn; String turnNum;
int move; String tMove, hMove;
public void init()
{
tortoise = getImage( getDocumentBase(), "images/tortoise.gif" );
hare = getImage( getDocumentBase(), "images/hare.gif" );
move = 0; turn = 0;
}
public void control()
{
while (( tortX < 985 ) || ( hareX < 985 ))
{
move = (int)(10 * Math.random());
switch (move)
{
case 1:
case 2:
tortX += (3 * WIDTH);
hareX += (9 * WIDTH);
tMove = "Fast Plod"; hMove = "Big Hop";
break;
case 3:
case 4:
case 5:
tortX += (3 * WIDTH);
hareX += WIDTH;
tMove = "Fast Plod"; hMove = "Small Hop";
break;
case 6:
tortX += WIDTH;
if (hareX == 250) {} // Agit Nihil
else if (hareX <= (250 + (11 * WIDTH)))
hareX = 250;
else
hareX -= (12 * WIDTH);
tMove = "Slow Plod"; hMove = "Big Slip";
break;
case 7:
case 8:
tortX += (1 * WIDTH);
if (hareX == 250) {} // Agit Nihil
else if (hareX <= (250 + (WIDTH)))
hareX = 250;
else
hareX -= (2 * WIDTH);
tMove = "Slow Plod"; hMove = "Small Slip";
break;
case 9:
case 10:
if (tortX == 250) {} // Agit nihil
else if (tortX <= (250 + (5 * WIDTH)))
tortX = 250;
else
tortX -= (6 * WIDTH);
tMove = "Slip"; hMove = "Fall Asleep.";
break;
// Cuniculus dormit, agit nihil .
}
turn++; turnNum = (turn + "");
repaint();
for (int i = 1; i <= 10; i++)
{
delay();
}
}
tortX = 985; hareX = 985;
repaint();
}
public void paint( Graphics screen )
{
drawRace(screen);
if (tortX >= 985)
{
screen.setFont(new Font("Times New Roman", Font.ITALIC, 48));
screen.drawString("Tortoise Wins", 650, 240);
clearCurrent(screen);
fillNext(screen);
}
else if (hareX >= 985)
{
screen.setFont(new Font("Times New Roman", Font.ITALIC, 48));
screen.drawString("Tortoise Wins", 650, 240);
clearCurrent(screen);
fillNext(screen);
}
else
{
screen.drawString(("Turn " + turnNum), 621, 55);
screen.setFont(new Font("Times New Roman", Font.ITALIC, 12));
screen.drawString(tMove, 59, 65); screen.drawString(hMove, 66, 255);
clearCurrent(screen);
fillNext(screen);
}
stop();
}
public void clearCurrent( Graphics s )
{
s.clearRect(tortX+1, tortY+1, WIDTH-1, HEIGHT-1);
s.clearRect(hareX+1, hareY+1, WIDTH-1, HEIGHT-1);
}
public void fillNext( Graphics s )
{
s.fillRect(tortX+1, tortY+1, WIDTH-1, HEIGHT-1);
s.fillRect(hareX+1, hareY+1, WIDTH-1, HEIGHT-1);
}
public void drawRace( Graphics s )
{
// Initium
s.drawRect(250, 100, 750, 50);
s.drawRect(250, 300, 750, 50);
int lineX = 265, lineYi = 100, lineYf = 150;
for (int i = 1; i <= 98; i++)
{
if (lineX == 1000)
{
lineX = 265; lineYi = 300; lineYf = 350;
}
s.drawLine(lineX, lineYi, lineX, lineYf);
lineX += 15;
}
s.fillRect(tortX+1, tortY+1, WIDTH-1, HEIGHT-1);
s.fillRect(hareX+1, hareY+1, WIDTH-1, HEIGHT-1);
s.drawImage(tortoise, 59, 80, this);
s.drawImage(hare, 66, 271, this);
s.setFont(new Font("Times New Roman", Font.BOLD, 24));
s.drawString("Race", 250, 55);
}
public void delay()
{
for (int i = 0; i < 90000000; i++)
{
}
}
public void stop()
{
}
}

Categories