import java.awt.*; import javax.swing.JApplet; import java.util.*; import java.awt.image.*; import javax.imageio.*; import java.net.*; import java.awt.event.*; /** * Demonstates how to write a Java Applet that can be run in a web browser * * @author Pete Nordquist * @version 120212 - now use component's width and height and an instance-level * Random number generator * @version 100127 - updated for tag example and added JApplet * @version 040415 - original */ public class GreenSnake extends JApplet implements KeyListener { /* HelloApp instance variables */ // declare a Random number generator Random rg = new Random(); private int score; private int snakeX; private int snakeY; private int blockSize = 20; // size of snake blocks and mice // private String s; /** * Called immediately after the applet starts. * Purpose is to initialize values that will be used by the paint method. */ public void init() { // s = this.getParameter("STODRAW"); // BufferedImage img = // ImageIO.read(new URL(getCodeBase(), "Sunset.jpg")); score = 0; snakeX = 0; snakeY = this.getHeight() - blockSize; this.addKeyListener(this); } /** * Called after the init() method and called everytime the applet needs to display itself. * Purpose is to draw the image the user sees. * (paint() is executed in a different thread than init().) * @param g the Graphics context in which the drawing takes place. */ public void paint(Graphics g) { // draw snake g.setColor(Color.white); g.fillRect(0,0, this.getWidth(), this.getHeight()); g.setColor(Color.green); g.fillRect(snakeX,snakeY,blockSize,blockSize); // // display string at point 50 pixels to the right and 50 pixels down from the upper left corner // g.setColor(Color.BLACK); // // if the applet is begin run in the appletViewer, the getParameter() call in init() // // will return null, so assign a default string if s == null. // if (s == null) // s = "Default string"; // g.drawString(s, 50, 50); // // append " - OK" to s and draw it again in the middle of the screen // s = s + " - OK"; // g.drawString(s, width / 2, height / 2); } public void keyPressed(KeyEvent ke) { // if the up arrow was pressed if (ke.getKeyCode() == KeyEvent.VK_RIGHT) { // set position one block to the right snakeX = snakeX + blockSize; repaint(); } } public void keyReleased(KeyEvent ke) {} public void keyTyped(KeyEvent ke) {} }