Program:
package snake;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.util.LinkedList;
public class SnakeCanvas extends Canvas implements Runnable
{
private final int GRID_WIDTH = 30;
private final int GRID_HEIGHT = 30;
private final int BOX_WIDTH = 5;
private final int BOX_HEIGHT = 5;
private int direction = Direction.NO_DIRECTION;
private LinkedList <Point> snake;
private Point fruit;
private Thread runThread;
private Graphics globalGraphics;
public void paint(Graphics g)
{
this.setPreferredSize(new Dimension(640,480));
snake = new LinkedList<Point>();
snake.add(new Point(3,1));
snake.add(new Point(3,2));
snake.add(new Point(3,3));
fruit = new Point(0,0);
globalGraphics = g.create();
if (runThread == null)
{
runThread = new Thread();
runThread.start();
}
}
public void Draw(Graphics g)
{
DrawGrid(g);
DrawSnake(g);
DrawFruit(g);
}
public void Move()
{
Point head = snake.peekFirst();
Point newPoint = head;
switch(direction)
{
case Direction.NORTH:
newPoint = new Point(head.x, head.y - 1);
break;
case Direction.SOUTH:
newPoint = new Point(head.x, head.y + 1);
break;
case Direction.WEST:
newPoint = new Point(head.x - 1, head.y);
break;
case Direction.EAST:
newPoint = new Point(head.x + 1, head.y);
break;
}
snake.remove(snake.peekLast());
if (newPoint.equals(fruit))
{
//has hit fruit
}
else
if (newPoint.x < 0 || newPoint.x > GRID_WIDTH)
{
//went out of bounds
}
else
if (newPoint.y < 0 || newPoint.y > GRID_HEIGHT)
{
//went out of bounds
}
else
if (snake.contains(newPoint))
{
//hit ourself
}
snake.push(newPoint);
}
public void DrawGrid(Graphics g)
{
//Draws the outside of the Rectangle
g.drawRect(0, 0, GRID_HEIGHT * BOX_HEIGHT, GRID_WIDTH * BOX_WIDTH);
//Draws the horizontal lines of the grid
for (int x = BOX_WIDTH; x < GRID_WIDTH * BOX_WIDTH; x+= BOX_WIDTH)
{
g.drawLine(x, 0, x, BOX_HEIGHT * GRID_HEIGHT);}
//Draws the vertical lines of the grid
for (int y = BOX_HEIGHT; y < GRID_HEIGHT * BOX_HEIGHT; y+= BOX_HEIGHT)
{
g.drawLine(0, y, BOX_WIDTH * GRID_WIDTH, y);
}
}
public void DrawSnake(Graphics g)
{
g.setColor(Color.BLUE); //Sets snake body to blue
for (Point p : snake){g.fillRect(p.x * BOX_WIDTH, p.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
} //Finds all snakes body parts filling in the grid at their points
g.setColor(Color.BLACK); //Returns color back to normal
}
public void DrawFruit(Graphics g)
{
g.setColor(Color.RED); //Sets fruit color
g.fillOval(fruit.x * BOX_WIDTH, fruit.y * BOX_HEIGHT, BOX_WIDTH , BOX_HEIGHT); //Draws circle within grid for fruit
}
@Override
public void run()
{
while(true)
{
Move();
Draw(globalGraphics);
try
{
Thread.currentThread();
Thread.sleep(100);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
Post A Comment:
0 comments: