Потеря this в конструкторе - Java

Узнай цену своей работы

Формулировка задачи:

Доброго времени суток Имеется 5 файлов кода :
Листинг программы
  1. import javafx.animation.AnimationTimer;
  2. import javafx.application.Application;
  3. import javafx.scene.Scene;
  4. import javafx.scene.image.Image;
  5. import javafx.scene.image.ImageView;
  6. import javafx.scene.input.KeyCode;
  7. import javafx.scene.layout.Pane;
  8. import javafx.stage.Stage;
  9. import java.util.ArrayList;
  10. import java.util.HashMap;
  11. public class Game extends Application {
  12. public static ArrayList<Block> platforms = new ArrayList<>(); //храним платформы
  13. private HashMap<KeyCode,Boolean> keys = new HashMap<>(); //’раник коды кнопок.
  14. Image backgroundImg = new Image(getClass().getResourceAsStream("background.png"));
  15. public static final int BLOCK_SIZE = 45;
  16. public static final int MARIO_SIZE = 40;
  17. public static Pane appRoot = new Pane();
  18. public static Pane gameRoot = new Pane();
  19. public Character player;
  20. int levelNumber = 0;
  21. private int levelWidth;
  22. private void initContent(){
  23. ImageView backgroundIV = new ImageView(backgroundImg);
  24. backgroundIV.setFitHeight(14*BLOCK_SIZE);
  25. backgroundIV.setFitWidth(212*BLOCK_SIZE);
  26. levelWidth = LevelData.levels[levelNumber][0].length()*BLOCK_SIZE;
  27. for(int i = 0; i < LevelData.levels[levelNumber].length; i++){
  28. String line = LevelData.levels[levelNumber][i];
  29. for(int j = 0; j < line.length();j++){
  30. switch (line.charAt(j)){
  31. case '0':
  32. break;
  33. case '1':
  34. Block platformFloor = new Block(Block.BlockType.PLATFORM, j * BLOCK_SIZE, i * BLOCK_SIZE);
  35. break;
  36. case '2':
  37. Block brick = new Block(Block.BlockType.BRICK,j*BLOCK_SIZE,i*BLOCK_SIZE);
  38. break;
  39. case '3':
  40. Block bonus = new Block(Block.BlockType.BONUS,j*BLOCK_SIZE,i*BLOCK_SIZE);
  41. break;
  42. case '4':
  43. Block stone = new Block(Block.BlockType.STONE,j * BLOCK_SIZE, i * BLOCK_SIZE);
  44. break;
  45. case '5':
  46. Block PipeTopBlock = new Block(Block.BlockType.PIPE_TOP,j * BLOCK_SIZE, i * BLOCK_SIZE);
  47. break;
  48. case '6':
  49. Block PipeBottomBlock = new Block(Block.BlockType.PIPE_BOTTOM,j * BLOCK_SIZE, i * BLOCK_SIZE);
  50. break;
  51. case '*':
  52. Block InvisibleBlock = new Block(Block.BlockType.INVISIBLE_BLOCK,j * BLOCK_SIZE, i * BLOCK_SIZE);
  53. break;
  54. }
  55. }
  56. }
  57. player =new Character();
  58. player.setTranslateX(0);
  59. player.setTranslateY(400);
  60. player.translateXProperty().addListener((obs,old,newValue)->{
  61. int offset = newValue.intValue();
  62. if(offset>640 && offset<levelWidth-640){
  63. gameRoot.setLayoutX(-(offset-640));
  64. backgroundIV.setLayoutX(-(offset-640));
  65. }
  66. });
  67. gameRoot.getChildren().add(player);
  68. appRoot.getChildren().addAll(backgroundIV,gameRoot);
  69. }
  70. private void update(){
  71. if(isPressed(KeyCode.UP) && player.getTranslateY()>=5){
  72. player.jumpPlayer();
  73. }
  74. if(isPressed(KeyCode.LEFT) && player.getTranslateX()>=5){
  75. player.setScaleX(-1);
  76. player.animation.play();
  77. player.moveX(-5);
  78. }
  79. if(isPressed(KeyCode.RIGHT) && player.getTranslateX()+40 <=levelWidth-5){
  80. player.setScaleX(1);
  81. player.animation.play();
  82. player.moveX(5);
  83. }
  84. if(player.playerVelocity.getY()<10){ //гравитаци¤
  85. player.playerVelocity = player.playerVelocity.add(0,1);
  86. }
  87. player.moveY((int)player.playerVelocity.getY());
  88. }
  89. private boolean isPressed(KeyCode key){
  90. return keys.getOrDefault(key,false);
  91. }
  92. @Override
  93. public void start(Stage primaryStage) throws Exception {
  94. initContent();
  95. Scene scene = new Scene(appRoot,1200,620);
  96. scene.setOnKeyPressed(event-> keys.put(event.getCode(), true));
  97. scene.setOnKeyReleased(event -> {
  98. keys.put(event.getCode(), false);
  99. player.animation.stop();
  100. });
  101. primaryStage.setTitle("Mini Mario");
  102. primaryStage.setScene(scene);
  103. primaryStage.show();
  104. AnimationTimer timer = new AnimationTimer() {
  105. @Override
  106. public void handle(long now) {
  107. update();
  108. }
  109. };
  110. timer.start();
  111. }
  112. public static void main(String[] args) {
  113. launch(args);
  114. }
  115. }
