Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*; // needed for event handling
- import java.awt.Toolkit;
- import java.util.Timer;
- import java.util.TimerTask;
- import java.util.Date;
- import java.awt.BorderLayout;
- public class DrawGame extends JPanel implements KeyListener, ActionListener {
- // This attribute keeps track of the number of "time steps" the
- // program has taken so far. At each time step, the snakes should
- // move, we should check for intersections, and check for keyboard events,
- // etc. This attribute is really just for convenience in debugging,
- // and is not needed for the functioning of the game.
- int totalTimeSteps=0;
- Toolkit toolkit;
- Timer timer;
- Snake snake = new Snake();
- JButton quit = new JButton("Quit");
- JTextField typingArea;
- boolean oval = true;
- public DrawGame() {
- // First thing to do: Start up the periodic task:
- System.out.println("About to start the snake.");
- startSnake(200); // Argument is number of milliseconds per snake move.
- System.out.println("Snake started.");
- setBackground(Color.yellow);
- this.add(quit); // place button in panel
- quit.addActionListener(this); // panel is listener for button
- typingArea = new JTextField(20);
- typingArea.addKeyListener(this);
- add(typingArea, BorderLayout.PAGE_START);
- }
- public void startSnake(int milliseconds) {
- toolkit = Toolkit.getDefaultToolkit();
- timer = new Timer();
- Date firstTime = new Date(); // Start task now.
- timer.schedule(new AdvanceTheSnakeTask(), firstTime, milliseconds);
- }
- class AdvanceTheSnakeTask extends TimerTask {
- public void run() {
- // Put stuff here that should happen during every advance.
- //toolkit.beep();
- snake.move();
- repaint();
- }
- }
- public void paintComponent(Graphics g) {
- super.paintComponent(g);
- snake.paint(g);
- }
- public void keyTyped(KeyEvent e) {
- if (e.getKeyChar()=='a') {
- snake.dirX=-1;
- snake.dirY=0;
- }
- if (e.getKeyChar()=='s') {
- snake.dirX=1;
- snake.dirY=0;
- }
- if (e.getKeyChar()=='w') {
- snake.dirX=0;
- snake.dirY=-1;
- }
- if (e.getKeyChar()=='z') {
- snake.dirX=0;
- snake.dirY=1;
- }
- }
- public void keyPressed(KeyEvent e) {
- }
- /** Handle the key released event from the text field. */
- public void keyReleased(KeyEvent e) {
- }
- public void actionPerformed(ActionEvent e){
- if (e.getSource() == quit)
- System.exit(0);
- }
- }
Add Comment
Please, Sign In to add comment