My Java Tortoise and Hare Applet will not run - java

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()
{
}
}

Related

How to do random generation of barriers for car collision game

How do I create a random car barrier for my game? I have this top-down car game that I need to make. This game aims to make the car move up and down (on the y-axis) to avoid the barriers, while the barriers are moving toward the car (on the x-axis). Is it possible to create a random generation of the barriers when they spawn, making the game enjoyable? Right now, I only have a set of barriers that last for 12 seconds before I get easily through them. Can I also keep the spacing of the barriers the same? So the car can fit.
code
color green = color(0,195,0);
color red = color(195,0,0);
color grey = color(100,100,100);
color yellow = color(200,200,0);
color white = color(255,255,255);
float roadx = 70, road1y = 130;
float road2y = 230, road3y = 330;
float carY = road2y;
float carX = roadx;
float carUPspeed = 1;
float laneX = 700;
float lanes;
void lane1(float x, float y){
fill(white);
rect(x + 100, y,30,100);
rect(x + 250, y + 100,30,100);
rect(x + 250, y + 200, 30, 100);
rect(x + 400, y + 100, 30, 100);
rect(x + 550, y + 100, 30, 100);
rect(x + 550, y, 30, 100);
rect(x + 700, y + 100, 30, 100);
rect(x + 700, y + 200, 30, 100);
}
void background(){
background(green);
}
void car(){
fill(red);
rect(carX, carY, 60, 40);
}
void setup(){
surface.setTitle("dodge");
size(900, 500);
}
void draw(){
background();
noStroke();
fill(grey);
rect(roadx - 400, road1y - 30, 1500, 100);
stroke(yellow);
strokeWeight(5);
rect(roadx - 400, road2y - 30, 1500, 100);
noStroke();
rect(roadx - 400, road3y - 27, 1500, 100);
car();
lane1(laneX, 100);
laneX -= 1;
lanes = 1;
}
void keyPressed(KeyEvent event){
if (key == 'w'){
if(carY != 130){
carY = carY - 100;
}
}
if (key == 's'){
if(carY != 330){
carY = carY + 100;
}
}
}
I've modified your lane rendering and added dynamic creation of barriers. Every 150 pixels moved, the barriers are updated (leftmost barriers are removed, new ones are added at the rightmost position and the cycle starts over).
The barriers are stored as an integer between 0 and 6, as there are 7 possibilities for the barrier positions:
int | 0 1 2 3 4 5 6
------+--------------------
lane0 | # # #
lane1 | # # #
lane2 | # # #
Hope this helps.
Modified code:
import java.util.*;
private static final int SCREEN_X = 900;
private static final int SCREEN_Y = 500;
private static final int LANE_HEIGHT = 100;
private static final int BARRIER_DISTANCE = 150;
private static final int BARRIER_HEIGHT = 100;
private static final int BARRIER_WIDTH = 30;
color green = color(0,195,0);
color red = color(195,0,0);
color grey = color(100,100,100);
color yellow = color(200,200,0);
color white = color(255,255,255);
float roadx = 70, road1y = 130;
float road2y = 230, road3y = 330;
float carY = road2y;
float carX = roadx;
float carUPspeed = 1;
float laneX = 50;
float lanes;
List<Integer> barriers;
void lane1(float x){
fill(white);
for (Integer b : barriers)
{
switch(b)
{
case 0: // ___
break;
case 1: // X__
rect(x, LANE_HEIGHT, BARRIER_WIDTH, BARRIER_HEIGHT);
break;
case 2: // _X_
rect(x, LANE_HEIGHT * 2, BARRIER_WIDTH, BARRIER_HEIGHT);
break;
case 3: // __X
rect(x, LANE_HEIGHT * 3, BARRIER_WIDTH, BARRIER_HEIGHT);
break;
case 4: // _XX
rect(x, LANE_HEIGHT * 2, BARRIER_WIDTH, BARRIER_HEIGHT);
rect(x, LANE_HEIGHT * 3, BARRIER_WIDTH, BARRIER_HEIGHT);
break;
case 5: // XX_
rect(x, LANE_HEIGHT * 1, BARRIER_WIDTH, BARRIER_HEIGHT);
rect(x, LANE_HEIGHT * 2, BARRIER_WIDTH, BARRIER_HEIGHT);
break;
case 6: // X_X
rect(x, LANE_HEIGHT * 1, BARRIER_WIDTH, BARRIER_HEIGHT);
rect(x, LANE_HEIGHT * 3, BARRIER_WIDTH, BARRIER_HEIGHT);
break;
}
x += BARRIER_DISTANCE;
}
}
void background(){
background(green);
}
void car(){
fill(red);
rect(carX, carY, 60, 40);
}
void setup(){
surface.setTitle("dodge");
size(900, 500);
// Initially generate 7 barriers (one more than the screen can fit)
barriers = new ArrayList<Integer>();
for (int i = 0; i <= (SCREEN_X / BARRIER_DISTANCE); i++)
{
barriers.add(int(random(0, 6)));
}
// Set the first to barriers to 'no barrier' to the player initially has some time
barriers.set(0, 0);
barriers.set(1, 0);
}
void draw(){
background();
noStroke();
fill(grey);
rect(roadx - 400, road1y - 30, 1500, LANE_HEIGHT);
stroke(yellow);
strokeWeight(5);
rect(roadx - 400, road2y - 30, 1500, LANE_HEIGHT);
noStroke();
rect(roadx - 400, road3y - 27, 1500, LANE_HEIGHT);
car();
lane1(laneX);
laneX -= 1;
// laneX cycles from 50 to -100 (because of draw position)
// So, every 150 pixels moved
if (laneX == -100)
{
// Reset laneX
laneX = 50;
// Remove leftmost barrier
barriers.remove(0);
// Add new barriers, incoming from the right
barriers.add(int(random(0, 6)));
}
lanes = 1;
}
void keyPressed(KeyEvent event){
if (key == 'w'){
if(carY != 130){
carY = carY - 100;
}
}
if (key == 's'){
if(carY != 330){
carY = carY + 100;
}
}
}

When clearing background, rect moves

So i've used a rect to divide the screen for two different background colours. The code im writing is for a minigame and its supposed to move a bubble up the screen, but when I click my mouse the rect I used to divide the screen moves as well. I probably did a very poor job at describing this so heres the code and you'll see what I mean.
PFont font1;
int dice = 100;
int num = 0;
float circlex = 300;
float circley = 830;
float xmove = 0;
float ymove = 0;
void setup ()
{
noLoop();
frameRate(10);
size (600, 900);
//background (#29C4FF);
//fill (#C4FFEC);
//strokeWeight(3);
//line(1, 225, 599, 225);
//noStroke ();
//rect (0, 0, 599, 225);
font1 = loadFont ("ArialMT-18.vlw");
ellipseMode(CENTER);
}
void draw ()
{
//OCEAN
background (#29C4FF);
fill (#C4FFEC);
strokeWeight(3);
line(1, 225, 599, 225);
noStroke ();
rect (0, 0, 599, 225);
textFont(font1, 18);
fill(0);
text("Click on the dice to help free Aang from the iceberg.", 100, 50);
//BUBBLE
fill(0, 0, 200);
ellipse(circlex, circley, 125, 125);
noStroke();
fill (210);
ellipse(circlex, circley, 118, 118);
//AANG
//BODY
fill(#FF8E03);
noStroke ();
triangle(255, 830, 345, 830, 300, 890);
//HEAD
fill(#027A9D);
ellipse(275, 820, 10, 15);
ellipse(325, 820, 10, 15);
ellipse(300, 820, 50, 55);
rectMode(CENTER);
fill(255);
rect(300, 800, 10, 15);
triangle(290, 805, 310, 805, 300, 820);
rect(288, 815, 8, 3);
rect(312, 815, 8, 3);
//DICE
fill(#027A9D);
rect(80, 130, 100, 100, 12);
fill(#8EC1EA);
rect(80, 130, 90, 90, 8);
//NUMBERS(DOTS)
fill(150, 0, 0);
int num = int(random(1, 7));
if (num == 1 || num == 3 || num == 5)
ellipse(80, 130, dice/5, dice/5);
if (num == 2 || num == 3 || num == 4 || num == 5 || num == 6) {
ellipse(80 - dice/4, 130 - dice/4, dice/5, dice/5);
ellipse(80 + dice/4, 130 + dice/4, dice/5, dice/5);
}
if (num == 4 || num == 5 || num == 6) {
ellipse(80 - dice/4, 130 + dice/4, dice/5, dice/5);
ellipse(80 + dice/4, 130 - dice/4, dice/5, dice/5);
}
if (num == 6) {
ellipse(80, 130 - dice/4, dice/5, dice/5);
ellipse(80, 130 + dice/4, dice/5, dice/5);
}
if (num == 1 || num == 2) {
circlex = circlex + xmove;
xmove = +20;
}
if (num == 3 || num == 4) {
circlex = circlex + xmove;
xmove = -20;
}
if (num == 5) {
circley = circley + ymove;
ymove = -25;
}
if (num == 6) {
circley = circley + ymove;
ymove = -50;
}
//ROLL
if (mousePressed && mouseButton == LEFT)
noLoop();
}
void mousePressed() {
loop();
}
rectMode(CENTER);
This line modifies how your rectangles are drawn. On the first run its still set to default (CORNER), but afterwards the rect get drawn from the center and thus moves to the top left.
Reference:
https://processing.org/reference/rectMode_.html
Solution 1:
Add rectMode(CORNER) before drawing the background.
Solution 2:
Move rectMode(CENTER) to the setup and draw all shapes a bit different.
In general I suggest you put the background into a function for a better readability and flexibility.
void setup () {
noLoop();
frameRate(10);
size (600, 900);
ellipseMode(CENTER);
rectMode(CENTER); // added rectMode here.
}
void draw () {
drawStage();
//BUBBLE
// ...
}
// Function to draw the background
void drawStage() {
//OCEAN
background (#29C4FF);
fill (#C4FFEC);
noStroke();
rect(width/2, 125, width, 250); // rect drawn with "width" scales if you choose to adjust your sketch size.
fill(0);
text("Click on the dice to help free Aang from the iceberg.", 100, 50);
}

"The nested type cannot hide an enclosing type" class - Java Processing

I'm getting this error: The nested type cannot hide an enclosing type. I have looked it up, and other people seem to be declaring their class twice, which I am not.
What's weird is if I copy and paste the code into a new processing document, it works with no error. But as I'm converting it to js i need it to work with no errors after saving and opening again.
MotorBike Bike1, Bike2, Bike3, Bike4, Bike5, Bike6, Bike7, Bike8, Bike9;
int Score_Bike1 = 0;
int Score_Bike2 = 0;
int Score_Bike3 = 0;
int Score_Bike4 = 0;
int Score_Bike5 = 0;
int Score_Bike6 = 0;
int Score_Bike7 = 0;
int Score_Bike8 = 0;
int Score_Bike9 = 0;
String Score_Spacing = " ";
int GameState = 0;
class MotorBike {
float Pos_X;
int Pos_Y;
float Speed;
int Size = 30;
float WheelSize = Size / 3;
color Color;
MotorBike(int Declare_X, int Declare_Y, int Declare_Speed, color Declare_Color)
{
this.Pos_X = Declare_X;
this.Pos_Y = Declare_Y;
Speed = Declare_Speed;
Color = Declare_Color;
}
void move()
{
if (GameState == 1) {
Speed = (random(0, 50) / 10);
Pos_X = Pos_X + Speed;
}
}
void render()
{
fill(Color);
triangle(Pos_X, Pos_Y, Pos_X + Size, Pos_Y, Pos_X + Size / 2, Pos_Y -Size / 2);
fill(255);
strokeWeight(1.5);
ellipse(Pos_X, Pos_Y, WheelSize, WheelSize);
ellipse(Pos_X + Size, Pos_Y, WheelSize, WheelSize);
}
}
void setup()
{
size(700, 600);
background(200);
SpawnBikes();
}
void draw()
{
background(200);
strokeWeight(3);
line(50, 10, 50, 590);
line(650, 10, 650, 590);
strokeWeight(1);
MoveBikes();
DetectWinner();
DisplayScore();
}
void MoveBikes()
{
Bike1.render();
Bike1.move();
Bike2.render();
Bike2.move();
Bike3.render();
Bike3.move();
Bike4.render();
Bike4.move();
Bike5.render();
Bike5.move();
Bike6.render();
Bike6.move();
Bike7.render();
Bike7.move();
Bike8.render();
Bike8.move();
Bike9.render();
Bike9.move();
}
void DetectWinner()
{
textSize(15);
fill(0);
if (Bike1.Pos_X >= 620) {
noLoop();
text("Bike 1 Wins", 310, 10, 350, 50);
Score_Bike1 += 1;
GameState = 2;
}
if (Bike2.Pos_X >= 620) {
noLoop();
text("Bike 2 Wins", 310, 10, 350, 50);
Score_Bike2 += 1;
GameState = 2;
}
if (Bike3.Pos_X >= 620) {
noLoop();
text("Bike 3 Wins", 310, 10, 350, 50);
Score_Bike3 += 1;
GameState = 2;
}
if (Bike4.Pos_X >= 620) {
noLoop();
text("Bike 4 Wins", 310, 10, 350, 50);
Score_Bike4 += 1;
GameState = 2;
}
if (Bike5.Pos_X >= 620) {
noLoop();
text("Bike 5 Wins", 310, 10, 350, 50);
Score_Bike5 += 1;
GameState = 2;
}
if (Bike6.Pos_X >= 620) {
noLoop();
text("Bike 6 Wins", 310, 10, 350, 50);
Score_Bike6 += 1;
GameState = 2;
}
if (Bike7.Pos_X >= 620) {
noLoop();
text("Bike 7 Wins", 310, 10, 350, 50);
Score_Bike7 += 1;
GameState = 2;
}
if (Bike8.Pos_X >= 620) {
noLoop();
text("Bike 8 Wins", 310, 10, 350, 50);
Score_Bike8 += 1;
GameState = 2;
}
if (Bike9.Pos_X >= 620) {
noLoop();
text("Bike 9 Wins", 310, 10, 350, 50);
Score_Bike9 += 1;
GameState = 2;
}
}
void DisplayScore()
{
textSize(15);
fill(0);
text("Bike 1: " + Score_Bike1 + Score_Spacing + "Bike 2: " + Score_Bike2 + Score_Spacing + "Bike 3: " +
Score_Bike3 + Score_Spacing + "Bike 4: " + Score_Bike4 + Score_Spacing + "Bike 5: " + Score_Bike5 + Score_Spacing +
"Bike 6: " + Score_Bike6 + Score_Spacing + "Bike 7: " + Score_Bike7 + Score_Spacing + "Bike 8: " + Score_Bike8 +
Score_Spacing + "Bike 9: " + Score_Bike9, 65, 530, 635, 700);
}
void keyPressed()
{
if (keyPressed) {
if (key == ' ')
{
if (GameState == 0) {
GameState = 1;
}
if (GameState == 2) {
loop();
background(200);
SpawnBikes();
GameState = 0;
}
}
}
}
void SpawnBikes()
{
Bike1 = new MotorBike(50, 100, 2, color(255, 0, 0));
Bike2 = new MotorBike(50, 150, 2, color(0, 255, 0));
Bike3 = new MotorBike(50, 200, 2, color(0, 0, 255));
Bike4 = new MotorBike(50, 250, 2, color(255, 255, 0));
Bike5 = new MotorBike(50, 300, 2, color(0, 255, 255));
Bike6 = new MotorBike(50, 350, 2, color(255, 0, 255));
Bike7 = new MotorBike(50, 400, 2, color(100, 255, 0));
Bike8 = new MotorBike(50, 450, 2, color(0, 100, 255));
Bike9 = new MotorBike(50, 500, 2, color(255, 0, 100));
}
Your problem is caused by the fact that you're naming your sketch the same thing as a class you're using inside your sketch. Your sketch can't be named MotorBike if you have a MotorBike class inside that sketch.
Either rename your sketch, or rename your class.
Behind the scenes, this is because Processing exports your sketch as a Java class, and any classes in your sketch become inner classes of that Java class. So your sketch becomes something like this:
class MotorBike{
void draw(){
//whatever
}
class MotorBike{
int x;
//whatever
}
}
This is illegal Java, which is what's causing your error. You can't have an inner class with the same name as a parent class. In other words, a nested type cannot hide an enclosing type.
This is also why it works okay when you copy it into a new sketch- Processing gives your sketch a random default name, so you don't have this name collision until you save your sketch as something else.

Android Game - set time limit to 30 seconds

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.

Hare and tortoise Race Applet , how can I make my code work properly?

I've been working on my project and it's a little hard to know what I can fix in this so I could make it work , I'm a beginner just to let you know..
Here's the error(s) message:
Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException: String is null
at sun.java2d.SunGraphics2D.drawString(SunGraphics2D.java:2817)
at project2.project2.paint(project2.java:101)
at sun.awt.RepaintArea.paintComponent(RepaintArea.java:264)
at sun.awt.RepaintArea.paint(RepaintArea.java:240)
at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:347)
at java.awt.Component.dispatchEventImpl(Component.java:4937)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Here's my code:
package project2;
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()
{
}
}
It looks like tMove or hMove (or both both) is null. It sesems like the switch statement in control() can leave these unassigned in some cases. Either ensure that tMove and hMove are definitely assigned before the screen is drawn or (perhaps better, because there's no guarantee that control() will be called before your applet is painted) replace this code:
screen.drawString(tMove, 59, 65);
screen.drawString(hMove, 66, 255);
with this:
if (tMove != null) {
screen.drawString(tMove, 59, 65);
}
if (hMove != null) {
screen.drawString(hMove, 66, 255);
}

Categories