Game using JavaFX

This game creates a window with a player (represented by a red circle) that can be moved with the arrow keys. The player cannot move outside of the window, and the background color is set to light blue. You can modify the constants to customize the game to your liking.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class SimpleGame extends Application {
    
    private static final int WIDTH = 600;
    private static final int HEIGHT = 400;
    private static final Color BACKGROUND_COLOR = Color.LIGHTBLUE;
    private static final Color PLAYER_COLOR = Color.DARKRED;
    private static final int PLAYER_SIZE = 20;
    private static final int PLAYER_SPEED = 5;
    
    private Canvas canvas;
    private GraphicsContext gc;
    private int playerX;
    private int playerY;
    
    @Override
    public void start(Stage primaryStage) throws Exception {
        canvas = new Canvas(WIDTH, HEIGHT);
        gc = canvas.getGraphicsContext2D();
        playerX = WIDTH / 2;
        playerY = HEIGHT / 2;
        
        StackPane root = new StackPane();
        root.getChildren().add(canvas);
        Scene scene = new Scene(root, WIDTH, HEIGHT, BACKGROUND_COLOR);
        scene.setOnKeyPressed(event -> handleKeyPress(event.getCode()));
        primaryStage.setScene(scene);
        primaryStage.show();
        
        drawPlayer();
    }
    
    private void drawPlayer() {
        gc.setFill(PLAYER_COLOR);
        gc.fillOval(playerX, playerY, PLAYER_SIZE, PLAYER_SIZE);
    }
    
    private void movePlayer(int deltaX, int deltaY) {
        if (playerX + deltaX >= 0 && playerX + deltaX <= WIDTH - PLAYER_SIZE) {
            playerX += deltaX;
        }
        if (playerY + deltaY >= 0 && playerY + deltaY <= HEIGHT - PLAYER_SIZE) {
            playerY += deltaY;
        }
        gc.clearRect(0, 0, WIDTH, HEIGHT);
        drawPlayer();
    }
    
    private void handleKeyPress(KeyCode keyCode) {
        switch (keyCode) {
            case UP:
                movePlayer(0, -PLAYER_SPEED);
                break;
            case DOWN:
                movePlayer(0, PLAYER_SPEED);
                break;
            case LEFT:
                movePlayer(-PLAYER_SPEED, 0);
                break;
            case RIGHT:
                movePlayer(PLAYER_SPEED, 0);
                break;
        }
    }
    
    public static void main(String[] args) {
        launch(args);
    }

}

Leave a Reply