Open In App
Related Articles

Simple Keyboard Racing with Python

Like Article
Save Article
Report issue

Let’s make a simple keyboard racing game using Python. In the game, the participant clicks a pair of keys in quick succession and the program shows the total time taken by the racer to cover the distance.

As soon as you see ‘GO!’ on screen, start pressing the keys ‘z’ and ‘x’. A ‘*’ sign is shown for every meter covered. Pressing ‘z’ and ‘x’ once will be counted as 1 meter; targets is to cover 10 meters.

Modules Used: 

msvcrt : Used to get keystroke as input for race
time : Used to calculate time taken to complete the race

Note that MSVCRT module can only function on a terminal window, not on a GUI program/IDE.

Below is the code:  


import msvcrt
import time
high_score = 17.78
name = "GeeksforGeeks"
while True:
    distance = int(0)
    print('\n\nWelcome to the 100m sprint, tap z and x rapidly to move!')
    print('* = 10m')
    print('\nCurrent record:' + str(high_score) + ' by: ' + name)
    print('\nPress enter to start')
    start_time = time.time()
    while distance < 10:
        k1 = msvcrt.getch().decode('ASCII')
        if k1 == 'z':
            k2 = msvcrt.getch().decode('ASCII')
            if k2 == 'x':
                distance += 1
                if distance == 5:
                    print("* You're halfway there!")
                elif distance % 1 == 0:
    fin_time = time.time() - start_time
    fin_time = round(fin_time, 2)
    print('Congratulations on successfully completing the race!')
    print('You took', fin_time, 'seconds to reach the finish line')
    if fin_time < high_score:
        print("Well done you've got a new high score ")
        name = input("Please enter your name : ")
        high_score = fin_time



Game Initiate

Game in Progress

Game Finished: New High Score


Last Updated : 21 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads