溫馨提示×

能否分享java racing的游戲案例

小樊
81
2024-09-25 17:32:31
欄目: 編程語言

當然可以!這里有一個簡單的Java賽車游戲案例,它使用Swing庫創(chuàng)建了一個基本的圖形用戶界面。這個游戲允許兩個玩家在一條直線上駕駛汽車。

首先,確保你已經(jīng)安裝了Java開發(fā)工具包(JDK)。然后,創(chuàng)建一個新的Java項目,并將以下代碼保存為RacingGame.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class RacingGame extends JFrame {
    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;
    private static final int CAR_WIDTH = 100;
    private static final int CAR_HEIGHT = 50;
    private static final int TRACK_LENGTH = 1000;
    private static final int CAR_SPEED = 5;
    private static final int CARS = 2;
    private static final int POSITION_OFFSET = CAR_WIDTH / 2;

    private JPanel trackPanel;
    private Car[] cars;
    private int[] carPositions;

    public RacingGame() {
        setTitle("Java Racing Game");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        trackPanel = new JPanel();
        trackPanel.setPreferredSize(new Dimension(TRACK_LENGTH, HEIGHT));
        add(trackPanel, BorderLayout.CENTER);

        cars = new Car[CARS];
        carPositions = new int[CARS];

        for (int i = 0; i < CARS; i++) {
            cars[i] = new Car(i);
            add(cars[i], BorderLayout.SOUTH);
        }

        JButton startButton = new JButton("Start");
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startRace();
            }
        });

        add(startButton, BorderLayout.NORTH);

        setVisible(true);
    }

    private void startRace() {
        for (int i = 0; i < CARS; i++) {
            carPositions[i] = 0;
            cars[i].start();
        }
    }

    private class Car extends JPanel implements Runnable {
        private int id;
        private int position;
        private Thread thread;
        private int speed;

        public Car(int id) {
            this.id = id;
            position = 0;
            speed = CAR_SPEED;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.BLUE);
            g.fillRect(position, 0, CAR_WIDTH, CAR_HEIGHT);
        }

        public void start() {
            thread = new Thread(this);
            thread.start();
        }

        @Override

0