본문 바로가기

자바(java)

타자 연습 게임: 랜덤 단어를 화면에 표시하고 사용자의 타자 속도를 측정하는 게임을 개발합니다.

반응형

1. 내용 설명

타자 연습 게임은 사용자가 화면에 표시된 랜덤 단어를 타이핑하여 타자 속도를 측정하는 게임입니다. 사용자는 제한 시간 내에 가능한 많은 단어를 정확하게 입력해야 합니다. 입력된 단어가 화면에 표시된 단어와 일치할 경우, 새로운 단어가 나타납니다.

2. 프로그램 간 사용 함수 설명

  • createAndShowGUI(): GUI 컴포넌트를 생성하고 표시합니다.
  • startGame(): 게임을 시작하고 타이머를 설정합니다.
  • generateWord(): 랜덤 단어를 생성하고 화면에 표시합니다.
  • checkInput(): 사용자 입력을 확인하고 점수를 업데이트합니다.

3. 코딩 내용

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

public class TypingGame {
    private JFrame frame;
    private JLabel wordLabel, timerLabel, scoreLabel;
    private JTextField inputField;
    private String[] words = {"apple", "banana", "cherry", "date", "elderberry"};
    private int score = 0, timeLeft = 30;
    private Timer timer;

    public TypingGame() {
        createAndShowGUI();
    }

    private void createAndShowGUI() {
        frame = new JFrame("Typing Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());

        wordLabel = new JLabel("Word");
        frame.add(wordLabel);

        inputField = new JTextField(20);
        inputField.addActionListener(e -> checkInput());
        frame.add(inputField);

        timerLabel = new JLabel("Time: " + timeLeft);
        frame.add(timerLabel);

        scoreLabel = new JLabel("Score: " + score);
        frame.add(scoreLabel);

        frame.pack();
        frame.setVisible(true);

        startGame();
    }

    private void startGame() {
        generateWord();
        timer = new Timer(1000, e -> updateTimer());
        timer.start();
    }

    private void generateWord() {
        Random random = new Random();
        String word = words[random.nextInt(words.length)];
        wordLabel.setText(word);
    }

    private void checkInput() {
        String userInput = inputField.getText();
        if (userInput.equalsIgnoreCase(wordLabel.getText())) {
            score++;
            scoreLabel.setText("Score: " + score);
            generateWord();
        }
        inputField.setText("");
    }

    private void updateTimer() {
        timeLeft--;
        if (timeLeft <= 0) {
            timer.stop();
            JOptionPane.showMessageDialog(frame, "Game Over! Your score: " + score);
            frame.dispose();
        }
        timerLabel.setText("Time: " + timeLeft);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new TypingGame());
    }
}

 

4. 전문용어

  • JFrame: 자바 Swing에서 사용되는 창 프레임입니다.
  • JLabel: 텍스트 레이블을 표시하는 컴포넌트입니다.
  • JTextField: 사용자 입력을 받을 수 있는 텍스트 필드입니다.
  • Timer: 정해진 시간마다 액션 이벤트를 발생시키는 스윙 타이머입니다.
  • Random: 랜덤한 숫자를 생성하는 자바 유틸리티 클래스입니다.

5. 라이브러리 추가 및 실행 방법

  • 본 프로그램은 자바 표준 라이브러리의 Swing 컴포넌트를 사용합니다.

컴파일:
javac TypingGame.java


실행:
java TypingGame

반응형