I have a game in Processing and there are two classes - main and player. I'm thinking the main class should have the setup and menu, and the player class have the controls, collision, movement etc.
I need help figuring out how to connect the two classes so the game can run. In the main class some variables and methods are not defined so I know I'm not referencing or calling them right.
I'm fairly new to classes and methods so any help would be appreciated. Thanks!
Main class:
//used for setup
//makes program run
//diff currents? play/instr/dead/replay
PFont title, main, dead;
PImage candy, lollipop, cottonCandy;
PImage badApple, bananaPeel, pepper;
PImage panda, heart, bkgrd;
PImage [] goodCandy = new PImage [3];
PImage [] badFood = new PImage [3];
PrintWriter highScore;
String current="menu";
int menuBut1x, menuBut1y;
int menuBut2x, menuBut2y;
int menuBut3x, menuBut3y;
int backButx, backButy;
void setup() {
size(1200,700);
frameRate(30);
title = loadFont("Gabriola-150.vlw");
textFont(title);
main = loadFont("SegoeUI-Light-60.vlw");
textFont(main);
dead = loadFont("Stencil-200.vlw");
textFont(dead);
highScore = createWriter("HighScore.txt");
menuBut1x = width/3-70;
menuBut1y = height/2-100;
menuBut2x = width/3-70;
menuBut2y = height/2+40;
menuBut3x = width/3-70;
menuBut3y = height/2+180;
backButx = 1030;
backButy = 10;
candy = loadImage("goodCandy0.png");
cottonCandy = loadImage("goodCandy1.png");
lollipop = loadImage("goodCandy2.png");
badApple = loadImage("badFood0.png");
bananaPeel = loadImage("badFood1.png");
pepper = loadImage("badFood2.png");
panda = loadImage("panda.png");
heart = loadImage("heart.png");
bkgrd = loadImage("floatClouds.jpg");
for (int i=0; i<goodCandy.length; i++) {
goodCandy[i] = loadImage("goodCandy" + i + ".png"); //loading goodCandy imgs via array
}
for (int i=0; i<badFood.length; i++) {
badFood[i] = loadImage("badFood" + i + ".png"); //loading badFood imgs via array
}
}
public void menu (){
background(#bfefff);
fill(255);
rect(menuBut1x, menuBut1y, 520, 100); //first button
rect(menuBut2x, menuBut2y, 520, 100); //second button
rect(menuBut3x, menuBut3y, 520, 100); //third button
textSize(100);
fill(#000000);
textFont(title);
text("Candy Dash!", 300, 180);
textSize(200);
fill(#000000);
textFont(main);
text("PLAY", 530, 320);
textSize(65);
fill(#000000);
textFont(main);
text("INSTRUCTIONS", 400, 465);
textSize(65);
fill(#000000);
textFont(main);
text("HIGH SCORES", 415, 600);
if (current=="menu") {
//background(#F0D5E2); DON'T HAVE BACKGROUND COLOUR HERE OR WILL COVER EVERYTHING - BKGRD TOP OF VOID DRAW
if (mouseX >= menuBut1x && mouseX <= menuBut1x+520 && mouseY >= menuBut1y && mouseY <= menuBut1y+100 && mousePressed) {
current="play"; //clicked play button
}
if (mouseX >= menuBut2x && mouseX <= menuBut2x+520 && mouseY >= menuBut2y && mouseY <= menuBut2y+100 && mousePressed) {
current="instructions"; //clicked instructions button
}
if (mouseX >= menuBut3x && mouseX <= menuBut3x+520 && mouseY >= menuBut3y && mouseY <= menuBut3y+100 && mousePressed) {
current="high scores"; //clicked high scores button
}
pandaX = 550; //resets the panda to starting position
pandaY = 580; //RESET EVERYTHING WHEN EXIT
points = 0;
}
if (current=="instructions") {
background(#e8f0f7);
textSize(80);
text("INSTRUCTIONS", 360, 140);
textSize(35);
text("Use the arrow keys to move left and right.", 100,240);
text("Your goal is to collect all the yummy candies, and avoid the bad foods!", 100, 300);
text("Watch out! Touch a bad food and YOU ARE DEAD!", 100, 360);
fill(#F0FFF0); //back button
rect(backButx, backButy, 160, 100); //back button
textSize(50);
fill(#000000);
text("MENU", 1040, 75);
textSize(35);
fill(#000000);
text("COLLECT THESE:", 180, 450);
image(candy, 80, 480, 120, 80);
image(lollipop, 220, 480, 100, 170);
image(cottonCandy, 350, 480, 100, 180);
text("AVOID THESE:", 800, 450);
image(badApple, 720, 480, 100, 140);
image(bananaPeel, 830, 480, 180, 170);
image(pepper, 1030, 470, 100, 170);
if (mouseX >= backButx && mouseX <= backButx+160 && mouseY >= backButy && mouseY <= backButy+100 && mousePressed) {
current="menu"; //clicked menu button
}
}
if (current=="high scores") {
background(#e8f0f7);
fill(#F0FFF0);
rect(backButx, backButy, 160, 100); //back button
textSize(50);
fill(#000000);
text("MENU", 1040, 75);
textSize(100);
text("HIGH SCORE: " + points, 300, height/2);
if (mouseX >= backButx && mouseX <= backButx+160 && mouseY >= backButy && mouseY <= backButy+100 && mousePressed) {
current="menu"; //clicked menu button
}
}
if (current=="play") {
image(bkgrd, 0, 0, 1200, 700);
//background(#cfe1e1);
fill(#F0FFF0);
rect(backButx, backButy, 160, 100); //back button
textSize(50);
fill(#000000);
text("MENU", 1040, 75);
candyFall(); //calling methods
touchCandy();
newCandy();
badFoodFall();
if (mouseX >= backButx && mouseX <= backButx+160 && mouseY >= backButy && mouseY <= backButy+100 && mousePressed) {
current="menu"; //clicked menu button
}
}
if (current=="gameOver") {
background(#7B0B1F);
textFont(dead);
textSize(150);
text("YOU ARE DEAD", 70, height/2);
textFont(main);
fill(#fbfbfb);
rect(200, 500, 300, 150); //replay button
textSize(80);
fill(#000000);
noStroke();
text("REPLAY", 220, 600);
fill(#fbfbfb);
rect(700, 500, 300, 150); //menu button
textSize(80);
fill(#000000);
noStroke();
text("MENU", 745, 600);
highScore.println("High Score: " + points); // Write the points to the file
points=0; //reset points to 0 when dead
pandaX = 550; //resets pandaX when dead
pandaY = 580; //resets pandaY when dead
if (mouseX >= 200 && mouseX <= 200+300 && mouseY >= 500 && mouseY <= 500+150 && mousePressed) {
current="play"; //clicked replay
}
if (mouseX >= 700 && mouseX <= 700+300 && mouseY >= 500 && mouseY <= 500+150 && mousePressed) {
current="menu"; //clicked menu button
}
}
}
Player class:
//controls movement of panda, collision w/ falling objects, etc -- all in different methods
import java.io.Serializable;
public class Player implements Serializable {
public int pandaX, pandaY, pandaW, pandaH;
public int candyY, candyX, candyW, candyH;
public int randCandyW, randCandyH, badAppleX, randY, lolliY;
public int rand, randX, randX2, lolliX;
public int points;
public int candySpeed, foodSpeed;
public int yDirCandy, yDirFood;
//constructor of class, where default values are assigned (coordinates, points, etc)
public Player(){
//setting up default coordinates
pandaX = 550;
pandaY = 580;
pandaW = 80;
pandaH = 112;
points = 0;
candySpeed = 10;
foodSpeed = 5;
yDirCandy = 1;
yDirFood = 1;
candyY = 10;
candyX = 200;
candyW = 187;
candyH = 121;
randCandyW = 100;
randCandyH = 100;
badAppleX = 700;
randY = -200;
lolliY = -600;
rand = (int) (2*Math.random()) +1;
randX = (int) (1100*Math.random())+20;
randX2 = (int) (1100*Math.random())+20;
lolliX = (int) (1100*Math.random())+20;
}
public int GetPoints(){ //just test
return points;
}
public void candyFall() {
image(panda, pandaX, pandaY, pandaW, pandaH);
fill(#000000);
text("Points: " + points, 20, 70);
touchCandy();
newCandy();
image(candy, candyX, candyY, candyW, candyH); //original candy
candyY = candyY + (candySpeed * yDirCandy);
image(goodCandy[rand], randX, randY, randCandyW, randCandyH); //rand candy
randY = randY + (candySpeed * yDirCandy);
image(lollipop, lolliX, lolliY, randCandyW, randCandyH); //lolli candy
lolliY = lolliY + (candySpeed * yDirCandy);
highScore.println("High Score: " + points); // Write the points to the file
}
public void badFoodFall(){
image(badFood[rand], randX2, randY, randCandyW, randCandyH); //rand food
randY = randY + (candySpeed * yDirCandy);
image(badApple, badAppleX, randY, randCandyW, randCandyH); //rand food
randY = randY + (candySpeed * yDirFood);
}
public void keyPressed() {
if (key==CODED) {
if (keyCode==LEFT) {
pandaX = pandaX-20;
}
if (keyCode==RIGHT) {
pandaX = pandaX+20;
}
if (pandaX<=5) {
pandaX=5; //if hit into wall panda won't go off screen
}
if (pandaX>=1120) {
pandaX=1120;
}
highScore.flush(); // Writes the remaining data to the file
highScore.close(); // Finishes the file
}
}
public void touchCandy() {
if ( (pandaX + pandaW > candyX && //original candy
pandaX < candyX + candyW &&
pandaY + pandaH > candyY &&
pandaY < candyY + candyH) ||
(pandaX + pandaW > randX && //rand candy
pandaX < randX + randCandyW &&
pandaY + pandaH > randY &&
pandaY < randY + randCandyH) ||
(pandaX + pandaW > lolliX && //lollipop
pandaX < lolliX + randCandyW &&
pandaY + pandaH > lolliY &&
pandaY < lolliY + randCandyH)
)
{
textSize(60);
text("YUM! You get points!", 370, 300);
points = points + 1; //if panda touches candy, get points!
image(heart, pandaX+20, pandaY-50, 50, 50);
}
if ((pandaX + pandaW > randX2 && //rand food
pandaX < randX2 + randCandyW &&
pandaY + pandaH > randY &&
pandaY < randY + randCandyH) ||
(pandaX + pandaW > badAppleX && //apple
pandaX < badAppleX + randCandyW &&
pandaY + pandaH > randY &&
pandaY < randY + randCandyH))
{
current="gameOver";
}
}
public void newCandy() {
if (candyY>=850) {
candyY=0; //resetting the original candy to top
}
if (lolliY>=850) {
lolliY=0; //resetting lolli to top
}
if (randY>=850) {
randY=0;
}
}
}
Related
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);
}
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.
}
}
}
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!");
}
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) {}
}
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()
{
}
}