Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Using graphics, timer, canvas, key events, and OOP, let's make pac man!
- */
- //imports
- //Graphics, GUI, Keyboard Interaction
- import java.awt.*;
- import java.awt.geom.*;
- import java.awt.event.KeyEvent;
- import javax.swing.JFrame;
- //We know Random
- import java.util.Random;
- //Timer is for animations
- import java.util.Timer;
- //PacGame is our interface for the game, window, gui, playing space
- public class PacGame extends Canvas {
- //Declare some variables
- PacMan player;
- public PacGame() {
- //adds a key event for keyboard interactions
- enableEvents(java.awt.AWTEvent.KEY_EVENT_MASK);
- requestFocus(); //makes sure the window is in focus
- //initialize our shapes
- player = new PacMan();
- Timer t = new Timer(true);
- t.schedule(new java.util.TimerTask()
- {
- public void run()
- {
- doStuff();
- repaint();
- }
- }, 10, 10);
- }
- public void paint(Graphics g) {
- player.draw(g);
- }
- //this method will run when a key event occurs
- public void processKeyEvent(KeyEvent e){
- if (e.getID() == KeyEvent.KEY_PRESSED)
- {
- if (e.getKeyCode() == KeyEvent.VK_W)
- {
- player.direction = "up";
- }
- if (e.getKeyCode() == KeyEvent.VK_S)
- {
- player.direction = "down";
- }
- if (e.getKeyCode() == KeyEvent.VK_A)
- {
- player.direction = "left";
- }
- if (e.getKeyCode() == KeyEvent.VK_D)
- {
- player.direction = "right";
- }
- }
- if (e.getID() == KeyEvent.KEY_RELEASED)
- {
- if (e.getKeyCode() == KeyEvent.VK_W || e.getKeyCode() == KeyEvent.VK_S ||e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_D )
- {
- player.direction = "";
- }
- }
- }
- public static void main(String[] args) {
- JFrame win = new JFrame("Pac-Man");
- win.setSize(1010,735);
- win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //Pong canvas = ;
- win.add(new PacGame());
- win.setVisible(true);
- }
- //where stuff happens
- public void doStuff() {
- }
- public boolean isFocusable() {return true;}
- }
- class PacMan extends Canvas {
- //TODO: ADD ANIMATION FRAMES
- int speed, score, lives, x, y, w;
- String direction; //in other games you might need a moveLR and moveUD - no need for pacman
- Color body;
- boolean isInvul;
- public PacMan() {
- speed = 1;
- body = Color.yellow;
- direction = "";
- score = 0;
- lives = 3;
- isInvul = false;
- x = 100;
- y = 100;
- w = 150;
- }
- public void draw(Graphics g) {
- g.setColor(body);
- drawCenteredCircle(g,x,y,w);
- }
- public void drawCenteredCircle(Graphics g, int x, int y, int w) {
- int a = x - (w/2);
- int b = y - (w/2);
- g.fillOval(a,b,w,w);
- }
- }
- class Wall extends Canvas {
- public Wall() {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement