我制作了一个蛇形游戏(通过尝试遵循youtuber的代码),方向由WASD控制。但是,当我按其中一个键时,什么也没发生。如果我按住它,它会改变方向,但是会有很大的延迟,可能超过一秒钟。我该如何解决?我查看了一下我的代码,并将其与我多次遵循的youtube代码进行了比较,但似乎仍然看不到问题所在。这是我第一次玩游戏,所以我对此很陌生。
这是我尝试播放的视频,如果有帮助的话。
https://www.youtube.com/watch?v=nK6l1uVlunc
package app;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.shape.Rectangle;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage; // Kontrollerer tittel, ikon, synlighet, størrelse, og dekorasjoner
import javafx.util.Duration;
public class App extends Application {
public enum Direction {
UP, DOWN, RIGHT, LEFT;
}
public static final int BLOCK_SIZE = 40;
public static final int APP_W = 20 * BLOCK_SIZE;
public static final int APP_H = 15 * BLOCK_SIZE;
public int score = 0;
public int highScore = 0;
private Direction direction = Direction.RIGHT; // Default spawn-bevegelse: til høyre
private boolean moved = false;
private boolean running = false; // Applikasjonen kjører
private Timeline timeline = new Timeline();
private ObservableList<Node> snake;
private Parent createContent() {
Pane root = new Pane();
root.setPrefSize(APP_W, APP_H);
Group snakeBody = new Group();
snake = snakeBody.getChildren();
Rectangle food = new Rectangle(BLOCK_SIZE, BLOCK_SIZE);
food.setFill(Color.RED);
food.setTranslateX((int)(Math.random() * (APP_W - BLOCK_SIZE)) / BLOCK_SIZE * BLOCK_SIZE);
food.setTranslateY((int)(Math.random() * (APP_H - BLOCK_SIZE)) / BLOCK_SIZE * BLOCK_SIZE);
KeyFrame frame = new KeyFrame(Duration.seconds(0.5), event -> {
if (!running)
return;
boolean toRemove = snake.size() > 1;
Node tail = toRemove ? snake.remove(snake.size()-1) : snake.get(0);
double tailX = tail.getTranslateX();
double tailY = tail.getTranslateY();
switch (direction) {
case UP:
tail.setTranslateX(snake.get(0).getTranslateX());
tail.setTranslateY(snake.get(0).getTranslateY() - BLOCK_SIZE);
break;
case DOWN:
tail.setTranslateX(snake.get(0).getTranslateX());
tail.setTranslateY(snake.get(0).getTranslateY() + BLOCK_SIZE);
break;
case RIGHT:
tail.setTranslateX(snake.get(0).getTranslateX() + BLOCK_SIZE);
tail.setTranslateY(snake.get(0).getTranslateY());
break;
case LEFT:
tail.setTranslateX(snake.get(0).getTranslateX() - BLOCK_SIZE);
tail.setTranslateY(snake.get(0).getTranslateY());
break;
}
moved = true;
if (toRemove)
snake.add(0, tail);
// Kollisjonsdeteksjon
// Krasjer i seg selv
for (Node rect : snake) {
if (rect != tail && tail.getTranslateX() == rect.getTranslateX() && tail.getTranslateY() == rect.getTranslateY()) {
restartGame();
break;
}
}
// Krasjer i kant
if (tail.getTranslateX() < 0 || tail.getTranslateX() >= APP_W || tail.getTranslateY() < 0 || tail.getTranslateY() >= APP_H) {
restartGame();
}
// Legg til mat
if (tail.getTranslateX() == food.getTranslateX() && tail.getTranslateY() == food.getTranslateY()) {
food.setTranslateX((int)(Math.random() * (APP_W - BLOCK_SIZE)) / BLOCK_SIZE * BLOCK_SIZE);
food.setTranslateY((int)(Math.random() * (APP_H - BLOCK_SIZE)) / BLOCK_SIZE * BLOCK_SIZE);
Rectangle rect = new Rectangle(BLOCK_SIZE, BLOCK_SIZE);
rect.setTranslateX(tailX);
rect.setTranslateY(tailY);
snake.add(rect);
}
});
timeline.getKeyFrames().add(frame);
timeline.setCycleCount(Timeline.INDEFINITE);
root.getChildren().addAll(food, snakeBody);
return root;
}
private void restartGame() {
stopGame();
startGame();
}
private void stopGame() {
running = false;
timeline.stop();
snake.clear();
}
private void startGame() {
direction = Direction.RIGHT;
Rectangle head = new Rectangle(BLOCK_SIZE, BLOCK_SIZE);
snake.add(head);
timeline.play();
running = true;
}
@Override
public void start(final Stage primaryStage) throws Exception {
// primaryStage.setTitle("My Application");
// primaryStage.setScene(new Scene(FXMLLoader.load(App.class.getResource("App.fxml"))));
// primaryStage.show();
Scene scene = new Scene(createContent());
scene.setOnKeyPressed(event -> {
if (!moved)
switch (event.getCode()) {
case W:
if (direction != Direction.DOWN)
direction = Direction.UP;
break;
case S:
if (direction != Direction.UP)
direction = Direction.DOWN;
break;
case A:
if (direction != Direction.RIGHT)
direction = Direction.LEFT;
break;
case D:
if (direction != Direction.LEFT)
direction = Direction.RIGHT;
break;
default:
break;
}
moved = false;
});
primaryStage.setTitle("Snake");
primaryStage.setScene(scene);
primaryStage.show();
startGame();
}
public static void main(final String[] args) {
App.launch(args); // Kaller init(), start() og så stop()
}
}
答案 0 :(得分:3)
我发现您的代码与教程中的代码有所不同。
if (!moved)
return;
switch (event.getCode()) {
.
.
.
}
moved = false;
在您的代码中,缺少if(!moved)之后的return语句。我尝试将其添加到代码中,然后对我有用。
希望能解决您的问题。 麦尔干杯
答案 1 :(得分:1)
问题在于,每次触发KeyFrame
时,您都会重置moved
标志。这要求用户在帧之间至少触发2个KEY_PRESSED
事件,以获取更改方向。
假设要防止用户在第一帧之前更改方向,则应在if
条件下删除否定项。 (根据您要使用该标志尝试实现的目标,可能需要使用其他修复程序。)
scene.setOnKeyPressed(event -> {
if (moved) {
switch (event.getCode()) {
case W:
if (direction != Direction.DOWN)
direction = Direction.UP;
break;
case S:
if (direction != Direction.UP)
direction = Direction.DOWN;
break;
case A:
if (direction != Direction.RIGHT)
direction = Direction.LEFT;
break;
case D:
if (direction != Direction.LEFT)
direction = Direction.RIGHT;
break;
default:
break;
}
}
});
通过使用Map
并将属性添加到Direction
枚举中,您还可以在代码方面进行一些改进。
public enum Direction {
UP(0, -1), RIGHT(1, 0), DOWN(0, 1), LEFT(-1, 0);
private final int dx;
private final int dy;
private Direction(int dx, int dy) {
this.dx = dx;
this.dy = dy;
}
/**
* Tests, if 2 directions are parallel (i.e. both either on the x or the y axis).<br>
* Note: Depends on the order of the enum constants
* @param other the direction to compare with
* @return true, if the directions are parallel, false otherwise
*/
public boolean isParallel(Direction other) {
return ((ordinal() - other.ordinal()) & 1) == 0;
}
}
在KeyFrame
...
double tailX = tail.getTranslateX();
double tailY = tail.getTranslateY();
Node head = snake.get(0);
tail.setTranslateX(head.getTranslateX() + BLOCK_SIZE * direction.dx);
tail.setTranslateY(head.getTranslateY() + BLOCK_SIZE * direction.dy);
moved = true;
...
final Map<KeyCode, Direction> keyMapping = new EnumMap<>(KeyCode.class);
keyMapping.put(KeyCode.W, Direction.UP);
keyMapping.put(KeyCode.S, Direction.DOWN);
keyMapping.put(KeyCode.A, Direction.LEFT);
keyMapping.put(KeyCode.D, Direction.RIGHT);
Scene scene = new Scene(createContent());
scene.setOnKeyPressed(event -> {
if (moved) {
Direction newDirection = keyMapping.get(event.getCode());
if (newDirection != null && !direction.isParallel(newDirection)) {
direction = newDirection;
}
}
});