Java Thread handling - java

I am trying to make a stoplight that performs certain tasks after a button is clicked. What this stoplight is supposed to do is change from green to yellow after 50 secs, from yellow to red after 10 secs, and from red to green after 60 secs (this part I have working fine), and if the button is pressed when it is green it should change to yellow, this should only work after 10 secs have at least passed while green. What I have a problem is how do I check if 10 secs have passed or not?
public class Stoplight extends Applet
{
Button cross;
public void init(){
cross = new Button("Cross");
add(cross);
StoplightCanvas stoplightCanvas = new StoplightCanvas(cross);
add(stoplightCanvas);
new StoplightThread(stoplightCanvas).start();
}
}
class StoplightCanvas extends Canvas implements ActionListener
{
int Xpos;
int Ypos;
int diameter;
Button cross;
int x = 1;
StoplightCanvas(Button cross)
{
this.cross = cross;
cross.addActionListener(this);
setSize(300, 600);
}
public void paint(Graphics g)
{
diameter = 70;
Xpos = 70;
Ypos = 50;
g.setColor(Color.BLUE);
g.fillRect(70, 50, 74, 220);
g.setColor(Color.WHITE);
if (x == 1)
g.setColor(Color.RED);
drawCircles(g, Xpos, Ypos);
g.setColor(Color.WHITE);
if (x == 2)
g.setColor(Color.YELLOW);
drawCircles(g, Xpos, Ypos + diameter);
g.setColor(Color.WHITE);
if (x == 3)
g.setColor(Color.GREEN);
drawCircles(g, Xpos, Ypos + diameter * 2);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == cross) {
}
repaint();
}
void drawCircles(Graphics g, int x, int y)
{
g.fillOval(x, y, diameter, diameter);
}
public void toggleColor() {
if (x == 1)
x = 3;
else if (x == 2)
x = 1;
else if (x == 3)
x = 2;
}
}
class StoplightThread extends Thread
{
StoplightCanvas stoplightCanvas;
StoplightThread(StoplightCanvas stoplightCanvas) {
this.stoplightCanvas = stoplightCanvas;
}
public void run()
{
while (true) {
try {
if (stoplightCanvas.x == 3){
Thread.sleep(50000);
} else if (stoplightCanvas.x == 2) {
Thread.sleep(10000);
} else if (stoplightCanvas.x == 1) {
Thread.sleep(60000);
}
} catch (InterruptedException e){}
stoplightCanvas.toggleColor();
stoplightCanvas.repaint();
}
}
}

You can set a timer when they press the button for 10 seconds. When that time expires, then change the color to yellow via the callback. It is much better than dealing with exceptions, because they should be for exceptional circumstances.
See this thread on how to set a timer for later.
Edit
The poster wishes to not use timers. One way would be to store the time when the button is pressed in a variable, then access that variable and compare against the current time within the while loop of the run method.

Related

I tried to implement collision and my game now refuses to load