Листинг программы
  1. import javafx.geometry.Point2D;
  2. import javafx.geometry.Rectangle2D;
  3. import javafx.scene.Node;
  4. import javafx.scene.image.Image;
  5. import javafx.scene.image.ImageView;
  6. import javafx.scene.layout.Pane;
  7. import javafx.util.Duration;
  8.  
  9. public class Character extends Pane{
  10. Image marioImg = new Image(getClass().getResourceAsStream("mario.png"));
  11. ImageView imageView = new ImageView(marioImg);
  12. int count = 3;
  13. int columns = 3;
  14. int offsetX = 96;
  15. int offsetY = 33;
  16. int width = 16;
  17. int height = 16;
  18. public SpriteAnimation animation;
  19. public Point2D playerVelocity = new Point2D(0,0);
  20. private boolean canJump = true;
  21. public Character(){
  22. imageView.setFitHeight(40);
  23. imageView.setFitWidth(40);
  24. imageView.setViewport(new Rectangle2D(offsetX,offsetY,width,height));
  25. animation = new SpriteAnimation(this.imageView,Duration.millis(200),count,columns,offsetX,offsetY,width,height);
  26. getChildren().addAll(this.imageView);
  27. }
  28. public void moveX(int value){
  29. boolean movingRight = value > 0;
  30. for(int i = 0; i<Math.abs(value); i++) {
  31. for (Node platform : Game.platforms) {
  32. if(this.getBoundsInParent().intersects(platform.getBoundsInParent())) {
  33. if (movingRight) {
  34. if (this.getTranslateX() + Game.MARIO_SIZE == platform.getTranslateX()){
  35. this.setTranslateX(this.getTranslateX() - 1);
  36. return;
  37. }
  38. } else {
  39. if (this.getTranslateX() == platform.getTranslateX() + Game.BLOCK_SIZE) {
  40. this.setTranslateX(this.getTranslateX() + 1);
  41. return;
  42. }
  43. }
  44. }
  45. }
  46. this.setTranslateX(this.getTranslateX() + (movingRight ? 1 : -1));
  47. }
  48. }
  49. public void moveY(int value){
  50. boolean movingDown = value >0;
  51. for(int i = 0; i < Math.abs(value); i++){
  52. for(Block platform :Game.platforms){
  53. if(getBoundsInParent().intersects(platform.getBoundsInParent())){
  54. if(movingDown){
  55. if(this.getTranslateY()+ Game.MARIO_SIZE == platform.getTranslateY()){
  56. this.setTranslateY(this.getTranslateY()-1);
  57. canJump = true;
  58. return;
  59. }
  60. }
  61. else{
  62. if(this.getTranslateY() == platform.getTranslateY()+ Game.BLOCK_SIZE){
  63. this.setTranslateY(this.getTranslateY()+1);
  64. playerVelocity = new Point2D(0,10);
  65. return;
  66. }
  67. }
  68. }
  69. }
  70. this.setTranslateY(this.getTranslateY() + (movingDown?1:-1));
  71. if(this.getTranslateY()>640){
  72. this.setTranslateX(0);
  73. this.setTranslateY(400);
  74. Game.gameRoot.setLayoutX(0);
  75. }
  76. }
  77. }
  78. public void jumpPlayer(){
  79. if(canJump){
  80. playerVelocity = playerVelocity.add(0,-30);
  81. canJump = false;
  82. }
  83. }
  84. }
