I am currently making an applet that simulates a Tortoise vs. Hare Race. They each have individual moves, picked at random. My applet works, but it only displays the end of the race in which the Tortoise Wins. I would like it to display the individual moves that the tortoise/hare make, almost like a gif.
heres 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;
int tortoiseXPos = 180, hareXPos = 180;
final int tortoiseYPos = 50, hareYPos = 400, SQUARE = 20;
int move;
public void init()
{
tortoise = getImage(getDocumentBase(), "tortoise.gif");
hare = getImage(getDocumentBase(), "hare.gif");
}
public void gameControl()
{
//1200 is finish line
while((tortoiseXPos < 1200) || (hareXPos < 1200))
{
move = (int)(Math.random() * 10);
tortoiseMoves(move);
hareMoves(move);
for(int i = 0; i < 10; i++)
{
delay();
}
}
}
public void paint(Graphics field)
{
drawField(field);
drawMove(field);
//Display winner when they get to the finish line
if(tortoiseXPos >= 1200)
{
field.setFont(new Font("Times New Roman", Font.ITALIC, 72));
field.drawString("Tortoise Wins", 650, 240);
}
else if(hareXPos >= 1200)
{
field.setFont(new Font("Times New Roman", Font.ITALIC, 72));
field.drawString("Tortoise 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 < 25; i++)
{
field.fillRect(x, 50, SQUARE, 50);
field.fillRect(x, 400, SQUARE, 50);
x += (SQUARE * 2);
}
field.setColor(Color.white);
x = 200;
for(int i = 0; i < 25; i++)
{
field.fillRect(x, 50, SQUARE, 50);
field.fillRect(x, 400, SQUARE, 50);
x += (SQUARE * 2);
}
}
public void clearMove(Graphics s)
{
}
public void drawMove(Graphics s)
{
gameControl();
s.drawImage(tortoise, tortoiseXPos, 50, this);
s.drawImage(hare, hareXPos, 400, this);
}
public void tortoiseMoves(int move)
{
//Moves for Tortoise
if(move <= 5)
{
tortoiseXPos += (3 * SQUARE);
}
else if(move <= 8)
{
tortoiseXPos += SQUARE;
}
else if(move <= 10)
{
tortoiseXPos -= (6 * SQUARE);
}
if(tortoiseXPos < 0)
{
tortoiseXPos = 0;
}
if(tortoiseXPos > 1200)
{
tortoiseXPos = 1200;
}
}
public void hareMoves(int move)
{
//Moves for Hare
if(move <= 2)
{
hareXPos += (9 * SQUARE);
}
if(move <= 5)
{
hareXPos += (SQUARE);
}
if(move <= 6)
{
hareXPos -= (SQUARE);
}
if(move <= 8)
{
hareXPos -= (2 * SQUARE);
}
if(move <= 10)
{
hareXPos = hareXPos;
}
if(hareXPos < 0)
{
hareXPos = 0;
}
if(hareXPos > 1200)
{
hareXPos = 1200;
}
}
public void delay()
{
//To see individual moves
for(int i = 0; i <= 90000000; i++)
{}
}
}
If you guys could give me some pointers on what method to use or how I should go about doing this, I'd appreciate it. Thanks
Add two arrays to your class and store each move for each racer. Then, "paint" the points for each racer on the screen as the race is progressing.
Related
Currently I'm studying Computer Science and my teacher want me to make a snake game with array.
I have this code that is exactly same as my friend's but it only grow one body length and won't grow longer and after it eats the food it starts to slow down the speed of moving snake. I'm not sure where I went wrong please help. Thank you.
Here's the code:
public class Main extends JPanel implements KeyListener, ActionListener {
private static final long serialVersionUID = 1L;
static int dir;
static int i;
static int x[] = new int[200]; // Decleare Array of snake on x coordinate
static int y[] = new int[200]; // Decleare Array of snake on y coordinate
static int taillength = 1;
static int sxinc = 20, syinc = 20; // Speed of moving snake
static int fx = 100, fy = 100; // Declare the position of where food at
static int f2x = 300, f2y = 300; // Declare the position of where food2 at
static int fmx = 300, fmy = 100; // Declare the position of where food3 at
static int score = 0; // Create Score Counter
static int width = 745, height = 489; // Declare the size of JPanel
static int nsx, nsy; // The new value of the snake movement
static int csx = 20, csy = 20; // The value to add/minus on the number to
static BufferedImage background = null;
static JFrame f;
static JFrame g;
public Main() {
addKeyListener(this);
}
public void addNotify() {
super.addNotify();
requestFocus();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, width, height, this);
g.setColor(Color.GREEN);
g.fillRect(fx, fy, 20, 20);
g.setFont(new Font("Times New Roman", Font.BOLD, 15));
g.setColor(Color.GREEN);
g.drawString("GREEN - Add 1 body length, add 1 score", 0, 429);
g.setColor(Color.BLUE);
g.fillRect(f2x, f2y, 20, 20);
g.setFont(new Font("Times New Roman", Font.BOLD, 15));
g.setColor(Color.BLUE);
g.drawString("BLUE - Add 2 body length, add 2 score", 0, 444);
g.setColor(Color.CYAN);
g.fillRect(fmx, fmy, 20, 20);
g.setFont(new Font("Times New Roman", Font.BOLD, 15));
g.setColor(Color.CYAN);
g.drawString("CYAN - Minus 1 body length, add 1 score", 0, 459);
g.setColor(Color.RED);
for (int j = 0; j < x.length && j < taillength; j++) {
g.fillRect(x[j], y[j], 20, 20);
g.setColor(Color.ORANGE);
}
g.fillRect(x[0], y[0], 20, 20);
g.setColor(Color.RED);
g.setFont(new Font("Times New Roman", Font.BOLD, 25));
g.setColor(Color.WHITE);
g.drawString("Score : " + score, 305, 459);
}
public void snakenew() {
for (int i = 0; i < x.length; i++) {
x[i] = 0;
y[i] = 0;
}
}
public static void main(String a[]) {
x[0] = 300;
y[0] = 220;
try { // Import Background
background = ImageIO.read(new File("H:/shutterstock_12730534.jpg"));
} catch (IOException e) {
}
Main p = new Main();
g = new JFrame();
g.add(p);
g.setSize(200, 300);
g.setVisible(true);
g.setResizable(false);
f = new JFrame();
f.add(p);
f.setSize(width, height);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Timer t = new Timer(60, p);
t.start();
}
public void actionPerformed(ActionEvent e) {
if ((x[0] + 20 > width) || (x[0] < 0) || (y[0] + 40 > height)
|| (y[0] < 0)) { // Game over when hit the wall
JOptionPane.showMessageDialog(null, "You hit the wall!", "Game",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
if ((taillength > 1) && (x[i] != x[0]) && (y[i] != y[0])) { // Game over
// when
// touch you
// snake
// body
if ((x[0] == x[i]) & (y[0] == y[i])) {
JOptionPane.showMessageDialog(null, "You ran into yourself!",
"Game", JOptionPane.INFORMATION_MESSAGE);
}
}
if (dir == KeyEvent.VK_UP) {
if (y[0] == y[taillength]) {
y[0] = y[0] - syinc;
}
}
else if (dir == KeyEvent.VK_DOWN) {
if (y[0] == y[taillength]) {
y[0] = y[0] + syinc;
}
}
else if (dir == KeyEvent.VK_LEFT) {
if (x[0] == x[taillength]) {
x[0] = x[0] - sxinc;
}
}
else if (dir == KeyEvent.VK_RIGHT) {
if (x[0] == x[taillength]) {
x[0] = x[0] + sxinc;
}
}
if (dir == KeyEvent.VK_K) {
if ((score > 6) && (taillength > 5)) {
taillength = taillength - 5;
score = score - 7;
}
}
if ((x[0] == fx) && (y[0] == fy)) { // Food Score and random food
fx = (int) (Math.random() * 37) * 20;
fy = (int) (Math.random() * 25) * 20;
taillength++;
score++;
}
if ((x[0] == f2x) && (y[0] == f2y)) {
f2x = (int) (Math.random() * 37) * 20;
f2y = (int) (Math.random() * 25) * 20;
taillength = taillength + 2;
score = score + 2;
}
if ((x[0] == fmx) && (y[0] == fmy)) {
if (taillength > 0) {
fmx = (int) (Math.random() * 37) * 20;
fy = (int) (Math.random() * 25) * 20;
taillength--;
score++;
}
}
for (i = taillength; i > 0; i--) {
x[i] = x[(i - 1)];
y[i] = y[(i - 1)];
}
f.repaint();
}
public void keyPressed(KeyEvent ke) {
dir = ke.getKeyCode();
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
}
A few things:
You are using a timer, but the item you are putting in the timer has no run() method... That's not how a timer works (please reference the last point as to why).
You are redrawing the whole screen every single time you tick. Not only is that ridiculous, it is most likely the cause of your aforementioned lag when you grow the body. Fixing this will ensure that you experience little to now lag between growth (although, you will still need to compensate at later growths by changing the speed of the snake; this, will also make the game more difficult as you go on, just like real Snake). This usage of the paint() method, can be attributed to the same reasoning as the last point.
You took someone elses code. Don't use code that doesn't belong to you--it might work, and you're fine, or you might have the same bug as the other guy, and now you've got a great time explaining why you have the copied code of some other student.
In conclusion: if you want to borrow code, never borrow code from someone who is in the same course as you. Finally, look up some examples of Snake games in Java. I'm sure you'll find some people who have experienced similar problems, from whom you might learn. I hope this helps you, and best of luck!
I'm trying to recreate a DigDug game in Java for my computer science class.
As I'm just a beginner, I'm only going to have the monsters move up and then back down, instead of chasing the player. I'm having difficulties making the monsters continuously move though. It will go up, but it will not go back down, and it doesn't repeat.
Previously it would just immediately fly off the screen if the player reached the point, or it wouldn't move at all. I have tried a for-loop, a while-loop and a do-while loop. I also tried a delay but it stopped my entire program. The goal is to make all of the monsters move up and down when the player reaches a certain point (340, 270).
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.Timer;
import java.util.ArrayList;
import java.awt.event.KeyAdapter;
public class DigDug extends Applet implements MouseMotionListener, MouseListener, KeyListener
{
private final Color c_background = new Color(32, 73, 150);
private final Color c_first = new Color(230, 185, 9);
private final Color c_second = new Color(224, 128, 18);
private final Color c_third = new Color(232, 61, 14);
private final Color c_last = new Color(184, 0, 0);
private final Color c_score = new Color(232, 42, 96);
public boolean ifEntered = false;
public boolean isMoving1 = false;
private int count = 0;
private int otherCount = 0;
private Image flower;
private Image diggy;
private Image enemies1;
private Image enemies2;
private Image enemies3;
private Image arrowUp;
private Image arrowDown;
private Image arrowLeft;
private Image arrowRight;
//private ArrayList<Point> enemies = new ArrayList<Point>();
Font myFont = new Font("SansSerif",Font.BOLD, 16);
private Timer timer;
private Point Up;
private int digx = 685;
private int digy = 45;
private int e1x = 76;
private int e1y = 210; //i created a variable that would hold the enemies's values
private int e2x = 465;
private int e2y = 342;
private int e3x = 546;
private int e3y = 127;
private boolean ifW = false;
private boolean ifA = false;
private boolean ifS = false;
private boolean ifD = false;
private boolean yaas = false;
private int arrowX = digx+5;
private int arrowY = digy+5;
private ArrayList<Integer> xpts = new ArrayList<Integer>();
private ArrayList<Integer> ypts = new ArrayList<Integer>();
public void init()
{
diggy = getImage(getDocumentBase(), "Dig_Dug.png");
flower = getImage(getDocumentBase(), "flower.gif");
enemies1 = getImage(getDocumentBase(), "Pooka.png");
enemies2 = getImage(getDocumentBase(), "Fygar.gif");
enemies3 = getImage(getDocumentBase(), "Pooka.png");
arrowUp = getImage(getDocumentBase(), "ArrowUp.png");
arrowDown = getImage(getDocumentBase(), "ArrowDown.png");
arrowRight = getImage(getDocumentBase(), "Arrow-Point-Right.png");
arrowLeft = getImage(getDocumentBase(), "ArrowLeft copy.png");
setBackground(c_background);
setSize(700,500);
addMouseMotionListener(this);
addMouseListener(this);
setFont(myFont);
addKeyListener(this);
Up = new Point(digx, digy);
}
public void paint(Graphics g)
{
score(g);
background(g);
g.setColor(Color.white);
//g.fillRect(player.x, player.y, 10, 10);
if(ifEntered)
{
if(digx > 330)
digx--;
else if(digy < 247)
digy++;
repaint();
}
if(digx == 330 && digy == 247)
{
yaas = true; //checks if the player has reached spot
//(random variable i created
}
if(yaas == true) //this if statement is where i am having the problem
{
//int count = 0;
//int count = 0;
boolean isUp = false;
for(int i = 0; i < count; i++)
{
if(e1y == 210)
{
while(e1y != 120)
{
e1y--;
}
isUp = true;
}
if(e1y == 120 && isUp == true)
{
while(e1y != 210)
{
e1y++;
}
isUp = false;
}
count++;
}
}
g.drawImage(diggy, digx, digy, 20, 20, null);
g.drawImage(flower, 680, 41, 20, 20, null);
g.drawImage(enemies1, e1x, e1y, 20, 20, null);
g.drawImage(enemies2, e2x, e2y, 20, 20, null);
g.drawImage(enemies3, e3x, e3y, 20, 20, null);
if(digy > e1y && digy < (e1y+20) && digx > e1x && digx < (e1x+20) ||e1y == digy || e1x == digx )
{
background(g);
g.setColor(Color.white);
g.drawString("GAME OVER", 294, 260);
// repaint();
}
if(digy > e2y && digy < (e2y+20) && digx > e2x && digx < (e2x+20)||e2y == digy || e2x == digx )
{
background(g);
g.setColor(Color.white);
g.drawString("GAME OVER", 294, 260);
// repaint();
}
if(digy > e3y && digy < (e3y+20) && digx > e3x && digx < (e3x+20) || e3y == digy && e3x == digx)
{
background(g);
g.setColor(Color.white);
g.drawString("GAME OVER", 294, 260);
// repaint();
}
}
public void score(Graphics g)
{
g.setColor(c_score);
g.drawString("1UP", 101, 21);
g.drawString("HIGH SCORE", 271, 21);
g.setColor(Color.white);
g.drawString(" " + count, 118, 35);
g.drawString(" " + count, 317, 35);
}
public void background(Graphics g)
{
g.setColor(c_first);
g.drawRect(0,65, 700, 120);
g.fillRect(0, 65, 700, 120);
g.setColor(c_second);
g.drawRect(0,166, 700, 120);
g.fillRect(0,166, 700, 120);
g.setColor(c_third);
g.drawRect(0, 267, 700, 120);
g.fillRect(0, 267, 700, 120);
g.setColor(c_last);
g.drawRect(0, 388, 700, 120);
g.fillRect(0, 388, 700, 120);
}
First, you will need an understanding of Painting in AWT and Swing and Concurrency in Java. I would also discourage the use of Applet, applets have there own bunch of issues which you probably don't need to deal with right now.
The paint method is not the place to update the state of your UI, the paint method should just paint the current state. You should also not change the state of the UI from within the paint method, this could cause no end of issues
To start with, you need some kind of "game loop", this loop is responsible for updating the state of the game and scheduling the updates to the UI
In the main loop, we maintain a movement "delta", this describes the amount of change that a particular object has and in what direction, in this example, I'm only dealing with enemies1, but you can imagine anything that moves will need it's own as well.
On each cycle of the game loop, we apply the delta to the objects current position, do a bounds check and invert the delta as required...
e1y += moveDelta;
if (e1y >= 210) {
e1y = 209;
moveDelta *= -1;
} else if (e1y <= 120) {
e1y = 121;
moveDelta *= -1;
}
The mainLoop below should probably go in the init or start method, depending on if you can work out how to "pause" the Thread
Thread mainLoop = new Thread(new Runnable() {
#Override
public void run() {
int moveDelta = -1;
gameOver = false;
while (!gameOver) {
if (ifEntered) {
if (digx > 330) {
digx--;
} else if (digy < 247) {
digy++;
}
repaint();
}
// Removed some code here for testing
e1y += moveDelta;
if (e1y >= 210) {
e1y = 209;
moveDelta *= -1;
} else if (e1y <= 120) {
e1y = 121;
moveDelta *= -1;
}
if (digy > e1y && digy < (e1y + 20) && digx > e1x && digx < (e1x + 20) || e1y == digy || e1x == digx) {
gameOver = true;
} else if (digy > e2y && digy < (e2y + 20) && digx > e2x && digx < (e2x + 20) || e2y == digy || e2x == digx) {
gameOver = true;
} else if (digy > e3y && digy < (e3y + 20) && digx > e3x && digx < (e3x + 20) || e3y == digy && e3x == digx) {
gameOver = true;
}
try {
Thread.sleep(40);
} catch (InterruptedException ex) {
}
repaint();
}
}
});
mainLoop.start();
You then need to replace the paint method with code that only paints the current state of the game
#Override
public void paint(Graphics g) {
super.paint(g);
score(g);
background(g);
g.setColor(Color.white);
//g.fillRect(player.x, player.y, 10, 10);
if (gameOver) {
g.setColor(Color.white);
g.drawString("GAME OVER", 294, 260);
} else {
g.drawImage(diggy, digx, digy, 20, 20, null);
g.drawImage(flower, 680, 41, 20, 20, null);
g.drawImage(enemies1, e1x, e1y, 20, 20, null);
g.drawImage(enemies2, e2x, e2y, 20, 20, null);
g.drawImage(enemies3, e3x, e3y, 20, 20, null);
}
}
Now, I'd recommend that you dump Applet in favour of a JPanel (for the core logic) and a JFrame (for displaying) and a Swing Timer instead of the Thread. You get double buffering for free to start with
This is my game project. It's very simple version of "Flappy Bird" and I have some serious problems with how the collisions algorithm works. I wrote 2 separate code fragments for collision, for wall1 and wall2. The problem begins when the ball is trying to go through a hole because somehow the program is detecting a collision with a wall. I'm almost positive that the collision algorithm was written correctly because I have been checking it all day.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends Applet implements KeyListener, Runnable {
Image bground;
Random generator = new Random();
int r1;
int wall1x;
int wall1y;
int wall1long;
int wall2x;
int wall2y;
int wall2long;
Timer timer;
private Image i;
private Graphics doubleG;
int r2;
int blok_x1 = 800;
int blok_y1;
int blok_x = 800;
int blok_y = 0;
int blok_x_v = 2;
int ballX = 20;
int ballY = 20;
int dx = 0;
int dyclimb = 1;
int dyrise = 1;
double gravity = 3;
double jumptime = 0;
int FPS = 100;
public int tab[];
public boolean grounded = true, up = false;
boolean OVER = false;
#Override
public void init() {
bground = getImage(getCodeBase(), "12.png");
this.setSize(600, 400);
tab = new int[100];
for (int t = 0; t < 100; t++) {
tab[t] = generator.nextInt(380) + 1;
}
addKeyListener(this);
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
ballX -= 10;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
ballX += 10;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
ballY -= 10;
up = true;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
ballY += 10;
}
}
#Override
public void paint(Graphics g) {
g.drawImage(bground, 0, 0, this);
if (OVER == false) {
for (int i = 0; i < 100; i++) {
g.setColor(Color.green);
wall1x = blok_x + i * 400;
wall1y = blok_y;
wall1long = tab[i];
g.fillRect(wall1x, wall1y, 20, wall1long);
g.setColor(Color.green);
wall2x = blok_x1 + i * 400;
wall2y = tab[i] + 60;
wall2long = 400 - tab[i];
g.fillRect(wall2x, wall2y, 20, wall2long);
g.setColor(Color.green);
}
g.setColor(Color.red);
g.fillOval(ballX, ballY, 20, 20);
} else {
g.drawString("GAME OVER", 300, 300);
}
}
#Override
public void update(Graphics g) {
if (i == null) {
g.setColor(Color.green);
i = createImage(this.getSize().width, this.getSize().height);
doubleG = i.getGraphics();
g.setColor(Color.green);
}
doubleG.setColor(getBackground());
g.setColor(Color.green);
doubleG.fillRect(0, 0, this.getSize().width, this.getSize().height);
doubleG.setColor(getForeground());
g.setColor(Color.green);
paint(doubleG);
g.drawImage(i, 0, 0, this);
}
#Override
public void run() {
int time = 10;
while (true) {
if (up == true) {
ballY -= dyclimb;
time--;
} else {
ballY += dyrise;
}
if (time == 0) {
time = 10;
up = false;
}
blok_x--;
blok_x1--;
if (ballX > 600 || ballX < 0 || ballY > 400 || ballY < 0) {
OVER = true;
}
for (int i = 0; i < 100; i++) { // collision algorithm
wall1x = blok_x + i * 400;
wall1y = blok_y;
wall1long = tab[i];
if (ballX + 20 >= wall1x && ballX <= wall1x + 20 && ballY <= wall1y + wall1long && ballY >= wall1x - 20) { //wall1
OVER = true;
}
}
for (int i = 0; i < 100; i++) {
wall2x = blok_x1 + i * 400;
wall2y = tab[i] + 60;
wall2long = 400 - tab[i];
if (ballX + 20 >= wall2x && ballX <= wall2x + 20 && ballY <= wall2y + wall2long && ballY >= wall2x - 20) { //wall2
OVER = true;
}
}
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
Logger.getLogger(NewApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Use Rectangle class. There's a method called Intersect or Intersection or something like that.
Say you have one object moving. Make a Rectangle to match the object in position(basically an invisible cover for the object).
Do the same things with another object.
When both are to collide, use the intersection method to check on the collision by using the rectangles.
These might help
http://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html
Java method to find the rectangle that is the intersection of two rectangles using only left bottom point, width and height?
java.awt.Rectangle. intersection()
Arrays are not my strong point and I usually have to go through a lot of errors, IndexOutOfBoundsException usually, before I get it right. this time the error I'm getting is this over and over again.
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at FinalSnake$DrawPanel.paintComponent(FinalSnake.java:272)
at javax.swing.JComponent.paint(JComponent.java:1037)
at javax.swing.JComponent._paintImmediately(JComponent.java:5106)
at javax.swing.JComponent.paintImmediately(JComponent.java:4890)
at javax.swing.RepaintManager$3.run(RepaintManager.java:814)
at javax.swing.RepaintManager$3.run(RepaintManager.java:802)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:802)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:745)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:725)
at javax.swing.RepaintManager.access$1000(RepaintManager.java:46)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1680)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:715)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:676)
at java.awt.EventQueue$2.run(EventQueue.java:674)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:685)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
When I use this code in my program, which is used to paint the body of the snake.
/* Sprite: Snake Body */
if (length > 0) {
for (int i = 0; i <= length; i++) {
g.setColor(Color.darkGray);
g.fillRect(bodyX.get(i), bodyY.get(i), width, height);
}
}
I never can understand what the program is trying to tell me whenever I get these errors XD
Here's the rest of the code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
public class FinalSnake extends JFrame {
String direction = "right";
//String duration =
int time = 100;
int start = 0;
/* Sprite: snake head co-ordinates */
int x = 400;
int y = 450;
int width = 10;
int height = 10;
/* Sprite: snake body */
int length = 0;
ArrayList<Integer> bodyX = new ArrayList<Integer>();
ArrayList<Integer> bodyY = new ArrayList<Integer>();
/* Score */
int point = 0;
String p = String.valueOf(point);
/* Sprite: mouse co-ordinates */
Random rand = new Random();
int addx = (rand.nextInt(10)) * 10;
int addy = (rand.nextInt(10)) * 10;
int mx = ((rand.nextInt(5) + 1) * 100) + addx;
int my = ((rand.nextInt(6) + 2) * 100) + addy;
DrawPanel drawPanel = new DrawPanel();
Timer timer;
public FinalSnake() {
addMouseListener(new MouseListenerfinal());
timer = new Timer(time, new TimerListener()); ////////////// <<<<<<<<<<<<<<<<<< TIMER
timer.start();
/* move snake up */
Action upAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
direction = "up"; ////////////// <<<<<<<<<<<<<<<<<< direction only change
}
};
/* move snake down */
Action downAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
direction = "down";
}
};
/* move snake left */
Action leftAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
direction = "left";
}
};
/* move snake right */
Action rightAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
direction = "right";
}
};
InputMap inputMap = drawPanel
.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = drawPanel.getActionMap();
inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "rightAction");
actionMap.put("rightAction", rightAction);
inputMap.put(KeyStroke.getKeyStroke("LEFT"), "leftAction");
actionMap.put("leftAction", leftAction);
inputMap.put(KeyStroke.getKeyStroke("DOWN"), "downAction");
actionMap.put("downAction", downAction);
inputMap.put(KeyStroke.getKeyStroke("UP"), "upAction");
actionMap.put("upAction", upAction);
add(drawPanel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}// FinalSnake()
private class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) { /////////////////// <<<<<<<<<<<<<< All logic here
if ("right".equals(direction)) {
x += 10;
if (x >= mx && x <= mx + 9 && y >= my && y <= my + 9) {
addx = (rand.nextInt(10)) * 10;
addy = (rand.nextInt(10)) * 10;
mx = ((rand.nextInt(5) + 1) * 100) + addx;
my = ((rand.nextInt(6) + 1) * 100) + addy;
point += 100;
p = String.valueOf(point);
length++;
time--;
bodyY.add(0, y);
bodyX.add(0, x);
//System.out.println(bodyX + ":" + bodyY);
}
if (x > 699) {
new GameOver();
dispose();
}
} else if ("left".equals(direction)) {
x -= 10;
if (x >= mx && x <= mx + 9 && y >= my && y <= my + 9) {
addx = (rand.nextInt(10)) * 10;
addy = (rand.nextInt(10)) * 10;
mx = ((rand.nextInt(5) + 1) * 100) + addx;
my = ((rand.nextInt(6) + 1) * 100) + addy;
point += 100;
p = String.valueOf(point);
length++;
time--;
bodyY.add(0, y);
bodyX.add(0, x);
}
if (x < 99) {
new GameOver();
dispose();
}
} else if ("up".equals(direction)) {
y -= 10;
if (y >= my && y <= my + 9 && x >= mx && x <= mx + 9) {
addx = (rand.nextInt(10)) * 10;
addy = (rand.nextInt(10)) * 10;
mx = ((rand.nextInt(5) + 1) * 100) + addx;
my = ((rand.nextInt(6) + 1) * 100) + addy;
point += 100;
p = String.valueOf(point);
length++;
time--;
bodyY.add(0, y);
bodyX.add(0, x);
}
if (y < 99) {
new GameOver();
dispose();
}
} else if ("down".equals(direction)) {
y += 10;
if (y >= my && y <= my + 9 && x >= mx && x <= mx + 9) {
addx = (rand.nextInt(10)) * 10;
addy = (rand.nextInt(10)) * 10;
mx = ((rand.nextInt(5) + 1) * 100) + addx;
my = ((rand.nextInt(6) + 1) * 100) + addy;
point += 100;
p = String.valueOf(point);
length++;
time--;
bodyY.add(0, y);
bodyX.add(0, x);
}
if (y > 799) {
new GameOver();
dispose();
}
}
drawPanel.repaint();
}
}
private class GameOver extends JFrame implements ActionListener {
JLabel answer = new JLabel("");
JPanel pane = new JPanel(); // create pane object
JButton pressme = new JButton("Quit");
JButton replay = new JButton("Replay?");
GameOver() // the constructor
{
super("Game Over");
timer.stop(); ////////////////////// <<<<<<<<<< Stop TIMER
setBounds(100, 100, 300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane(); // inherit main frame
con.add(pane);
pressme.setMnemonic('Q'); // associate hotkey
pressme.addActionListener(this); // register button listener
replay.addActionListener(this);
pane.add(answer);
pane.add(pressme);
pane.add(replay);
pressme.requestFocus();
answer.setText("You Lose");
setVisible(true); // make frame visible
}// GameOver()
// here is the basic event handler
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == pressme)
System.exit(0);
if (source == replay) {
dispose();
EventQueue.invokeLater(new Runnable() {
public void run() {
new FinalSnake();
}
});
}
}// actionPreformed
}// GameOver
private class DrawPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (start == 1){
g.setColor(Color.white);
}
Font ith = new Font("Ithornît", Font.BOLD, 78);
/* Background: Snake */
g.setColor(Color.darkGray);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.gray);
g.fillRect(100, 100, 600, 700);
g.setColor(Color.white);
g.drawRect(99, 99, 601, 701);
g.drawString("Quit", 102, 86);
g.drawRect(100, 70, 30, 20);
//g.drawString("Pause", 152, 86);
//g.drawRect(150, 70, 40, 20);
g.drawString("Score: ", 602, 86);
g.drawString(p, 640, 86);
g.setFont(ith);
g.drawString("SNAKE", 350, 60);
/* Sprite: Mouse */
g.setColor(Color.black);
g.fillRect(mx, my, width, height);
/* Sprite: Snake Body */
if (length > 0) {
for (int i = 0; i < length; i++) {
g.setColor(Color.darkGray);
g.fillRect(bodyX.get(i), bodyY.get(i), width, height);
}
}
/* Sprite: Snake head */
g.setColor(Color.white);
g.fillRect(x, y, width, height);
}// Paint Component
public Dimension getPreferredSize() {
return new Dimension(800, 850);
}// Dimension
}// DrawPanel
public static void main(String[] args) {
//new StartScreen();
EventQueue.invokeLater(new Runnable() {
public void run() {
new FinalSnake();
}
});
}// main
}// Snake Class
/* Tracks where mouse is clicked */
class MouseListenerfinal extends MouseAdapter {
public void mouseReleased(MouseEvent me) {
if (me.getX() >= 101 && me.getX() <= 131 && me.getY() >= 94
&& me.getY() <= 115) {
System.exit(0);
}
if (me.getX() >= 151 && me.getX() <= 181 && me.getY() >= 94
&& me.getY() <= 115) {
}
String str = "Mouse Released at " + me.getX() + "," + me.getY();
System.out.println(str);
}
}// MouseAdapter
Change for (int i = 0; i <= length; i++) { to for (int i = 0; i < length; i++) {, since ArrayLists start at index 0 and end at size()-1.
Ok so weird thing happened! I decided to switch the > into a < in the for loop and now it works!! I'm laughing at myself because the only problems were the less than/greater than signs.
for (int i = 0; i < length; i++) {
I found out why I got the error in the for loop
for (int i = 0; i < length; i++) {
the i < length really should be i > length. I assumed it was right and didn't look it over
after fixing that it still did not output the body and i have yet to make it work because when I run it I get a similar error, but it still runs the program (not the way it should tho)
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 64, Size: 64
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at FinalSnake$DrawPanel.paintComponent(FinalSnake.java:277)
at javax.swing.JComponent.paint(JComponent.java:1037)
at javax.swing.JComponent._paintImmediately(JComponent.java:5106)
at javax.swing.JComponent.paintImmediately(JComponent.java:4890)
at javax.swing.RepaintManager$3.run(RepaintManager.java:814)
at javax.swing.RepaintManager$3.run(RepaintManager.java:802)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:802)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:745)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:725)
at javax.swing.RepaintManager.access$1000(RepaintManager.java:46)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1680)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:715)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:676)
at java.awt.EventQueue$2.run(EventQueue.java:674)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:685)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
EDIT: Thanks to all who pointed out the typo! However, I am still having issues with my timer. For some reason, the timer is not causing the window to be repainted after every second. Edited code is posted below!
I am having trouble compiling the following code- I get the two errors:
C:\java>javac Project2.java
Project2.java:8: error: Project2 is not abstract and does not override abstract
method actionPerformed(ActionEvent) in ActionListener
public class Project2 extends Applet implements ActionListener
^
Project2.java:19: error: <anonymous Project2$1> is not abstract and does not ove
rride abstract method actionPerformed(ActionEvent) in ActionListener
ActionListener getNewValues = new ActionListener() {
^
2 errors
The purpose of the program is to simulate a race between a tortoise and a hare. A random number generator is used to determine how many moves forward or backward the tortoise and hare can move at any given turn.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import javax.swing.*;
import java.awt.Color;
public class Project2 extends Applet
{
int squaret = 1;
int squareh = 1; //initial location of tortoise and hare
int move;
String tmessage;
String hmessage;
Timer timer;
public void init()
{
timer = new Timer(1000, getNewValues);
timer.addActionListener(getNewValues);
}
ActionListener getNewValues = new ActionListener() {
public void actionPerformed(ActionEvent e)
{
repaint();
}
};
public void paint (Graphics g)
{
move = (int)(Math.random() * 10) + 1;
if (move > 8)
{
squaret -= 6;
tmessage = "Tortoise slips!";
if (squaret < 1)
squaret = 1;
}
else if (move > 6)
{
squaret += 1;
tmessage = "Tortoise plods slowly along.";
if (squaret > 49)
squaret = 50;
squareh -=2;
hmessage = "Hare slips slightly.";
if (squareh < 1)
squareh = 1;
}
else if (move > 5)
{
squaret += 1;
tmessage = "Tortoise plods slowly along.";
if (squaret > 49)
squaret = 50;
squareh -=12;
hmessage = "Hare makes a big slip.";
if (squareh < 1)
squareh = 1;
}
else if (move > 2)
{
squaret += 3;
tmessage = "Tortoise plods along quickly.";
if (squaret > 49)
squaret = 50;
squareh += 1;
hmessage = "Hare makes a small hop.";
if (squareh > 49)
squareh = 50;
}
else
{
squaret += 3;
tmessage = "Tortoise plods along quickly.";
if (squaret > 49)
squaret = 50;
squareh += 9;
hmessage = "Hare makes a big hop.";
if (squareh > 49)
squareh = 50;
}
g.drawString("Start (Square 1)", 0, 70);
g.drawString("Finish (Square 50)", 900, 70);
//determine positions for each area
//each box is ten wide and 150 tall
final int WIDTH_OF_OVAL = 4;
final int HEIGHT_OF_OVAL = 4;
final int WIDTH_OF_SQUARE = 20;
final int HEIGHT_OF_SQUARE = 20;
g.setColor(Color.GREEN);
g.fillOval(((WIDTH_OF_SQUARE - WIDTH_OF_OVAL) / 2) + WIDTH_OF_SQUARE * (squaret - 1), ((HEIGHT_OF_SQUARE - HEIGHT_OF_OVAL) / 2), WIDTH_OF_OVAL, HEIGHT_OF_OVAL);
g.setColor(Color.YELLOW);
g.fillOval(((WIDTH_OF_SQUARE - WIDTH_OF_OVAL) / 2) + WIDTH_OF_SQUARE * (squaret - 1), ((HEIGHT_OF_SQUARE - HEIGHT_OF_OVAL) / 2) + HEIGHT_OF_SQUARE, WIDTH_OF_OVAL, HEIGHT_OF_OVAL);
//show messages
g.setColor(Color.BLACK);
g.drawString(tmessage, 10, 100);
g.drawString(hmessage, 10, 120);
g.drawLine(0, HEIGHT_OF_SQUARE, WIDTH_OF_SQUARE * 50, HEIGHT_OF_SQUARE); //draw horizontal middle line
for (int i = 0; i < 50; i++) //draw vertical lines
{
int width = (i + 1) * WIDTH_OF_SQUARE;
g.drawLine(width, 0, width, HEIGHT_OF_SQUARE * 2);
}
if (squaret > 49 && squareh > 49)
{
g.drawString("Tie!", 500, 60);
timer.stop();
}
else if (squaret > 49)
{
g.drawString("Turtle wins!", 500, 60);
timer.stop();
}
else if (squareh > 49)
{
g.drawString("Hare wins!", 500, 60);
timer.stop();
}
else
{
}
update(g);
}
public static void main(String[] args)
{
Project2 panel = new Project2();
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(2600, 300);
application.setVisible(true);
}
}
I have the method actionPerformed so I am not sure why I am getting the error that I am getting. Any feedback or help would be much appreciated!
You have a spelling mistake in actionPerformed, you missed r. Change to:
public void actionPerformed(ActionEvent e)
{
repaint();
}