蛇游戏使用数组

时间:2019-01-23 04:41:40

标签: java

我正在使用数组制作蛇游戏。我想存储每个蛇形体的xy坐标,以便以后可以将其用于碰撞或其他操作。

我使xCoordinate[row or col]的value(?)每按一次键都增加或减少1,但是我认为这不是存储坐标的正确方法。另外,按键只改变方向,因此只增加或减少一次。甚至不起作用。

我该怎么做才能存储坐标?

import java.util.Random;
import java.util.Scanner;   //allows us to use the scanner package

public class KeyInput {

    static MainBoard b; //initialize board named b

    public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        Random rand = new Random();
        final int ROWS = 25, COLS = 25;
        int row=0, col =0;
        boolean finished = false;
        int[] xCoordsFood, yCoordsFood;
        int[] xCoordsSnake, yCoordsSnake;

        b = new MainBoard(ROWS, COLS); 

        xCoordsFood = new int[25];
        yCoordsFood = new int[25];
        xCoordsSnake = new int[25];
        yCoordsSnake = new int[25];

        // MAIN GAME LOOP
        while(!finished){
            //get random location of food
            int loc = rand.nextInt(25);
            for (int i = 0; i < 25; i++) {
                xCoordsFood[i] = rand.nextInt(25);
                yCoordsFood[i] = rand.nextInt(25);
            } 

            b.putPeg("red",row,col);

            b.displayMessage("Key: " + b.getKey()); 
            if (b.getKey() == 'w'){
                row --;
                xCoordsSnake[row] =- 1;
                System.out.print(xCoordsSnake[row]);
            }
            if (b.getKey() == 'a'){
                col--;
                yCoordsSnake[col] =- 1;
                System.out.print(yCoordsSnake[col]);
            }
            if (b.getKey() == 's'){
                row ++;
                xCoordsSnake[row] =+ 1;
                System.out.print(xCoordsSnake[row]);
            }
            if (b.getKey() == 'd'){
                col++;
                yCoordsSnake[col] =+ 1;
                System.out.print(yCoordsSnake[col]);
            }
            // DELAY SO THAT ANIMATION IS SLOWED DOWN
            try {
                Thread.sleep(200);
            }
            catch (InterruptedException e){
            }
            // CHECK IF SQUARE GOES OUT OF BOUNDS
            if (row<0 || row>=ROWS || col<0 || col>=COLS){
                finished = true;
            }
            System.out.println(b.getKey());     
        }
        b.displayMessage("GAME OVER!"); 

    }
}

1 个答案:

答案 0 :(得分:0)

由于数据结构的大小可变,因此应使用有效添加新元素(例如链表)的数据结构。

此外,您不必移动数组中的所有值,因为蛇的各部分将占据其他部分的位置。因此,例如,您只需要移除尾巴并在每个动作中添加一个新的头部即可。

重要的是在编码之前要多考虑问题,以提供更简单,更有效的解决方案。

相关问题