Typing Game with Python and Turtle (Source Code Included)

Develop a typing game to improve keyboard skill as demonstrated in the following YouTube video.

Typing Game with Python and Turtle
Typing Game with Python and Turtle

At any moment ten random letters fall from the top of screen. When you hit a correct letter from keyboard, that letter disappears and is replaced by a new random letter dropping from the top. Also, your score will increase by 1. When you hit an incorrect letter, your score will decrease by 1.

Make these letters fall at random speeds and also let the speed increase gradually as time progresses. The game will end when a letter falls to the bottom of the screen.

You will need to use Turtle’s ontimer() and onkey() events to implement this project.

Source Code:

import turtle
import random

screen = turtle.Screen()
screen.setup(1000,1000)
screen.title('Typing Game - PythonTurtle.Academy')
screen.bgcolor('blue')
screen.tracer(0,0)
turtle.hideturtle()
turtle.up()
turtle.color('red')
score_turtle = turtle.Turtle()
score_turtle.color('red')
score_turtle.up()
score_turtle.hideturtle()
turtle.goto(350,400)
turtle.write('Score: ', align='center', font=('Courier',25,'normal'))

min_speed = 5
max_speed = 30
letters = []
speeds = []
pos = []
lts = []
n = 10
game_over = False
score = 0

def increase_difficulty():
    global min_speed, max_speed
    min_speed += 1
    max_speed += 1
    screen.ontimer(increase_difficulty,5000)

def draw_game_over():
    turtle.goto(0,0)
    turtle.color('red')
    turtle.write('GAME OVER', align='center', font=('Courier',50,'normal'))
    turtle.goto(0,-150)
    turtle.color('orange')
    turtle.write('Your Score is {}'.format(score), align='center', font=('Courier',40,'normal'))
    screen.update()

def draw_score():
    score_turtle.clear()
    score_turtle.goto(420,400)
    score_turtle.write('{}'.format(score),align='center',font=('Courier',25,'normal'))
    screen.update()
    
def draw_letters():
    global game_over
    for i in range(len(letters)):
        lts[i].clear()
        lts[i].goto(pos[i])
        lts[i].write(letters[i],align='center',font=('courier',20,'normal'))
        pos[i][1] -= speeds[i]
        if pos[i][1]<-500:
            game_over = True
            draw_game_over()
            return
    screen.update()
    screen.ontimer(draw_letters,50)

def f(c): # handle keyboard press
    global score
    if c in letters:
        score += 1
        k = letters.index(c)
        while True:
            l = chr(ord('a')+random.randrange(26))
            if l not in letters:
                letters[k] = l
                break            
        pos[k] = [random.randint(-450,450),500]        
        speeds[k] = random.randint(min_speed,max_speed)
    else: score -= 1
    draw_score()
        
for _ in range(n):
    lts.append(turtle.Turtle())
    while True:
        l = chr(ord('a')+random.randrange(26))
        if l not in letters:
            letters.append(l)
            break
    speeds.append(random.randint(min_speed,max_speed))
    pos.append([random.randint(-450,450),500])
    
for i in range(n):
    lts[i].speed(0)
    lts[i].hideturtle()
    lts[i].up()
    lts[i].color('yellow')
    
draw_letters()
increase_difficulty()

screen.onkey(lambda: f('a'), 'a')
screen.onkey(lambda: f('b'), 'b')
screen.onkey(lambda: f('c'), 'c')
screen.onkey(lambda: f('d'), 'd')
screen.onkey(lambda: f('e'), 'e')
screen.onkey(lambda: f('f'), 'f')
screen.onkey(lambda: f('g'), 'g')
screen.onkey(lambda: f('h'), 'h')
screen.onkey(lambda: f('i'), 'i')
screen.onkey(lambda: f('j'), 'j')
screen.onkey(lambda: f('k'), 'k')
screen.onkey(lambda: f('l'), 'l')
screen.onkey(lambda: f('m'), 'm')
screen.onkey(lambda: f('n'), 'n')
screen.onkey(lambda: f('o'), 'o')
screen.onkey(lambda: f('p'), 'p')
screen.onkey(lambda: f('q'), 'q')
screen.onkey(lambda: f('r'), 'r')
screen.onkey(lambda: f('s'), 's')
screen.onkey(lambda: f('t'), 't')
screen.onkey(lambda: f('u'), 'u')
screen.onkey(lambda: f('v'), 'v')
screen.onkey(lambda: f('w'), 'w')
screen.onkey(lambda: f('x'), 'x')
screen.onkey(lambda: f('y'), 'y')
screen.onkey(lambda: f('z'), 'z')

screen.listen()
screen.mainloop()

One to Ten (Source Code)

Draw from a single point to ten points that fall into a single line. Also draw dots on the end points.

One to Ten

Source Code:

import turtle

turtle.setup(1000,1000)
turtle.title('One to Ten - PythonTurtle.Academy')
turtle.speed(0)
turtle.hideturtle()

turtle.color('green')

turtle.up()
turtle.goto(0,250)
turtle.dot('red')
for x in range(-450,460,100):
    turtle.up()
    turtle.goto(0,250)
    turtle.down()
    turtle.goto(x,-250)
    turtle.dot('blue')

Real Stock Price Chart with Moving Averages (Source Code)

In a previous project we draw real stock price charts by reading data from files. We also draw stock moving averages in this project. Download historical stock prices for GoogleApple, and SPY and draw 20-day and 50-day moving averages for the last 1000 trading days.

20-day and 50-day moving averages for AAPL
20-day and 50-day moving averages for GOOGL
20-day and 50-day moving averages for SPY

Source Code:

import turtle

with open('googl.us.txt','r') as fin:
    lines = fin.readlines()
n = min(len(lines)-1,1000)
lines = lines[-n:]
prices = [None]*n
mva1 = [None]*n
mva2 = [None]*n
p1 = 20
p2 = 50

for i in range(1,n+1):
    row = lines[i-1].split(',')
    prices[i-1] = float(row[4])
    mva1[i-1] = sum(prices[max(0,i-p1):i])/min(p1,i)
    mva2[i-1] = sum(prices[max(0,i-p2):i])/min(p2,i)
minprice, maxprice = min(prices),max(prices)

screen = turtle.Screen()
screen.title('Stock Price and Moving Averages From File - PythonTurtle.Academy')
screen.setup(1000,1000)
screen.setworldcoordinates(0,minprice*0.9,n,maxprice*1.1)

turtle.speed(0)
turtle.hideturtle()
turtle.color('gray')
turtle.up()
turtle.goto(0,prices[0])
turtle.down()
tm1 = turtle.Turtle()
tm2 = turtle.Turtle()
tm1.hideturtle()
tm2.hideturtle()
tm1.color('red')
tm2.color('blue')
tm1.up()
tm1.goto(0,mva1[0])
tm1.down()
tm2.up()
tm2.goto(0,mva2[0])
tm2.down()
for i in range(1,n):
    turtle.goto(i,prices[i])
    tm1.goto(i,mva1[i])
    tm2.goto(i,mva2[i])

Real Stock Price Chart (GOOG, AAPL, SPY) with Source Code

Download historical stock prices for Google, Apple, and SPY. Read the file and draw the stock charts for these companies. The following figures show the stock prices for these companies:

Stock Price Chart of GOOG from 2004 to 2016
Stock Price Chart of AAPL from 1984 to 2016
Stock Price Chart of SPY from 2005 to 2016

Source Code:

import turtle

with open('spy.us.txt','r') as fin:
    lines = fin.readlines()
n = len(lines)-1
prices = [None]*n
for i in range(1,len(lines)):
    row = lines[i].split(',')
    prices[i-1] = float(row[4])
minprice, maxprice = min(prices),max(prices)

screen = turtle.Screen()
screen.title('Stock Price From File - PythonTurtle.Academy')
screen.setup(1000,1000)
screen.setworldcoordinates(0,minprice*0.9,n,maxprice*1.1)
turtle.speed(0)
turtle.hideturtle()
turtle.up()
turtle.goto(0,prices[0])
turtle.down()
for i in range(1,n):
    turtle.goto(i,prices[i])

Stock Price Random Walk with Moving Averages

Moving averages can smooth out the stock prices and reduce the randomness. Based on the previous projects (stock price random walk with candlestick chart, and trending stock price random walk with candlestick chart), add 10 day and 25 day moving averages to the charts.

Stock Price Random Walk with Moving Averages
Trending Stock Price Random Walk with Moving Averages
Trending Stock Price Random Walk with Moving Averages