Skip to content

Instantly share code, notes, and snippets.

@ornirus
Last active August 29, 2015 14:07
Show Gist options
  • Save ornirus/10919b4353175aa0d908 to your computer and use it in GitHub Desktop.
Save ornirus/10919b4353175aa0d908 to your computer and use it in GitHub Desktop.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class RandomMovement extends JFrame
implements ActionListener {
int xPos, yPos, direction;
private JPanel panel;
private Random random;
private javax.swing.Timer timer;
public static void main(String[] args) {
RandomMovement frame = new RandomMovement();
frame.setSize(700, 700);
frame.createGUI();
frame.setVisible(true);
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout() );
random = new Random();
panel = new JPanel();
panel.setPreferredSize(new Dimension(600, 600));
panel.setBackground(Color.lightGray);
window.add(panel);
timer = new javax.swing.Timer(200, this);
timer.start();
xPos = 350;
yPos = 350;
direction = 0;
}
public void actionPerformed(ActionEvent event) {
Graphics paper = panel.getGraphics();
paper.setColor(Color.blue);
paper.fillOval(xPos, yPos, 15, 15);
direction = random.nextInt(4);
if (direction == 0) {
paper.setColor(Color.lightGray);
paper.fillOval(xPos, yPos, 15, 15);
yPos = yPos - 20;
yPos = (yPos + 685) % 685;
paper.setColor(Color.blue);
paper.fillOval(xPos, yPos, 15, 15);
}
if (direction == 1) {
paper.setColor(Color.lightGray);
paper.fillOval(xPos, yPos, 15, 15);
yPos = yPos + 20;
yPos = (yPos + 685) % 685;
paper.setColor(Color.blue);
paper.fillOval(xPos, yPos, 15, 15);
}
if (direction == 2) {
paper.setColor(Color.lightGray);
paper.fillOval(xPos, yPos, 15, 15);
xPos = xPos + 20;
xPos = (xPos + 685) % 685;
paper.setColor(Color.blue);
paper.fillOval(xPos, yPos, 15, 15);
}
if (direction == 3) {
paper.setColor(Color.lightGray);
paper.fillOval(xPos, yPos, 15, 15);
xPos = xPos - 20;
xPos = (xPos + 685) % 685;
paper.setColor(Color.blue);
paper.fillOval(xPos, yPos, 15, 15);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment