Wednesday, June 11, 2008

Speaking game using python and Mac OS X's say

#!/usr/bin/env python

import os
import random

def say(word):
os.system("say " + word)

class Score:
def __init__(self):
self.total = 0
self.correct = 0

if __name__ == '__main__':
pairs = [["bed", "bad"], ["sped", "speed"],
["wary", "very"], ["bull", "ball"],
["mall", "mole"], ["pale", "pull"],
["soup", "stoop"], ["file", "fill"]]
scores = {}
for pair in pairs:
scores["".join(pair)] = Score()
input = ""

print("To quit, enter q")
while input != "q":
pair = random.choice(pairs)
word = random.choice(pair)
print("1) " + pair[0])
print("2) " + pair[1])
say(word)
input = raw_input("What did the computer say?: ")
input = input.strip()

if input != "q":
key = "".join(pair)
score = scores[key]
score.total += 1
if input == word:
score.correct += 1
print("Correct!")
else:
print("Wrong!")
print("You\'ve gotten the right answer for "
+ " vs ".join(pair) + " "
+ str(score.correct) + " out of "
+ str(score.total) + " times")
Here's a little game to drill you on somewhat similar sounding pairs of English words. I'm sure much could be done to improve it. Is the use of a class here kosher with Python practice? What's contrary to idiom here?

No comments: