Applet not repeating loop - java

The Purpose:
I have an assignment that involves a race between a tortoise and a hare. Basically, I have two .gif files, one of a tortoise and one of a hare, that are to be displayed in an applet and race each other by advancing along the x axis. In the process, I must use a random number generator to generate different "moves" in which the animal (image file) moves forward or backwards a certain number of positions. This loop must be repeated until one of the animals reach the 50th position. There also must be a time delay of some sort in between each move that the two animals make.
The Code:
import java.util.Random;
import java.awt.Graphics;
import java.applet.Applet;
import java.awt.Image;
import java.awt.Color;
public class ProjectTwo extends Applet
{
Image tortoise, hare;
Random generator = new Random();
int[] positions = new int [50];
int[] randoms = new int[50];
public int t = 0;
public int h = 0;
public int s = 0;
public void init()
{
for (int i = 0; i < positions.length; i++)
{
positions[i] = ((i * 145) + 10);
}
for (int x = 0; x < randoms.length; x++)
{
randoms[x] = generator.nextInt(6) + 1;
}
tortoise = getImage( getDocumentBase(), "images/tortoise.gif" );
hare = getImage( getDocumentBase(), "images/hare.gif" );
}
public void delay()
{
for(int g = 0; g <= 90000000; g++) ;
}
public void paint (Graphics g)
{
g.drawImage (tortoise, positions[0], 10, this);
g.drawImage (hare, positions[0], 137, this);
delay();delay();delay();
do
{
switch (randoms[s])
{
case 1:
case 2:
t += 3;
h += 9;
if (t >= 50)
{
g.drawImage (tortoise, positions[50], 10, this);
}
else
{
g.drawImage (tortoise, positions[t], 10, this);
}
if (h >= 50)
{
g.drawImage (hare, positions[50], 137, this);
}
else
{
g.drawImage (hare, positions[h], 137, this);
}
s++;
break;
case 3:
case 4:
case 5:
t += 3;
h += 1;
if (t >= 50)
{
g.drawImage (tortoise, positions[50], 10, this);
}
else
{
g.drawImage (tortoise, positions[t], 10, this);
}
if (h >= 50)
{
g.drawImage (hare, positions[50], 137, this);
}
else
{
g.drawImage (hare, positions[h], 137, this);
}
s++;
break;
case 6:
t += 1;
h -= -12;
if (t >= 50)
{
g.drawImage (tortoise, positions[50], 10, this);
}
else
{
g.drawImage (tortoise, positions[t], 10, this);
}
if (h <= 0)
{
g.drawImage (hare, positions[0], 137, this);
t = 0;
}
else
{
g.drawImage (hare, positions[h], 137, this);
}
s++;
break;
case 7:
case 8:
t += 1;
h -= 2;
if (t >= 50)
{
g.drawImage (tortoise, positions[50], 10, this);
}
else
{
g.drawImage (tortoise, positions[t], 10, this);
}
if (h <= 0)
{
g.drawImage (hare, positions[0], 137, this);
t = 0;
}
else
{
g.drawImage (hare, positions[h], 137, this);
}
s++;
break;
case 9:
case 10:
t -= 6;
if (t <= 0)
{
g.drawImage (tortoise, positions[0], 10, this);
t = 0;
}
else
{
g.drawImage (tortoise, positions[t], 10, this);
}
g.drawImage (hare, positions[h], 137, this);
s++;
break;
}
} while (t >= 50 | h >= 50);
}
}
The Expected Result:
The tortoise.gif file appears at (10, 10) and the hare.gif file appears at (10, 137)
There is a short delay until the random number generator rolls a 4 (It doesn't matter to me where/when the numbers are created as long as they are in between 1-10)
The tortoise advances 3 positions (formula for positions is 145x + 10, making the tortoise's new coordinates (445, 10)
The hare advances 1 position, making it's new coordinates (155, 10)
Repeat process until one advances to the 50th position(see additional information for what should happen for every random number)
What Actually Happens
The tortoise and the hare show up in their appropriate places, but do not move.
The Problem
I want the tortoise and the hare to advance their positions according to a timer, but after compiling the code and launching the applet, due to some kind of mistake in my code, they do not.
What I Think Might Be Wrong
I believe the problem might have to do with how I implemented the delay, my using an element in an array as the x value for the images, or conflicting variables in my do-while loop and/or my case statement, although I do not know what is wrong nor what I should fix. However, I now realize that if the program does work, due to my use of randoms.length as a constructor in my for loop near the top, the tortoise and the hare will only change positions 50 times before stopping no matter what. I don't know how to fix this problem either.
Additional Information
Here is a chart on how far the animals should move according to the random number chosen:
1-2 = Tortoise moves +3 positions, Hare moves + 9
3-5 = Tortoise moves +3 positions, Hare moves +1
6 = Tortoise moves +1 position, Hare moves back -12
7-8 = Tortoise moves +1 position, Hare moves back -2
9-10 = Tortoise moves back -6 positions, Hare does not move at all
An animal can move no farther back than the original position (positions[0]). If the number goes below, the animal must stay at that position. This rule also applies for positions greater than 50.
This code compiles fine, but the applet doesn't function as attempted.
I apologize if this code seems very messy, as I am fairly new to coding with Java as well as working with applets.

Seems you should change
while (t >= 50 | h >= 50)
to
while (t <= 50 | h <= 50)
since t and h both start out at 0,and you want to loop while they are lower or equal to 50, not while they are higher or equal to 50.

Related

Processing function does nothing but freezes the program

I'm working on a pathfinding algorithm in processing. If I don't draw a line that crosses the path between the green and the red dot, it works, but if I do, I've got a problem, that if I call a function, the program does absolutely nothing but freezes, and I have no idea why. The pixelss stores what you draw, and there are all kinds of stuff, that don't matter at this problem.
When you paste it to processing, press ctrl+t to auto-format it so you can understand it better, but I'd bet it's a newbie issue.
int[][] pixelss = new int[500][500];
void setup() {
background(255);
size(500, 500);}
int[][] badcoos = new int[500][500];
void golinego() {
stroke(200, 200, 255);
line(30, 30, 470, 470);
int j = 30;
int i = 30;
while (dist(i, j, 470, 470) > 10) {
stroke(0, 0, 180);
circle(i, j, 1);
if (pixelss[i+1][j+1]==0) {
i++;j++;}
if (pixelss[i][j]==1) {
if (pixelss[i][j+1]==1) {
if (pixelss[i+1][j]==0) {
i++;}
} else if (pixelss[i+1][j]==1) {
if (pixelss[i][j+1]==0) {
j++;}
} else {
i-=1;
j-=1;}}}}
void draw() {
stroke(0, 255, 0);
fill(0, 255, 0);
circle(30, 30, 10);
stroke(255, 0, 0);
fill(255, 0, 0);
circle(470, 470, 10);
if (mousePressed == true) {
try {
stroke(0);
fill(0);
circle(mouseX, mouseY, 2);
pixelss[mouseX][mouseY] = 1;
pixelss[mouseX+1][mouseY] = 1;
pixelss[mouseX-1][mouseY] = 1;
pixelss[mouseX][mouseY+1] = 1;
pixelss[mouseX][mouseY-1] = 1;
pixelss[mouseX+1][mouseY+1] = 1;
pixelss[mouseX-1][mouseY+1] = 1;
pixelss[mouseX+1][mouseY-1] = 1;
pixelss[mouseX-1][mouseY-1] = 1;
}catch(ArrayIndexOutOfBoundsException e) {}}}
void keyPressed() {
if (key=='r') {
pixelss = new int[500][500];
badcoos = new int[500][500];
background(255);}
if (key==' ') {
golinego();}
if (key=='d') {
background(0);
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 500; j++) {
if (pixelss[i][j]==1) {
stroke(255);
circle(i, j, 1);}}}}}
The program is getting caught in your while loop.
You can see this if you print out the values of i and j inside the loop. They never meet the condition to escape the loop, so that chunk of code runs repeatedly with no change.
while (dist(i, j, 470, 470) > 10) {
println(i, j);
// etc...
}
This hangs the app because the while loop needs to complete before the the draw function gets called again to update the screen.
It's not clear to me what you're actually doing in the while loop, but that's where you should look. Either alter your logic inside the loop, or change the condition to ensure that the code doesn't get stuck in an infinite loop.
You should at least print something when the ArrayIndexOutOfBoundsException is caught.
It looks like you are working with some kind of gui library, make sure you are doing any processing in separate thread from the gui or the gui will become unresponsive and appear to 'freeze' like you describe.
https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

Processing, replacing text

I currently got this code for a poster I'm trying to make for a study (Gonna put it all, as it might be relevant):
package interactiveposter;
import processing.core.PApplet;
import processing.core.PImage;
public class InteractivePoster extends PApplet {
// Declare variables:
PImage[] imgs = new PImage[12];
int i = 0;
boolean introduction = true;
boolean storyboardtext = true;
boolean features = true;
int picWidth = 300;
int picHeight = 200;
PImage storyboard;
PImage phone;
// Set size of window and load images:
public void setup() {
size(750,900);
smooth();
storyboard = loadImage("C:/Users/Frederik/Desktop/Medialogy AAU/Images/storyboardfixed.png");
storyboard.resize(270, 757);
phone = loadImage("C:/Users/Frederik/Desktop/Medialogy AAU/Images/phone.PNG");
phone.resize(300, 500);
}
// All that should run continuously goes in draw:
public void draw() {
background(255,255,255);
textAlign(CENTER);
textSize(24);
fill(0);
text("Creative Play - Applied Technology",width/2,50);
textSize(16);
fill(120);
text("B-341",width/2,900);
image(storyboard, 50, 100);
image(phone, 385, 140);
int tboxPos = 50;
tboxPos=tboxPos+335;
if(introduction == false) {
features = true;
text("Text 1...Introduction", 490, 230);
}
if(storyboardtext == false) {
text("Text 2...Storyboard", 480, 230);
}
if(features == false) {
text("Text 3...Features", 480, 230);
introduction = true;
}
fill(0,0,0);
rect(tboxPos,700, 300, 100, 7); //FrameRect
fill(102,204,255);
rect(tboxPos, 700, 300, 50, 7); //IntroductionRect
fill(255,255,255);
textSize(20);
text("Introduction", tboxPos+150, 730);
fill(102,204,255);
rect(tboxPos, 750, 150, 50, 7); // StoryboardRect
fill(255,255,255);
textSize(20);
text("Storyboard", tboxPos+75, 780);
fill(102,204,255);
rect(tboxPos+150, 750, 150, 50, 7); //FeaturesRect
fill(255,255,255);
textSize(20);
text("Features", tboxPos+225, 780);
}
// Check if mouse is clicked on one of the images, then change that variable from true to false or opposite
public void mouseClicked() {
if(mouseX > 385 && mouseX < 685 && mouseY > 700 && mouseY < 750)
{
if(introduction == true) introduction = false;
else introduction = true;
}
if(mouseX > 385 && mouseX < 535 && mouseY > 750 && mouseY < 800)
{
if(storyboardtext == true) storyboardtext = false;
else storyboardtext = true;
}
if(mouseX > 535 && mouseX < 685 && mouseY > 750 && mouseY < 800)
{
if(features == true) features = false;
else features = true;
}
}
}
Poster:
So when you push the buttons below the smartphone, relevant text should appear. For now it works individually, I click introduction, but to see one of the others I have to click introduction again to make it dissapear first.
What I need to do is make the text replace the other when another button is clicked.
I tried putting the other texts to true in the if statements, but it only worked for some of them, the others got kind of blocked.
Another thought was doing something in void mouseClicked(), but I'm unsure what.
Help is highly appreciated, thank you =)
Right now, you're only setting one variable for each button. Instead, what you want to do is set all of the variables.
Here is one example:
if(mouseX > 385 && mouseX < 685 && mouseY > 700 && mouseY < 750){
if(introduction == true){
introduction = false;
}
else{
features = false
storyboardtext = false;
introduction = true;
}
}
By the way, you could shorten all of the above:
if(mouseX > 385 && mouseX < 685 && mouseY > 700 && mouseY < 750){
features = false
storyboardtext = false;
introduction = !introduction;
}
You might also consider using an enum instead of 3 separate boolean values.
I recommend using an integer to keep track of states, with more states boolean become harder to manage and it's easier to make mistakes.
Here's a basic example:
final int INTRODUCTION = 0;
final int STORYBOARD = 1;
final int FEATURES = 2;
int state = INTRODUCTION;
void draw(){
switch(state){
case INTRODUCTION:
drawIntroduction();
break;
case STORYBOARD:
drawStoryboard();
break;
case FEATURES:
drawFeatures();
break;
}
}
void drawIntroduction(){
background(0);
fill(255);
text("Introduction",15,15);
}
void drawStoryboard(){
background(255);
fill(0);
text("Storyboard",15,55);
}
void drawFeatures(){
background(192);
fill(64);
text("Features",15,95);
}
void keyReleased(){
state = (state + 1) % 3;//cycle through states to test
}
I recommend using separate functions for drawing each state to keep the code tidier. Press any key to cycle through states.
The above, roughly adapted to your code, would look a bit like this:
package interactiveposter;
import processing.core.PApplet;
import processing.core.PImage;
public class InteractivePoster extends PApplet {
// Declare variables:
PImage[] imgs = new PImage[12];
int i = 0;
int picWidth = 300;
int picHeight = 200;
PImage storyboard;
PImage phone;
final int INTRODUCTION = 0;
final int STORYBOARD = 1;
final int FEATURES = 2;
int state = INTRODUCTION;
// Set size of window and load images:
public void setup() {
size(750,900);
smooth();
storyboard = loadImage("C:/Users/Frederik/Desktop/Medialogy AAU/Images/storyboardfixed.png");
storyboard.resize(270, 757);
phone = loadImage("C:/Users/Frederik/Desktop/Medialogy AAU/Images/phone.PNG");
phone.resize(300, 500);
}
// All that should run continuously goes in draw:
public void draw() {
background(255,255,255);
textAlign(CENTER);
textSize(24);
fill(0);
text("Creative Play - Applied Technology",width/2,50);
textSize(16);
fill(120);
text("B-341",width/2,900);
image(storyboard, 50, 100);
image(phone, 385, 140);
int tboxPos = 50;
tboxPos=tboxPos+335;
if(state == INTRODUCTION) {
text("Text 1...Introduction", 490, 230);
}
if(state == STORYBOARD) {
text("Text 2...Storyboard", 480, 230);
}
if(state == FEATURES) {
text("Text 3...Features", 480, 230);
}
fill(0,0,0);
rect(tboxPos,700, 300, 100, 7); //FrameRect
fill(102,204,255);
rect(tboxPos, 700, 300, 50, 7); //IntroductionRect
fill(255,255,255);
textSize(20);
text("Introduction", tboxPos+150, 730);
fill(102,204,255);
rect(tboxPos, 750, 150, 50, 7); // StoryboardRect
fill(255,255,255);
textSize(20);
text("Storyboard", tboxPos+75, 780);
fill(102,204,255);
rect(tboxPos+150, 750, 150, 50, 7); //FeaturesRect
fill(255,255,255);
textSize(20);
text("Features", tboxPos+225, 780);
}
// Check if mouse is clicked on one of the images, then change that variable from true to false or opposite
public void mouseClicked() {
if(mouseX > 385 && mouseX < 685 && mouseY > 700 && mouseY < 750)
{
state = INTRODUCTION;
}
if(mouseX > 385 && mouseX < 535 && mouseY > 750 && mouseY < 800)
{
state = STORYBOARD;
}
if(mouseX > 535 && mouseX < 685 && mouseY > 750 && mouseY < 800)
{
state = FEATURES;
}
}
}
Note that I'm unable to test this code(so there may be syntax errors), but the concept explained should be clear.
Also, check out this answer on a similar question and also the Button sample (under File > Examples > Topics > GUI > Button in Processing)

My Tortoise & Hare Java Project Won't Work

I have to do this thing for my Java class where I make an applet displaying a tortoise & hare race. Here is the assignment:
This project involves writing an applet to simulate a tortoise and hare race. The
contenders will each race along a horizontal course that contains a lane for each
of them. The course should have at least 50 squares or positions…you may add
more if you wish. The race begins with each contender at position 1 of their
respective lanes. The contender that first reaches or passes the last square of
the course is the winner of the race.
The following table indicates the types of moves that each contender can make.
Contender Type of Move Percentage of Time Result of Move
Tortoise Fast plod 50% 3 squares to right
Slow plod 30% 1 square to right
Slip 20% 6 squares to left
Hare Big hop 20% 9 squares to right
Small hop 30% 1 square to right
Big slip 10% 12 squares to left
Small slip 20% 2 squares to left
Fall asleep 20%
Each contender starts at position 1. When a contender slips, they can’t slip any
further left than position 1. You will use a random number generator to simulate
the percentages of each type of move indicated in the table.
Generate a random integer, n, in the range 1 ≤ n ≤ 10. For the tortoise, perform a
fast plod if the number is 1-5, a slow plod if the number is 6-8, and a slip if the
number is 9-10. For the hare, perform a big hop if the number is 1-2, a small hop
if the number is 3-5, a big slip if the number is 6, a small slip if the number is 7-8,
and fall asleep if the number is 9-10.
You must keep track of each contender’s position and display each contender’s
position using a graphics image. Graphics images for the tortoise and hare can
be found in the course downloads folder. You may have to adjust the length of
the course and the size of the applet window to get just the right look.
Hint: Get the overall logic for the program working before you deal with the
graphics. You might find it helpful (but it is not absolutely necessary) to structure
the overall control flow based on a simulation clock. Each time the clock “ticks”
the contenders move.
My program doesn't give an error message, but when I try to run it, I get a blank image of two rectangles with a bunch of divisions, it says "Race" and "Turn Null." I have tried the best I could to find what's wrong, but I think it could use a different pair of eyes. Please help if possible!
Here is my code:
import java.awt.*;
import java.applet.*;
public class TortoiseAndHareProject extends Applet {
Image tortoise, hare; //creates two images, tortoise and hare
int tortX = 250, hareX = 250; //sets them both to start at pixel 250
final int tortY = 100, hareY = 300, WIDTH = 15, HEIGHT = 50; //sets finals tortY, hareY, WIDTH, and HEIGHT = variables to use in the race
//WIDTH will serve as a counter for distance
int turn;
String turnNum;
int move;
String tMove, hMove;
public void init() {
tortoise = getImage(getDocumentBase(), "tortoise.gif");
hare = getImage(getDocumentBase(), "hare.gif");
move = 0;
turn = 0;
}
public void control() throws InterruptedException {
while ((tortX < 985) || (hareX < 985)) { //while neither has won the race yet (985 = finish)
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) { //nothing happens, the hare just doesn't move
} else if (hareX <= (250 + (11 * WIDTH))) //if hare is less than 12 squares ahead of 250
hareX = 250; //the hare just goes back to 250
else
hareX -= (12 * WIDTH); //the hare just moves back 12 * WIDTH
tMove = "Slow Plod";
hMove = "Big Slip";
break;
case 7:
case 8:
tortX += (1 * WIDTH);
if (hareX == 250) { //nothing happens, the hare just doesn't move
} else if (hareX <= (250 + (WIDTH))) //if hare is less than 2 squares ahead of 250
hareX = 250; //the hare just goes back to 250
else
hareX -= (2 * WIDTH); //the hare just moves back 2 * WIDTH
tMove = "Slow Plod";
hMove = "Small Slip";
break;
case 9:
case 10:
if (tortX == 250) { //nothing happens
} else if (tortX <= (250 + (5 * WIDTH))) //if the tortoise is less than 6 squares ahead of 250
tortX = 250; //the tortoise just goes back to 250
else
tortX -= (6 * WIDTH);
tMove = "Slip";
hMove = "Fall Asleep.";
break;
}
turn++;
turnNum = (turn + "");
repaint();
Thread.sleep(30);
}
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) { //if hareX has gotten greater than 985
screen.setFont(new Font("Times New Roman", Font.ITALIC, 48));
screen.drawString("Hare Wins", 650, 240);
clearCurrent(screen);
fillNext(screen);
} else {
screen.drawString(("Turn " + turnNum), 621, 55);
screen.setFont(new Font("Times New Roman", Font.ITALIC, 12));
if (tMove != null) {
screen.drawString(tMove, 59, 65);
}
if (hMove != null) {
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);
//in order to get a new screen
}
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);
//in order to fill the screen with the tortoise & hare
}
public void drawRace(Graphics s) {
s.drawRect(250, 100, 750, 50); //draws a rectangle for the race
s.drawRect(250, 300, 750, 50); //draws another rectangle for the race
int lineX = 265, lineYi = 100, lineYf = 150;
for (int i = 1; i <= 98; i++) { //for the duration of the race
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 stop() {
}
}

Java race applet not working

I'm having trouble simulating a race between two competitors. This is your typical race program where you use a random number generator to determine what "moves" the competitors use. As seen in my code below, the track is composed of 50 rectangles, and the filled in rectangle shows the location of each competitor on the track. Some "moves" make the competitor jump 9 squares to the right, or 2 squares back, for example. When I run the applet, only the initial starting position is displayed; the applet doesn't work. I realize it's a lot of code, but what do I need to do to fix my problem? I'm really stuck at this point. Any help is appreciated. I have can only use AWT, not swing. This is an assignment for class :/ Here is the code:
import java.awt.*;
import java.applet.*;
public class Example 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) {} // DO NOTHING
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) {} // DO NOTHING
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) {} // DO NOTHING
else if (tortX <= (250 + (5 * WIDTH)))
tortX = 250;
else
tortX -= (6 * WIDTH);
tMove = "Slip"; hMove = "Fall Asleep. Zzz...";
break;
// Hare falls asleep. No action.
}
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 )
{
// GENERATES INITIAL GRAPHICS FOR RACE
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()
{
}
}
Your first problem is you actually never "start" the race...Sure your init the applet, but then, nothing...
Your second problem is the control method is block the Event Dispatching Thread, this means, they while you are in this method NOTHING will get painted to the screen. This is because the Event Dispatching Thread is also responsible for dispatching repaint requests.
You third problem is your violating the paint contact. You have a responsibility to call super.paint(screen) - paint is a complex method and should never ignore it unless you have a REALLY good reason do to so.
Your fourth problem is, you using an Applet instead of a JApplet. Better to ignore the AWT controls in favor of the Swing controls. Swing are more flexible and easier to extend.
Your fifth problem is you painting onto a top level container, this is never recommended. You are better using something like JPanel and overriding it's paintComponent method (don't forget to call super.paintComponent). Apart from everything else, it's double buffered and will reducing flicking as the screen is updated.
Take a look at...
Concurrency in Swing and How to use Swing Timer to solve you EDT blocking issues...
Performing Custom Painting for ideas about painting in Swing

Multithreading in java

I want to use 4 threads in my applet and used Runnable interface wants to move all the threads around required position.
When in my applet, clouds image walks from o to 750 at y axis and the helicopter starts walking when clouds comes at 150 in y axis and helicopter walks upto it reaches to the 350 and then this thread stops.
And then when my helicopter reaches to the 200 then a man image comes out and walks to the x axis, it will stop when it has walked 5 to 10 milliseconds.
following is my code:
import java.applet.* ;
package com.pack;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class HelicopterScene extends Applet {
Image a, b, c;
int i, j, h, p;
public void init() {
i = 20;
j = 750;
h = 0;
a = getImage(getCodeBase(), "HelicopterAttack.jpg");
b = getImage(getCodeBase(), "pppp.png");
c = getImage(getCodeBase(), "helicopter1.png");
}
public void paint(Graphics g) {
showStatus(" Helicopter Scene Applet is started.....");
g.drawImage(a, 0, 0, this);
if (i <= 750 && j >= 20) {
if (i >= 150) {
g.drawImage(c, h, 255, 150, 35, this);
h++;
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException w) {
}
}
g.drawImage(b, j, 120, 90, 70, this);
g.drawImage(b, i, 180, 120, 70, this);
i++;
j--;
repaint();
try {
Thread.sleep(10);
if (i == 750 && j == 20) {
p = h;
g.drawImage(c, p, 255, 150, 35, this);
h++;
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException w) {
}
i = 20;
j = 750;
}
} catch (InterruptedException e) {
}
}
}
}
First of all, you never want to sleep on the UI thread. Second, you never want to paint off the UI thread. You should investigate SwingUtilities.invokeLater().

Categories

Resources