Листинг программы
  1. import javafx.animation.Animation;
  2. import javafx.animation.Interpolator;
  3. import javafx.animation.Transition;
  4. import javafx.geometry.Rectangle2D;
  5. import javafx.scene.image.ImageView;
  6. import javafx.util.Duration;
  7. /**
  8. * Created by ¬ладислав on 20.08.2015.
  9. */
  10. public class SpriteAnimation extends Transition{
  11. private final ImageView imageView;
  12. private final int count;
  13. private final int columns;
  14. private int offsetX;
  15. private int offsetY;
  16. private final int width;
  17. private final int height;
  18. public SpriteAnimation(
  19. ImageView imageView,
  20. Duration duration,
  21. int count, int columns,
  22. int offsetX, int offsetY,
  23. int width, int height
  24. ){
  25. this.imageView = imageView;
  26. this.count = count;
  27. this.columns = columns;
  28. this.offsetX = offsetX;
  29. this.offsetY = offsetY;
  30. this.width = width;
  31. this.height = height;
  32. setCycleDuration(duration);
  33. setCycleCount(Animation.INDEFINITE);
  34. setInterpolator(Interpolator.LINEAR);
  35. this.imageView.setViewport(new Rectangle2D(offsetX, offsetY, width, height));
  36. }
  37. public void setOffsetX(int x){
  38. this.offsetX = x;
  39. }
  40. public void setOffsetY(int y){
  41. this.offsetY = y;
  42. }
  43. protected void interpolate(double frac) {
  44. final int index = Math.min((int)Math.floor(count*frac), count-1);
  45. final int x = (index%columns)*width+offsetX;
  46. final int y = (index/columns)*height+offsetY;
  47. imageView.setViewport(new Rectangle2D(x, y, width, height));
  48. }
  49. }
Листинг программы
  1. public class LevelData {
  2. static String[] LEVEL1 =new String[]{
  3. "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  4. "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  5. "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  6. "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  7. "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  8. "00000000000000000000003000000000000000000000000000000000000000000000000000000000222222220002223000000000000003000000000002220000233200000000000000000000000000000000000000000000000000000000440000000000000000000000",
  9. "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004440000000000000000000000",
  10. "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044440000000000000000000000",
  11. "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000444440000000000000000000000",
  12. "00000000000000002000232320000000000000000000005*0000000005*000000000000000000232000000000000002000002200003003003000002000000000022000000400400000000004400400000000000022320000000000004444440000000000000000000000",
  13. "000000000000000000000000000000000000005*0000006*0000000006*000000000000000000000000000000000000000000000000000000000000000000000000000004400440000000044400440000000000000000000000000044444440000000000000000000000",
  14.  
  15. };
  16. public static String[][] levels= new String[][]{
  17. LEVEL1
  18. };
  19. }
