3 minutes
Flash cards using pygame
Flash Cards
I am currently enrolled in a spanish class for beginners at the local community college. So, the other day one of the classmates who sits next to me asked if I was using flash cards
to memorize the words. I mentioned that since I am pretty much in front of a computer all day, I will write a simple program to simulate a flash card.
Today, I embarked upon writing the very first version of my flash card
application using pygame. It’s a pretty simple program that reads a list of words from a text file and displays them in a small flash card sized window. It moves between the next and previous words using the Left/Right arrow keys. The translation between english and spanish can be toggled using the Up/Down arrow keys.
import pygame
from pygame.locals import *
import sys
import time
WINWIDTH = 800
WINHEIGHT = 300
HALF_WINWIDTH = int(WINWIDTH / 2)
RUNNING = 1
BGCOLOR = BRIGHTBLUE = (0, 170, 255)
TEXTCOLOR = WHITE = (255, 255, 255)
MEANINGCOLOR = MCOLOR = (85, 65, 0)
def main():
global MAINSURF, BASICFONT, MAINCLOCK
pygame.init()
MAINCLOCK = pygame.time.Clock()
MAINSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT))
pygame.display.set_caption('Lingua Flash Card')
BASICFONT = pygame.font.Font('freesansbold.ttf', 36)
topCoord = 50
spanishText = []
englishText = []
file = open("lesson1.txt")
for line in file:
es_text, en_text = line.split(":")
spanishText.append(es_text.strip())
englishText.append(en_text.strip())
list_len = len(spanishText)
# These lists will hold the Pygame Surface and Rect objects of the text.
instSpanishSurfs = []
instEnglishSurfs = []
instRects = []
# Render the text and get the Pygame Surface and Rect objects of the text.
for i in range(len(spanishText)):
instSpanishSurfs.append(BASICFONT.render(spanishText[i], 1, TEXTCOLOR))
textPos = instSpanishSurfs[i].get_rect()
# Render the text and get the Pygame Surface and Rect objects of the text.
for i in range(len(englishText)):
instEnglishSurfs.append(BASICFONT.render(englishText[i], 1, MCOLOR))
textPos.top = topCoord + 10
textPos.centerx = HALF_WINWIDTH
next = 0
meaning = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_LEFT:
next -= 1
if next < 0:
next = list_len - 1
if event.key == K_RIGHT:
next += 1
if next > list_len - 1:
next = 0
if event.key == K_UP:
meaning = 0
if event.key == K_DOWN:
meaning = 1
MAINSURF.fill(BGCOLOR)
if meaning == 0:
MAINSURF.blit(instSpanishSurfs[next], textPos)
elif meaning == 1:
MAINSURF.blit(instEnglishSurfs[next], textPos)
pygame.display.update()
def terminate():
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Source
I used the starpusher game posted at ‘the invent with python’
blog as an example. I plan to polish up and add some more functionality to the program, before pushing to my github account [github.com/amehta]