當普通人想要學習打字時,他們會使用諸如Typing master之類的軟件 。但是程序員們可以使用他們的知識來編寫自己的打字導師應用。一如既往,Python將會是最好的選擇,因為它易于理解,并為我們的特定目的提供了很多庫。下面讓我們來看一下程序員如何使用Python制作自己的打字導師應用程序吧。為了檢查打字速度和準確性,我們需要記錄擊鍵。為此,我們將使用一個稱為tkinter的python庫。由于tkinter已從Python 3.4及更高版本內置,因此您無需使用pip進行安裝。
這個應用程式如何運作?
首先,我們將獲取許多英文字母的數據集。然后,我們將從該數據集中向用戶隨機呈現單詞。用戶必須輸入這些單詞。如果他成功鍵入一個單詞,他將得到下一個單詞。同樣,用戶將獲得特定的生命。一旦用戶輸入錯誤的字母,他將失去生命。如果他的生活結束了,比賽就結束了。而且,基于用戶鍵入特定單詞所花費的時間以及正確鍵入的字母數來計算分數。
在此項目中使用的英語單詞數據集可以在這里找到 。下載此文件并將其存儲在存在python文件的相同位置。該文件包含大約10,000個英語單詞。我們將從列表中隨機選擇給定數量的單詞。對于分數計算,每當用戶正確按下一個字母時,我們就將分數加1。還為每個單詞分配了時間限制,該時間限制是單詞長度的倍數。如果用戶在時間限制之前輸入單詞,則剩余時間將添加到得分中。
代碼展示:
import tkinter as tk
import random
from os import system, name
import time
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
index = 0
list_index = 0
list = []
word_count = 10
f = open('words.txt', 'r')
for line in f:
list.append(line.strip())
random.shuffle(list)
list = list[:word_count]
print("---WELCOME TO TYPING TUTOR---")
time.sleep(1)
clear()
print("Total words: ", len(list))
time.sleep(2)
clear()
print("Word "+str(list_index+1)+" out of "+str(word_count)+": "+list[list_index])
start_time = time.time()
end_time = 0
time_multiplier = 2
lives = 3
score = 0
def keypress(event):
global index
global list_index
global list
global lives
global score
global start_time
global end_time
global time_multiplier
word = list[list_index]
if event.char == word[index]:
index = index + 1
score = score + 1
else:
clear()
print("Word " + str(list_index + 1) + " out of " + str(word_count) + ": " + list[list_index])
print("wrong letter!")
lives = lives - 1
print("Lives left: ", lives)
if lives == 0:
print("Game Over!")
print("Final Score: ", score)
root.destroy()
return
if index == len(word):
clear()
print("right!")
index = 0
list_index = list_index + 1
end_time = time.time()
time_taken = int(end_time - start_time)
time_left = time_multiplier * len(word) - time_taken
score = score + time_left
print("time taken: " + str(time_taken) + " out of " + str(time_multiplier*len(word)) + " seconds.")
print("Current score: ", score)
time.sleep(1.5)
start_time = end_time
clear()
if list_index < len(list) and index == 0:
print("Word " + str(list_index + 1) + " out of " + str(word_count) + ": " + list[list_index])
elif list_index == len(list):
clear()
print("Congratulations! you have beaten the game!")
print("Final Score: ", score)
root.destroy()
root = tk.Tk()
root.bind_all('', keypress)
root.withdraw()
root.mainloop()
這段代碼復制到一個新的Python文件并將它命名為 app.py。可以使用以下命令設置游戲中顯示的單詞總數 word_count 變量。當前設置為100。 time_multiplier 變量控制分配給每個單詞的時間。當前設置為2。這意味著對于長度為5的單詞,時間限制為5 * 2 = 10秒。lives 變量定義玩家的生命數量。每當玩家錯誤地鍵入字母時,生命都會過去。
要運行此代碼,請打開命令提示符,將目錄更改為該python文件的存儲位置,然后鍵入: python app.py
請注意,運行此代碼后,命令提示符將不會保留為活動窗口。您不必擔心。只需開始輸入顯示的單詞的字母即可。當您繼續正確輸入時,樂譜將更新,接下來的單詞將繼續出現。另外,您實際上不會在屏幕上的任何地方看到要鍵入的單詞。您只需要繼續按正確的鍵即可。每當您按下任何不正確的鍵時,都會扣除生命。
通過上述介紹,如何使用Python制作自己的打字導師應用程序相信大家也已經知曉了吧,想了解更多關于Python的信息,請繼續關注中培偉業。