Листинг программы
  1. import javafx.geometry.Rectangle2D;
  2. import javafx.scene.image.Image;
  3. import javafx.scene.image.ImageView;
  4. import javafx.scene.layout.Pane;
  5.  
  6. public class Block extends Pane {
  7. Image blocksImg = new Image(getClass().getResourceAsStream("1.png"));
  8. ImageView block;
  9. public enum BlockType {
  10. PLATFORM, BRICK, BONUS, PIPE_TOP, PIPE_BOTTOM, INVISIBLE_BLOCK, STONE
  11. }
  12. public Block(BlockType blockType, int x, int y) {
  13. block = new ImageView(blocksImg);
  14. block.setFitWidth(Game.BLOCK_SIZE);
  15. block.setFitHeight(Game.BLOCK_SIZE);
  16. setTranslateX(x);
  17. setTranslateY(y);
  18. switch (blockType) {
  19. case PLATFORM:
  20. block.setViewport(new Rectangle2D(0, 0, 16, 16));
  21. break;
  22. case BRICK:
  23. block.setViewport(new Rectangle2D(16, 0, 16, 16));
  24. break;
  25. case BONUS:
  26. block.setViewport(new Rectangle2D(384, 0, 16, 16));
  27. break;
  28. case PIPE_TOP:
  29. block.setViewport(new Rectangle2D(0, 128, 32, 16));
  30. block.setFitWidth(Game.BLOCK_SIZE * 2);
  31. break;
  32. case PIPE_BOTTOM:
  33. block.setViewport(new Rectangle2D(0, 145, 32, 14));
  34. block.setFitWidth(Game.BLOCK_SIZE * 2);
  35. break;
  36. case INVISIBLE_BLOCK:
  37. block.setViewport(new Rectangle2D(0, 0, 16, 16));
  38. block.setOpacity(0);
  39. break;
  40. case STONE:
  41. block.setViewport(new Rectangle2D(0, 16, 16, 16));
  42. break;
  43. }
  44. getChildren().add(block);
  45. Game.platforms.add(this);
  46. Game.gameRoot.getChildren().add(this);
  47. }
  48. }
В классе Block Нетбинс пишет ошибку "потеря this в конструкторе" на строках:
Листинг программы
  1. Game.platforms.add(this);
  2. Game.gameRoot.getChildren().add(this);
А в классе LevelData пишет "использование статических неокончательных переменных при инициализации" Посоветуйте как сделать так чтоб заработало. Заранее спасибо всем кто откликнулся.

Решение задачи: «Потеря this в конструкторе»

textual
Листинг программы
  1. public class Block extends Pane {
  2.  
  3.     private Image blocksImg = new Image(getClass().getResourceAsStream("1.png"));
  4.     private ImageView block;
  5.  
  6.     public static enum BlockType {
  7.         PLATFORM, BRICK, BONUS, PIPE_TOP, PIPE_BOTTOM, INVISIBLE_BLOCK, STONE
  8.     }
  9.  
  10.     public static Block create(BlockType blockType, int x, int y) {
  11.         Block b = new Block(blockType, x, y);
  12.         Game.platforms.add(b);
  13.         try {
  14.             Game.gameRoot.getChildren().add(b);
  15.         } catch (RuntimeException e) {
  16.             Game.platforms.remove(b);
  17.             throw e;
  18.         }
  19.         return b;
  20.     }
  21.  
  22.     protected Block(BlockType blockType, int x, int y) {
  23.         block = new ImageView(blocksImg);
  24.         block.setFitWidth(Game.BLOCK_SIZE);
  25.         block.setFitHeight(Game.BLOCK_SIZE);
  26.         setTranslateX(x);
  27.         setTranslateY(y);
  28.  
  29.         switch (blockType) {
  30.             case PLATFORM:
  31.                 block.setViewport(new Rectangle2D(0, 0, 16, 16));
  32.                 break;
  33.             case BRICK:
  34.                 block.setViewport(new Rectangle2D(16, 0, 16, 16));
  35.                 break;
  36.             case BONUS:
  37.                 block.setViewport(new Rectangle2D(384, 0, 16, 16));
  38.                 break;
  39.             case PIPE_TOP:
  40.                 block.setViewport(new Rectangle2D(0, 128, 32, 16));
  41.                 block.setFitWidth(Game.BLOCK_SIZE * 2);
  42.                 break;
  43.             case PIPE_BOTTOM:
  44.                 block.setViewport(new Rectangle2D(0, 145, 32, 14));
  45.                 block.setFitWidth(Game.BLOCK_SIZE * 2);
  46.                 break;
  47.             case INVISIBLE_BLOCK:
  48.                 block.setViewport(new Rectangle2D(0, 0, 16, 16));
  49.                 block.setOpacity(0);
  50.                 break;
  51.             case STONE:
  52.                 block.setViewport(new Rectangle2D(0, 16, 16, 16));
  53.                 break;
  54.         }
  55.         getChildren().add(block);
  56.     }
  57. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

6   голосов , оценка 3.5 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут