Love Collector: A Fun Game to Collect Hearts
import javax.swing.; import java.awt.; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random;
public class LoveCollector extends JFrame implements ActionListener { private final int SCREEN_WIDTH = 500; private final int SCREEN_HEIGHT = 500; private final int BOY_SIZE = 50; private final int HEART_SIZE = 30; private final int BIG_HEART_SIZE = 100; private final int TOTAL_HEARTS = 13; private final int HEARTS_TO_WIN = 12;
private JButton boy;
private JButton heart;
private JButton bigHeart;
private int collectedHearts;
private Random random;
public LoveCollector() {
setTitle('Love Collector');
setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
Container container = getContentPane();
container.setLayout(null);
boy = new JButton(new ImageIcon('D:/ai.jpg'));
boy.setBounds(0, 0, BOY_SIZE, BOY_SIZE);
container.add(boy);
heart = new JButton(new ImageIcon('D:/ai.jpg'));
heart.setBounds(getRandomX(), getRandomY(), HEART_SIZE, HEART_SIZE);
heart.addActionListener(this);
container.add(heart);
bigHeart = new JButton(new ImageIcon('D:/ai.jpg'));
bigHeart.setBounds(SCREEN_WIDTH / 2 - BIG_HEART_SIZE / 2, SCREEN_HEIGHT / 2 - BIG_HEART_SIZE / 2,
BIG_HEART_SIZE, BIG_HEART_SIZE);
bigHeart.setVisible(false);
container.add(bigHeart);
collectedHearts = 0;
random = new Random();
Timer timer = new Timer(1000, this);
timer.start();
}
private int getRandomX() {
return random.nextInt(SCREEN_WIDTH - HEART_SIZE);
}
private int getRandomY() {
return random.nextInt(SCREEN_HEIGHT - HEART_SIZE);
}
private void generateNewHeart() {
heart.setBounds(getRandomX(), getRandomY(), HEART_SIZE, HEART_SIZE);
heart.setVisible(true);
}
private void showBigHeart() {
bigHeart.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == heart) {
collectedHearts++;
if (collectedHearts == HEARTS_TO_WIN) {
generateNewHeart();
showBigHeart();
} else if (collectedHearts > HEARTS_TO_WIN) {
JOptionPane.showMessageDialog(this, 'Game Over!');
System.exit(0);
} else {
generateNewHeart();
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
LoveCollector loveCollector = new LoveCollector();
loveCollector.setVisible(true);
});
}
}
原文地址: https://www.cveoy.top/t/topic/1am 著作权归作者所有。请勿转载和采集!