我正在制作蛇游戏,但每当我尝试用draw()
方法更新我的画布时,新蛇就不会画画。它引入run
线程。我尝试了很多不同的东西,但我似乎无法让它发挥作用。
进口:
import javafx.application.Application;
import javafx.event.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.geometry.*;
import java.io.*;
import java.util.*;
import javafx.scene.input.KeyEvent;
import javafx.event.EventHandler;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.*;
import javafx.scene.paint.*;
import javafx.scene.canvas.*;
实际课程:
public class Snake extends Application implements Runnable
{
//Snake parts and locations
boolean dead;
int headX=0;
int headY=0;
// for the game
Group root = new Group();
Scene snakeG = new Scene(root, 550, 550,Color.BLACK);
final Canvas canvas = new Canvas(550,550);
GraphicsContext gc = canvas.getGraphicsContext2D();
//Start Game
VBox newGame = new VBox(3);
Scene startC = new Scene(newGame, 200, 200);
Label info = new Label("Snake Game \nCreated by: Austin");
Label rules = new Label("Rules\n1.) If you hit the edge you die\n2.) If you touch your snake you die\n3.)Collect fruit to increase your snakes size");
Button startBut = new Button("Start Game");
Stage startS;
public static void main ( String[] args )
{
launch(args);
}
@Override
public void start ( Stage primaryStage )throws Exception
{
startS=primaryStage;
startS.setTitle("Snake");
newGame.getChildren().addAll(info,rules,startBut);
newGame.setAlignment(Pos.CENTER);
startS.setScene(startC);
startS.show();
startBut.setOnAction(e ->
{
startGame();
});
}
public void startGame()
{
System.out.println("Success");
headX=275;
headY=275;
dead = false;
gc.clearRect(0,0,800,800);
startS.setScene(snakeG);
gc.setFill(Color.GREEN);
gc.fillRect(headX,headY,10,10);
root.getChildren().add(canvas);
(new Thread ( new Snake())).start();
}
public void run()
{
draw();
}
// draws the snake
public void draw()
{
System.out.println("DRAW STARTED");
gc.setFill(Color.GREEN);
gc.fillRect(50,50,10,10);
}
}
如果您知道在JavaFX中绘制图形的更好方法,请告诉我。这是我能找到的唯一方法。
答案 0 :(得分:3)
您的方法存在一些问题。
您只能使用JavaFX Thread修改活动场景图(包括画布)。阅读JavaFX concurrency documentation:
JavaFX场景图表示JavaFX应用程序的图形用户界面,它不是线程安全的,只能从UI线程(也称为JavaFX Application线程)访问和修改。
Runnable
。一些建议:
SceneGraph
节点用于游戏对象而不是Canvas
更容易,但两者都应该有效。