как анимировать объекты в игре atari сороконожка - PullRequest
0 голосов
/ 30 ноября 2018

Так что я работаю над созданием простого клона игры atari сороконожка.Вот видео к игровому процессу.https://www.youtube.com/watch?v=VkxJu250AO8.Что я хочу сделать, так это добавить игрока / снаряд на него.

Мой вопрос: как я могу добавить игрока / спрайта, которого можно перемещать влево и вправо, чтобы можно было стрелять ракетой?Я инициализировал свой код, но хочу знать, как я его делаю, чтобы змея двигалась сама по себе и чтобы я могла запустить по ней ракету.

import java.lang.reflect.Array;
import java.util.Random;
import javafx.animation.AnimationTimer;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundSize;
import javafx.scene.layout.Region;
import javafx.scene.media.AudioClip;



public class Game extends Region {
      private final Canvas mCanvas;
     Snake mSnake;
     Missile mMissile;
     AnimationTimer mTimer;
     final int nCells = 24;
     final int CELL_DIM = 20;
     int NUM_ROCKS = 15;
     int NUM_LIVES;

     private Image bGround= new Image("/images/starfield.png");
     private final Image rock1 = new Image("/images/Rock1.png");

    private final Image rock2 = new Image("/images/Rock2.png");
    private final Image rock3 = new Image("/images/Rock3.png");
    private final Image rock4 = new Image("/images/Rock4.png");
    private final Image mBullet= new Image("/images/bullet.png");
    private int[][] mPlayfield = new int[nCells][nCells];
    private int[] rock_Array = new int[552];
    private Image mSegment = new Image("/images/segment.png", CELL_DIM, 
    CELL_DIM, false, false);
    private Image mLauncher = new Image("/images/rocket.png", CELL_DIM, 
    CELL_DIM, false, false);

   public Game(){

    mCanvas = new Canvas(nCells * CELL_DIM, nCells * CELL_DIM);
    //NUM_ROCKS = 15;

    GraphicsContext gc = mCanvas.getGraphicsContext2D();
    gc.drawImage(bGround, 0, 0);
    mSnake = new Snake(10, 0, 0);
    NUM_LIVES = 3;
    initPlayfield();
    draw();

   }

   private void draw(GraphicsContext gc) {
      for(int i =0; i < nCells; i++){
        for(int j = 0; j < nCells; j++){
            switch(mPlayfield[i][j]){
                case 1:
                    gc.drawImage(rock1, i*CELL_DIM, j*CELL_DIM);
                    break;
                case 2:
                     gc.drawImage(rock2, i*CELL_DIM, j*CELL_DIM);
                    break;   
                case 3:
                    gc.drawImage(rock3, i*CELL_DIM, j*CELL_DIM);
                    break;
                case 4:
                    gc.drawImage(rock4, i*CELL_DIM, j*CELL_DIM);
                    break;
            }//end of switch
        }
      }//end of for           
     }//end of draw grid

    private void draw() {
     GraphicsContext gc = mCanvas.getGraphicsContext2D();
     draw(gc);
     drawSnake(gc);
     drawLauncher(gc);
    }

    public void onStop(){

  }

   private void initPlayfield() {
      createRocks();
      ranArray(rock_Array);
      int k = 0;
      for(int i=1; i < nCells; i++){
        for(int j = 0; j < nCells -1; j++){
            mPlayfield[i][j] = rock_Array[k];
            k++;
        }
       }//end of for loop
    }//end of initPlayfield

  public int[][] getField(){
     return mPlayfield;
  }
  public Canvas getCanvas(){
     return mCanvas;
  }

 private void createRocks() {
    for(int i = 0; i < NUM_ROCKS; i++){
        rock_Array[i] = 4;//initiate to 4;
    }
    for(int j = 15; j < rock_Array.length; j++){
        rock_Array[j] = 0;
    }
 }

  private void ranArray(int[] arr){
     Random rand = new Random();
     for(int i = 0; i < arr.length ; i++){
        int index = rand.nextInt(arr.length);
        int a = arr[index];
        arr[index] = arr[i];
        arr[i] = a;
    }
  }

  private void drawSnake(GraphicsContext gc) {
     for(int i =0; i < 10; i++){
        gc.drawImage(mSegment, i*CELL_DIM, CELL_DIM);
    }
  }

  private void drawLauncher(GraphicsContext gc) {
     gc.drawImage(mLauncher, 12, (nCells -1)*CELL_DIM);
  }

}//end of game

Вот мой класс многоножки

   public class MyCentipede extends Application {

   private Object root;
   private Label mStatus, mScore;
   private Canvas mCanvas = new Canvas(550, 550);


    @Override
    public void start(Stage primaryStage){

    BorderPane root = new BorderPane();
    //root.setCenter(sPane);
    Game newGame = new Game();

    root.getChildren().add(newGame.getCanvas());
    // add the menus
    root.setCenter((Node)newGame);
    root.setTop(buildMenuBar()) ;
    this.mStatus = new Label("Lives = 3");
    mScore = new Label("High Score");
    ToolBar toolBar = new ToolBar(mStatus, mScore) ;
    //root.getChildren().add(player);
    root.setBottom(toolBar) ; 

    Scene scene = new Scene(root, (newGame.nCells*newGame.CELL_DIM)-10, 
  (newGame.nCells*newGame.CELL_DIM)+20);

    primaryStage.setTitle("My Centipede!");

    primaryStage.setScene(scene);
    //primaryStage.setResizable(false);
    primaryStage.show();
 }
    public void setStatus(String status){
         this.mStatus.setText(status);
 }


  private MenuBar buildMenuBar(){
    // build a menu bar
    MenuBar menuBar = new MenuBar() ;
    // File menu with just a quit item for now
    Menu fileMenu = new Menu("_File") ;
    MenuItem quitMenuItem = new MenuItem("_Quit") ;
    quitMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.Q,
    KeyCombination.CONTROL_DOWN));
    quitMenuItem.setOnAction(actionEvent -> Platform.exit()) ;
    fileMenu.getItems().add(quitMenuItem) ;

    Menu gameMenu = new Menu("_Game") ;
    MenuItem newGame = new MenuItem("_New");
    newGame.setAccelerator(new KeyCodeCombination(KeyCode.N, 
    KeyCombination.CONTROL_DOWN));
    newGame.setOnAction(actionEvent -> onNewGame());
    MenuItem go = new MenuItem("_Go");
    go.setAccelerator(new KeyCodeCombination(KeyCode.G, 
    KeyCombination.CONTROL_DOWN));
    go.setOnAction(actionEvent -> onGo());
    MenuItem pause = new MenuItem("_Pause");
    pause.setAccelerator(new KeyCodeCombination(KeyCode.P, 
    KeyCombination.CONTROL_DOWN));
    pause.setOnAction(actionEvent -> onPause());
    MenuItem highScore = new MenuItem("_High Score");
    highScore.setAccelerator(new KeyCodeCombination(KeyCode.H, 
    KeyCombination.CONTROL_DOWN));
    MenuItem resetScore = new MenuItem("_Reset High Score");
    resetScore.setAccelerator(new KeyCodeCombination(KeyCode.R, 
    KeyCombination.CONTROL_DOWN));
    MenuItem settings = new MenuItem("_Settings");
    settings.setAccelerator(new KeyCodeCombination(KeyCode.S, 
    KeyCombination.CONTROL_DOWN));
    SeparatorMenuItem mSep = new SeparatorMenuItem();
    SeparatorMenuItem mSep1 = new SeparatorMenuItem();
    SeparatorMenuItem mSep2 = new SeparatorMenuItem();
    gameMenu.getItems().addAll(newGame, mSep, go, pause, mSep1, highScore,  
    resetScore, mSep2, settings);

    // Help menu with just an about item for now
    Menu helpMenu = new Menu("_Help") ;
    MenuItem aboutMenuItem = new MenuItem("_About") ;
    aboutMenuItem.setOnAction(actionEvent -> onAbout()) ;
    helpMenu.getItems().add(aboutMenuItem) ;
    menuBar.getMenus().addAll(fileMenu, gameMenu, helpMenu) ;
    return menuBar ;
}



/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}




}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...