반응형
[Python & PyQt5] 파이큐티를 활용하여 타자게임 만드는 방법 !! #2
안녕하세요. pyqt5 라이브러리를 활용하여 간단한 타자게임을 만들기 시리즈 입니다.
추가 사항
- 게임시작버튼
- 종료시간입력 기능
예제코드
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton
from PyQt5.QtCore import QTimer
class TypingGame(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
self.currentWord = ''
self.gameStarted = False
def initUI(self):
self.layout = QVBoxLayout()
self.timeInputLine = QLineEdit(self)
self.timeInputLine.setPlaceholderText('Enter game time in seconds')
self.layout.addWidget(self.timeInputLine)
self.startButton = QPushButton('Start Game', self)
self.startButton.clicked.connect(self.startGame)
self.layout.addWidget(self.startButton)
self.wordLabel = QLabel('Start typing...', self)
self.layout.addWidget(self.wordLabel)
self.inputLine = QLineEdit(self)
self.inputLine.returnPressed.connect(self.checkWord)
self.layout.addWidget(self.inputLine)
self.setLayout(self.layout)
self.setWindowTitle('Typing Game')
self.show()
self.gameTimer = QTimer(self)
self.wordTimer = QTimer(self)
self.wordTimer.timeout.connect(self.newWord)
def startGame(self):
if not self.gameStarted:
gameTime = int(self.timeInputLine.text()) * 1000 # Convert seconds to milliseconds
self.gameTimer.singleShot(gameTime, self.endGame) # Set the game timer
self.wordTimer.start(5000) # Change words every 5 seconds
self.newWord()
self.gameStarted = True
self.startButton.setDisabled(True)
self.timeInputLine.setDisabled(True)
def newWord(self):
import random
self.currentWord = random.choice(self.words)
self.wordLabel.setText(self.currentWord)
def checkWord(self):
if self.inputLine.text() == self.currentWord:
self.newWord()
self.inputLine.clear()
def endGame(self):
self.wordTimer.stop()
self.wordLabel.setText('Game Over!')
self.gameStarted = False
self.startButton.setDisabled(False)
self.timeInputLine.setDisabled(False)
self.inputLine.clear()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = TypingGame()
sys.exit(app.exec_())
코드 변경사항
결과
728x90
반응형
'Coding > Python' 카테고리의 다른 글
[Python] 파이썬에서 영어가 아닌 단어 찾는 방법 !! (0) | 2024.02.14 |
---|---|
[Python & PyQt5] 파이큐티를 활용하여 타자게임 만드는 방법 !! #3 (2) | 2024.02.07 |
[Python & PyQt5] 파이큐티를 활용하여 타자게임 만드는 방법 !! #1 (0) | 2024.01.31 |
[Python] 파이썬 리스트안에 있는 단어들 갯수(빈도수) 구하는 방법 !! (Counter 함수 사용) (1) | 2024.01.29 |
[Python & PyQt5] 파이큐티를 활용하여 로또번호 추천해주는 프로그램 만드는 방법 !! (0) | 2024.01.28 |
댓글