有人能帮我控制java处理中的蛇游戏吗

r7knjye2  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(362)

我正在做一个java处理的基本蛇游戏。当用户按l或d时,蛇应该顺时针转动,当用户按a或j键时,蛇应该逆时针转动。钥匙不应该直接控制蛇的方向。他们应该控制蛇的转向。
演示看演示问题2
问题图像
我的代码

final int ROWS=20, COLS=15; //The number of rows and columns of squares
 final int SQ_SIZE=40;       //The size of each square in pixels
 final int[] X_DIRECTIONS = {0, -1, 0, 1}; //X change for down, left, up, right
 final int[] Y_DIRECTIONS = {1, 0, -1, 0}; //Y change for down, left, up, right

 int startingLength = 5, currentLength = 0, snakeSpeed = 30, currentDirection = 0;
 int [] x = new int[ROWS*COLS];
 int [] y = new int[ROWS*COLS];

 void setup(){
   background(#ff9900);
   size(600,800); //MUST be COLS*SQ_SIZE, ROWS*SQ_SIZE
   resetSnake();
 }

 void draw(){
   if(frameCount % snakeSpeed == 0){
       background(#ff9900);  
       drawCircles(x, y, currentLength, #32CD32);
       moveSnake(X_DIRECTIONS[currentDirection],  Y_DIRECTIONS[currentDirection]);
       //moveSnake(X_DIRECTIONS[currentDirection], 0);
   }  
 }

 void resetSnake(){
   currentLength = startingLength;
   fillArray(y, currentLength, ROWS/2, -1);
   fillArray(x, currentLength, COLS/2, 0);
   drawCircles(x, y, currentLength, #32CD32);
 }

 void moveSnake(int addX, int addY){
   if(addX != 0){
     fillArray(x, currentLength, x[0] + addX, addX);
   } 
   fillArray(y, currentLength, y[0] + addY, -addY);
 }

 void keyPressed(){
   int newDir = keyCode == DOWN ? 0:(keyCode == UP ? 2:(keyCode == RIGHT ? 3:(keyCode == LEFT ? 1:-1)));
   if(newDir != -1) currentDirection = newDir;  
 }

 void drawCircles(int[]x, int[]y, int n, int colour){
   //Draw circles here
    for(int i = 0; i < n; i++){
      fill(colour);
      circle(x[i]*SQ_SIZE, y[i]*SQ_SIZE, SQ_SIZE);
    }
 }

 void fillArray(int[] a, int n, int start, int delta){
   int index = 0;
   if(delta > 0){
     for(int i = start; i < start + n; i+=delta){
       a[index++] = i;
     }
   }else if(delta < 0){
      for(int i = start; i > start-n; i+=delta){
      a[index++] = i;
      }
   }else{
     for(int i = 0; i < n; i++){
       a[index++] = start;
     }
   }
 }
gajydyqb

gajydyqb1#

因为你有一个数组中的方向,你可以像这样“旋转”它们:

void keyPressed(){
    if (keyCode == 76 //the code for 'l'
     || keyCode == 68) { //the code for 'd'
        currentDirection++;
        if(currentDirection > 3) { //make sure currentDirection is not bigger than the array length
            currentDirection = 0;
        }
    }

    if (keyCode == 65 //the code for 'a'
     || keyCode == 74) { //the code for 'j'
        currentDirection--;
        if (currentDirection < 0) { //make sure currentDirection is not smaller than 0
            currentDirection = 3;
        }
    } 
}

相关问题