Import Java

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

import java.awt.

Rectangle;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

public class CarGameGUI {

JFrame fr;

JPanel carPanel;

CarHandler hnd;

JLabel background;

JLabel playerCarLabel;

JLabel otherCarLabel;

int speed;

private ImageIcon car1;

private ImageIcon car2;

private boolean gameStarted;

public CarGameGUI() {

speed = 10; // Menurunkan kecepatan agar permainan tidak terlalu cepat

hnd = new CarHandler(this);

gameStarted = false;

initGUI();

private void initGUI() {

fr = new JFrame("Car Game");


fr.setLayout(null);

background = new JLabel("", new ImageIcon("jalan.gif"), JLabel.CENTER);

background.setBounds(0, 0, 500, 700);

fr.add(background);

carPanel = new JPanel();

carPanel.setSize(80, 168);

carPanel.setLocation(150, 400);

car1 = new ImageIcon("thirdCar.png");

playerCarLabel = new JLabel(car1);

playerCarLabel.setVisible(false);

playerCarLabel.setSize(180, 180);

carPanel.add(playerCarLabel);

car2 = new ImageIcon("secondCar.png");

otherCarLabel = new JLabel(car2);

otherCarLabel.setBounds(200, 100, 80, 168);

otherCarLabel.setVisible(false);

otherCarLabel.setSize(240, 240);

background.add(otherCarLabel);

background.add(carPanel);

JButton startButton = new JButton("Start");

startButton.setBounds(200, 350, 100, 30);

startButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (!gameStarted) {

gameStarted = true;
JOptionPane.showMessageDialog(fr, "Game started!");

playerCarLabel.setVisible(true);

otherCarLabel.setVisible(true);

fr.requestFocus();

background.remove(startButton);

fr.validate();

new Thread(() -> {

while (gameStarted) {

Rectangle playerBounds = playerCarLabel.getBounds();

Rectangle otherCarBounds = otherCarLabel.getBounds();

if (playerBounds.intersects(otherCarBounds)) {

JOptionPane.showMessageDialog(fr, "Game Over! You crashed!");

gameStarted = false;

otherCarLabel.setLocation(200, 100); // Atur ulang posisi mobil kedua

int currentY = otherCarLabel.getY();

int newY = currentY + speed;

if (newY >= fr.getHeight()) {

newY = -otherCarLabel.getHeight(); // Reset posisi mobil kedua

otherCarLabel.setLocation(newY, otherCarLabel.getY());

try {

Thread.sleep(20);

} catch (InterruptedException ex) {

ex.printStackTrace();

}
}

}).start();

});

background.add(startButton);

fr.setSize(500, 700);

fr.setVisible(true);

fr.setResizable(false);

fr.setLocationRelativeTo(null);

fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

fr.addKeyListener(hnd);

public static void main(String[] args) {

new CarGameGUI();

You might also like