I'm new to coding in Java and I'm trying to code a basic collecting items game but when I tried implementing collision the code the game now just entirely refuses to load and I can't figure out why. No specific code please because it's for a course. It was working before I added the collection function but I cannot work out exactly what broke it. All that the error box says is >NullPointerException. Could not run the sketch (Target VM failed to initialize).
Code
Billy player;
Orb orb1, orb2, orb3, orb4, orb5;
CountDown timer;
int orbscollected=0;
PImage background;
int bgX=0;
final int playing=0;
final int finished=1;
int gamestate=playing;
void setup(){
size(1000, 600);
background=loadImage("background.jpg");
background.resize(width,height);
player=new Billy(height/2);
orb1=new Orb(850, 500);
orb2=new Orb(850, 400);
orb3=new Orb(850, 300);
orb4=new Orb(850, 200);
orb5=new Orb(850, 100);
timer = new CountDown(60);
}
void draw(){
if (gamestate==playing){
image(background, bgX, 0);
player.render();
orb1.render();
orb2.render();
orb3.render();
orb4.render();
orb5.render();
text(timer.getRemainingTime(), 10,10);
if (timer.getRemainingTime() == 0){
gamestate = finished;
}
if (player.collected(orb1)==true && player.collected(orb2)==true && player.collected(orb3)==true && player.collected(orb4)==true && player.collected(orb5)==true){
gamestate = finished;
}
}
}
void keyPressed(){
if (key==CODED){
if (keyCode == UP && player.y > 0)
player.y -=5;
else if (keyCode == DOWN && player.y < height-20)
player.y +=5;
else if (keyCode == RIGHT && player.x < width-20)
player.x +=5;
else if (keyCode == LEFT && player.x >0)
player.x -=5;
}
}
class Billy {
int x = 50 ;
int y;
int counter;
Boolean collected;
PImage img = loadImage("Old_hero.png");
PImage img2 = loadImage("Old_hero2.png");
Billy(int y) {
this.y = y;
}
void render() {
if (counter < 10) {
image(img, x, y);
} else if (counter < 20) {
image(img2, x, y);
} else {
counter = 0;
}
counter++;
}
Boolean collected(Orb orb){
if (player.x == orb.x && player.y == orb.y) {
collected=true;
}
return collected;
}
}
class Orb {
int x;
int y;
int counter;
PImage img1 = loadImage("mm_yellow.png");
Orb(int x, int y){
this.x = x;
this.y = y;
}
void update() {
move();
render();
}
void move() {
x -= (0);
}
void render() {
if (counter>0){
image(img1, x, y);
}
counter++;
}
}
class CountDown
{
private int durationSeconds;
public CountDown(int duration)
{
this.durationSeconds = duration;
}
public int getRemainingTime() //return the seconds left on the timer or 0
{ //millis() processing command, returns time in 1000ths sec since program started
return max(0, durationSeconds - millis()/1000) ;
}
}
Something that sticks out directly is the return value of your collected method.
If the player is not on the orb coordinates then you're returning null and that's most likely where your exception is coming from.
Change the collected variable to a boolean or initialize it to false on creation.

Setting a timer to control when the random variable is executed

I am trying to set a timer class to control when the ball chooses a new color. I need to make the ball change colors at a set time and not just continuously set different colors. This is my ball class and the whole program is run through a start class.
public void go() {
if (dx >= 0) {
dx = 20;
}
}
public void update(Start sp) {
if (x + dx > sp.getWidth() - radius * 2) {
x = sp.getWidth() - radius * 2;
dx = -dx;
}
else if (x + dx < 0) {
dx = -dx;
}
else {
x += dx;
}
}
public void paint(Graphics g) {
Random set = new Random();
int num1;
num1 = set.nextInt(4);
if (num1 == 0) {
g.setColor(Color.blue);
g.fillOval(x, y, radius * 2, radius * 2);
}
if (num1 == 1) {
g.setColor(Color.green);
g.fillOval(x, y, radius * 2, radius * 2);
}
if (num1 == 2) {
g.setColor(Color.white);
g.fillOval(x, y, radius * 2, radius * 2);
}
if (num1 == 3) {
g.setColor(Color.magenta);
g.fillOval(x, y, radius * 2, radius * 2);
}
}
Declare this field in your class, outside of a method.
Timer timer = new Timer();
Declare this method.
public void setTimerToChangeColors() {
timer.schedule(new TimerTask() {
#Override
public void run() {
// Whatever you want your ball to do to changes its colors
setTimerToChangeColors();
}
}, 10*1000); // 10 seconds * 1000ms per second
}
You only need to call setTimerToChangeColors once. It will continue restarting itself every 10 seconds. You can fill in the code for what you want to do when the task is triggered. If you want random time, you will have to edit where the timer is scheduled 10*1000 to a random generator.

java bounceBall mouse escape

I have a problem.
I am a beginner with java, and succeeded up to this point. Add bubbles with random sizes.
Now I need to make the bubbles escaping mouse when he gets near them.
Can anyone give me a hint how?
Thank you.
public class BounceBall extends JFrame {
private ShapePanel drawPanel;
private Vector<NewBall> Balls;
private JTextField message;
// set up interface
public BounceBall() {
super("MultiThreading");
drawPanel = new ShapePanel(400, 345);
message = new JTextField();
message.setEditable(false);
Balls = new Vector<NewBall>();
add(drawPanel, BorderLayout.NORTH);
add(message, BorderLayout.SOUTH);
setSize(400, 400);
setVisible(true);
}
public static void main(String args[]) {
BounceBall application = new BounceBall();
application.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private class NewBall extends Thread {
private Ellipse2D.Double thisBall;
private boolean ballStarted;
private int size, speed; // characteristics
private int deltax, deltay; // of the ball
public NewBall() {
ballStarted = true;
size = 10 + (int) (Math.random() * 60);
speed = 10 + (int) (Math.random() * 100);
int startx = (int) (Math.random() * 300);
int starty = (int) (Math.random() * 300);
deltax = -10 + (int) (Math.random() * 21);
deltay = -10 + (int) (Math.random() * 21);
if ((deltax == 0) && (deltay == 0)) {
deltax = 1;
}
thisBall = new Ellipse2D.Double(startx, starty, size, size);
}
public void draw(Graphics2D g2d) {
if (thisBall != null) {
g2d.setColor(Color.BLUE);
g2d.fill(thisBall);
}
}
public void run() {
while (ballStarted) // Keeps ball moving
{
try {
Thread.sleep(speed);
} catch (InterruptedException e) {
System.out.println("Woke up prematurely");
}
// calculate new position and move ball
int oldx = (int) thisBall.getX();
int oldy = (int) thisBall.getY();
int newx = oldx + deltax;
if (newx + size > drawPanel.getWidth() || newx < 0) {
deltax = -deltax;
}
int newy = oldy + deltay;
if (newy + size > drawPanel.getHeight() || newy < 0) {
deltay = -deltay;
}
thisBall.setFrame(newx, newy, size, size);
drawPanel.repaint();
}
}
}
private class ShapePanel extends JPanel {
private int prefwid, prefht;
public ShapePanel(int pwid, int pht) {
prefwid = pwid;
prefht = pht;
// add ball when mouse is clicked
addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
NewBall nextBall = new NewBall();
Balls.addElement(nextBall);
nextBall.start();
message.setText("Number of Balls: " + Balls.size());
}
});
}
public Dimension getPreferredSize() {
return new Dimension(prefwid, prefht);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < Balls.size(); i++) {
(Balls.elementAt(i)).draw(g2d);
}
}
}
}
You should not have a Thread for each individual ball, this will not scale well, the more balls you add, the more threads you add. At some point, the amount of work it takes to manage the threads will exceed the benefit for using multiple threads...
Also, I doubt if your need 1000fps...something like 25fps should be more than sufficient for your simple purposes. This will give the system some breathing room and allow other threads within the system time to execute.
Lets start with a simple concept of a Ball. The Ball knows where it is and which direction it is moving it, it also knows how to paint itself, for example...
public class Ball {
private int x;
private int y;
private int deltaX;
private int deltaY;
private int dimeter;
private Ellipse2D ball;
private Color color;
public Ball(Color color, Dimension bounds) {
this.color = color;
Random rnd = new Random();
dimeter = 5 + rnd.nextInt(15);
x = rnd.nextInt(bounds.width - dimeter);
y = rnd.nextInt(bounds.height - dimeter);
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
int maxSpeed = 10;
do {
deltaX = rnd.nextInt(maxSpeed) - (maxSpeed / 2);
} while (deltaX == 0);
do {
deltaY = rnd.nextInt(maxSpeed) - (maxSpeed / 2);
} while (deltaY == 0);
ball = new Ellipse2D.Float(0, 0, dimeter, dimeter);
}
public void update(Dimension bounds) {
x += deltaX;
y += deltaY;
if (x < 0) {
x = 0;
deltaX *= -1;
} else if (x + dimeter > bounds.width) {
x = bounds.width - dimeter;
deltaX *= -1;
}
if (y < 0) {
y = 0;
deltaY *= -1;
} else if (y + dimeter > bounds.height) {
y = bounds.height - dimeter;
deltaY *= -1;
}
}
public void paint(Graphics2D g2d) {
g2d.translate(x, y);
g2d.setColor(color);
g2d.fill(ball);
g2d.translate(-x, -y);
}
}
Next, we need somewhere for the balls to move within, some kind of BallPit for example...
public class BallPit extends JPanel {
private List<Ball> balls;
public BallPit() {
balls = new ArrayList<>(25);
balls.add(new Ball(Color.RED, getPreferredSize()));
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Ball ball : balls) {
ball.update(getSize());
}
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
for (Ball ball : balls) {
ball.paint(g2d);
}
g2d.dispose();
}
}
This maintains a list of balls, tells them when the need to update and when the need to paint. This example uses a simple javax.swing.Timer, which acts as the central timer which updates the balls and schedules the repaints.
The reason for this is takes care of synchronisation between the updates and the paints, meaning that the balls won't be updating while they are been painted. This is achieved because javax.swing.Timer triggers it's callbacks within the context of the EDT.
See Concurrency in Swing and How to use Swing Timers for more details.
Okay, so that fixes the threading issues, but what about the mouse avoidance...
That's a little more complicated...
What we need to is add a MouseMoitionListener to the BillPit and record the last position of the mouse.
public class BallPit extends JPanel {
//...
private Point mousePoint;
//...
public BallPit() {
//...
MouseAdapter handler = new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
mousePoint = e.getPoint();
}
#Override
public void mouseExited(MouseEvent e) {
mousePoint = null;
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
//...
The reason for including mouseExit is to ensure that balls don't try and move away from a phantom mouse cursor...
Next, we need to update Ball to have an "area of effect", this is the area around the ball that will trigger a change in movement if the mouse cursor moves within it's range...
public class Ball {
//...
private final Ellipse2D.Float areaOfEffect;
public Ball(Color color, Dimension bounds) {
//...
areaOfEffect = new Ellipse2D.Float(-10, -10, dimeter + 20, dimeter + 20);
}
Now, I also add some additional painting for debug reasons...
public void paint(Graphics2D g2d) {
g2d.translate(x, y);
g2d.setColor(new Color(0, 0, 192, 32));
g2d.fill(areaOfEffect);
g2d.setColor(color);
g2d.fill(ball);
g2d.translate(-x, -y);
}
Next, we need to modify the Ball's update method to accept the mousePoint value...
public void update(Dimension bounds, Point mousePoint) {
PathIterator pathIterator = areaOfEffect.getPathIterator(AffineTransform.getTranslateInstance(x, y));
GeneralPath path = new GeneralPath();
path.append(pathIterator, true);
if (mousePoint != null && path.contains(mousePoint)) {
// Determine which axis is closes to the cursor...
int xDistance = Math.abs(x + (dimeter / 2) - mousePoint.x);
int yDistance = Math.abs(y + (dimeter / 2) - mousePoint.y);
if (xDistance < yDistance) {
// If x is closer, the change the delatX
if (x + (dimeter / 2) < mousePoint.x) {
if (deltaX > 0) {
deltaX *= -1;
}
} else {
if (deltaX > 0) {
deltaX *= -1;
}
}
} else {
// If y is closer, the change the deltaY
if (y + (dimeter / 2) < mousePoint.y) {
if (deltaY > 0) {
deltaY *= -1;
}
} else {
if (deltaY > 0) {
deltaY *= -1;
}
}
}
}
//...Rest of previous method code...
}
Basically, what this is trying to do is determine which axis is closer to the mouse point and in which direction the ball should try and move...it's a little "basic", but gives the basic premise...
Lastly, we need to update the "update" loop in the javax.swing.Timer to supply the additional parameter
for (Ball ball : balls) {
ball.update(getSize(), mousePoint);
}
I'm going to answer this, but I'm very close to issuing a close vote because it doesn't show what you've done so far to attempt this. I would not be surprised if others are closer to the edge than I am on this. At the same time, you've clearly shown your progress before you reached this point, so I'll give you the benefit of the doubt. In the future, I would strongly advise making an attempt and then posting a question that pertains to the specific problem you're having while making that attempt.
You need two things:
The current location of the mouse
A range check and reversal of direction if too close.
The location of the mouse can be achieved by adding two variables (x and y) and, every time the mouse is moved (so add a mouse event listener to your JPanel or something) update those variables with the new location.
Then, you can do a range check (think Pythagorean theorem) on each bubble to make sure they're far enough away. If the bubble is too close, you'll want to check where that bubble would end up if it carried on its current course, as well as where it would end up if it changed X direction, Y direction, or both. Pick the one that ends up being furthest away and set the deltax and deltay to those, and let the calculation carry on as normal.
It sounds like a lot, but those are the two basic components you need to achieve this.

Java method supposed to check whether graphics touching not working

My "checkiftouching" method is not working. It is suppose to change the location of the circle and give you a point when the square and circle are touching. It senses when they are touching by checking when there locations are close enough together. The rest of the program runs smoothly. It has a square that moves with the arrows.
import java.awt.Graphics;
public class RunPaintGUI extends JFrame implements KeyListener{
int x = 30;
int y = 30;
Random randomgenerator = new Random();
int a = randomgenerator.nextInt(1220);
int b = randomgenerator.nextInt(700);
public static void main(String[] args){
RunPaintGUI RunPaintGUI = new RunPaintGUI();}
public RunPaintGUI(){
this.setSize(1275, 775);
this.setResizable(false);
this.setVisible(true);
this.setTitle("game")
this.addKeyListener(this);
}
public void paint(Graphics g){
super.paint(g);
g.fill3DRect(x,y, 60, 60, true);
g.fillOval(a, b, 50, 50);
g.drawString("score: " + score, 600, 50);
}
public void checkiftouching(){
if ((a - x) < 70){
if ((a -x) > -70){
if ((b - y) < 70){
if ((b - y) > -70){
System.out.println("you win");
a = randomgenerator.nextInt(1220);
b = randomgenerator.nextInt(720);
repaint();
score = score + 1;
}}}}}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT){
x = x - 10;
repaint();
else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
x = x + 10;
repaint();
else if (e.getKeyCode() == KeyEvent.VK_UP){
y = y - 10;
repaint();
else if (e.getKeyCode() == KeyEvent.VK_Left){
y = y + 10;
repaint();
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e {
// TODO Auto-generated method stub
}
It sounds like you need a hitbox. A hitbox, which is commonly used in game to detect collisions, can be used in your scenario. A hitbox is simply a rectangle that you don't draw but still keep track of its position. You should use a Rectangle for a hitbox. If you would prefer to use a ellipse for your cirlces though you can use a Ellipse2D. Although if you do this you will have to use a Rectangle2D.
Rectangle hitbox = new Rectangle(x,y,width,height);
//...
if (e.getKeyCode() == KeyEvent.VK_LEFT){
x = x - 10;
hitbox.x = x;
repaint();
// and so on for your various key events
Your checkiftouching() method gets much simpler with hitboxes.
if (hitbox1.intersects(hitbox)) {
System.out.println("you win");
a = randomgenerator.nextInt(1220);
b = randomgenerator.nextInt(720);
repaint();
score = score + 1;
}
If you choose to use an Ellipse2D then you must declare it like this:
Ellipse2D.Double hitbox = new Ellipse2D.Double(x,y,width,height);
Then you set the x coordinate:
hitbox.setFrame(newXCoordinate, hitbox.getY(), hitbox.getWidth(), hitbox.getHeight());
Or the y coordinate:
hitbox.setFrame(hitbox.getX(), newYCoordinate, hitbox.getWidth(), hitbox.getHeight());

stop applet flickering with double buffering Java Applet

sorry to keep asking questions about my program but i think i'm nearly there and i'm teaching myself java so please bear with me. I'm creating an applet that moves sheep object across the screen in a random direction when a dog object moves close to the sheep. Getting the sheep to move in a random direction took some work and with the help of you guys on here it now works (sort of) but what I'm trying to do now is stop it from flickering when i drag objects across the screen. I've read about double buffering, I can get it to work for items drawn in the paint method of a main class but cant get it to work for my sheep and dog objects which are defined as separate objects in separate classes. Any help will be much appreciated. Here is my code:
package mandAndDog;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class SheepDog extends Applet implements ActionListener, MouseListener, MouseMotionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
Dog dog;
Sheep sheep;
int[] directionNumbersLeft = {0, 1, 3};
int[] directionNumbersUp = {0, 1, 2};
int x;
int selection;
int xposR;
int yposR;
int sheepx;
int sheepy;
int sheepBoundsx;
int sheepBoundsy;
int MAX_DISTANCE = 50;
int direction;
int distance;
Boolean sheepisclosetodog;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
dog = new Dog(10, 10);
sheepx = 175;
sheepy = 75;
sheep = new Sheep(sheepx, sheepy);
sheepBoundsx = 30;
sheepBoundsy = 30;
direction = (int)(Math.random()*4);
distance = (int) (Math.random() * MAX_DISTANCE) % MAX_DISTANCE;
sheepisclosetodog = false;
Random rand = new Random();
x = rand.nextInt(3);
selection = directionNumbersLeft[x];
}
public void paint(Graphics g)
{
dog.display(g);
sheep.display(g);
g.drawString(Integer.toString(distance), 85, 100);
g.drawString(Integer.toString(direction), 85, 125);
g.drawString(Integer.toString(selection), 85, 140);
}
public void actionPerformed(ActionEvent ev)
{}
public void mousePressed(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseMoved(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{}
public void mouseDragged(MouseEvent e)
{
dog.setLocation(xposR, yposR);
sheep.setLocation(sheepx, sheepy);
if (xposR > (sheepx - 20)&& xposR < (sheepx - 20)+(sheepBoundsx - 20) && yposR > (sheepy - 20)
&& yposR < (sheepy - 20)+(sheepBoundsy - 20) && direction == 0){
sheepx = sheepx + 50;
direction = (int)(Math.random()*4);
}
if (xposR > (sheepx - 20)&& xposR < (sheepx - 20)+(sheepBoundsx - 20) && yposR > (sheepy - 20)
&& yposR < (sheepy - 20)+(sheepBoundsy - 20) && direction == 1){
sheepy = sheepy + 50;
direction = (int)(Math.random()*4);
}
if (xposR > (sheepx - 20)&& xposR < (sheepx - 20)+(sheepBoundsx - 20) && yposR > (sheepy - 20)
&& yposR < (sheepy - 20)+(sheepBoundsy - 20) && direction == 2){
sheepx = sheepx - 50;
direction = (int)(Math.random()*4);
}
if (sheepx <= 5){
direction = directionNumbersLeft[x];
}
if (xposR > (sheepx - 20)&& xposR < (sheepx - 20)+(sheepBoundsx - 20) && yposR > (sheepy - 20)
&& yposR < (sheepy - 20)+(sheepBoundsy - 20) && direction == 3){
sheepy = sheepy - 50;
direction = (int)(Math.random()*4);
}
if (sheepy <=5){
direction = directionNumbersUp[x];
}
xposR = e.getX();
yposR = e.getY();
repaint();
}
}
class Dog
{
int xpos;
int ypos;
int circleWidth = 30;
int circleHeight = 30;
public Dog(int x, int y)
{
xpos = x;
ypos = y;
}
public void setLocation(int lx, int ly)
{
xpos = lx;
ypos = ly;
}
public void display(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(xpos, ypos, circleWidth, circleHeight);
}
}
class Sheep
{
int xpos;
int ypos;
int circleWidth = 10;
int circleHeight = 10;
public Sheep(int x, int y)
{
xpos = x;
ypos = y;
}
public void setLocation(int lx, int ly)
{
xpos = lx;
ypos = ly;
}
public void display(Graphics g)
{
g.setColor(Color.green);
g.fillOval(xpos , ypos, circleWidth, circleHeight);
g.drawOval(xpos - 20, ypos - 20, 50, 50);
}
}
First of all, I dont exactly understand why you have a display method inside your Sheep and Dog class. Instead of doing that, I suggest you display the sheep and dog inside your SheepDog class.
Also instead of using Graphics, you should use Graphics2D. In order to use this simply do
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
}
This is possible because Graphics2D is a subclass of Graphics. Once you do that, what I would do is override the update() method and do this
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
graphics = image.getGraphics();
}
graphics.setColor(getBackground());
graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
graphics.setColor(getForeground());
paint(graphics);
g.drawImage(image, 0, 0, this);
}
When you call repaint(), it actually first calls the update() method, which in turn calls the paint() method. Towards the top of the class, you should declare
Image image;
Graphics graphics;

Categories

Resources