I am currently looking to program a snake game. At the moment I have a rectangle(which will be the main snake), which I can move from left to right using the arrow keys. I can't find any code which will allow me to use the up and down arrows to move the rectangle. I have included the code which I am using below. Any help will be greatly appreciated. Thanks :)
MAIN SNAKE
- import processing.core.PApplet;
- import javax.swing.JOptionPane;
- public class Snake extends PApplet{
- Rect1 play1 = new Rect1(150,10,150,10,this);
- int keyPressed = 0;
- int sensitivity = 3;
- int directionY;
- int directionX;
- //Instantiate object with input values
- public void setup(){
- size(400,400);
- smooth();
- }
- public void keyPressed(){
- if(key==CODED) {
- if (keyCode==LEFT){
- keyPressed = (-1*sensitivity);
- play1.move(keyPressed);
- }
- else if(keyCode==RIGHT){
- keyPressed = (1*sensitivity);
- play1.move(keyPressed);
- }
- else if (keyCode == UP) {
- keyPressed();
- play1.move(keyPressed);
- println("UP");
- } else if (keyCode == DOWN) {
- play1.move(keyPressed);
- println("DOWN");
- }
- }
- }
- //Draw and move the object
- public void draw(){
- this.frameRate(25);
- //PApplet.println(ra1,x1);
- background(150,240,200);
- play1.display();
- // Bright red
- fill(255,200,0);
- ellipse(20,20,16,16);
- }
- }
RECTANGLE
- import processing.core.PApplet;
- public class Rect1 {
- int x1,y1,x2,y2;
- float speed;
- PApplet parent;
- Rect1(int startX, int startY, int endX, int endY, PApplet p){
- parent = p;
- x1 = startX;
- y1 = startY;
- x2 = endX;
- y2 = endY;
- }
- void display(){
- parent.fill(255,100,100);
- parent.noStroke();
- parent.rect(x1,y1,x2,y2);
- }
- void move(int move){
- x1 +=move;
- }
- }
1