diff options
Diffstat (limited to 'Application.py')
-rw-r--r-- | Application.py | 93 |
1 files changed, 93 insertions, 0 deletions
diff --git a/Application.py b/Application.py new file mode 100644 index 0000000..3172741 --- /dev/null +++ b/Application.py @@ -0,0 +1,93 @@ +''' +Created on 11 Jan 2013 + +@author: cgueret +''' +from gi.repository import Gtk +import csv +import random + +class Data(object): + ''' + Class used to interface with the data + ''' + def __init__(self): + ''' + Constructor + ''' + self._ranks = {} + with open('ranks.csv', 'rb') as csvfile: + reader = csv.reader(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) + for row in reader: + self._ranks[row[0]] = int(row[1]) + + def get_random_subset(self, size): + ''' + Generate a random subset of pairs (country, rank) + ''' + subset = {} + while len(subset.keys()) != size: + key = self._ranks.keys()[random.randint(0, len(self._ranks.keys())-1)] + if key not in subset: + subset[key] = self._ranks[key] + return subset + + +class Main(object): + def __init__(self): + ''' + Constructor + ''' + # Variable to count the number of points + self._points = 0 + self._good_answer = -1 + self._data = Data() + + # Load the graphical user interface + self._gui = Gtk.Builder() + self._gui.add_from_file("GUI.glade") + + # Connect the buttons + for number in range(1, 5): + button = self._gui.get_object("button%d" % number) + button.connect("clicked", self.on_button_clicked, number) + + # Create a new question + self.make_new_question() + + def get_widget(self): + ''' + Return the main widget of the application + ''' + return self._gui.get_object("main_box") + + def get_score(self): + return self._points + + def set_score(self, value): + self._points = value + self._gui.get_object("score_zone").set_label(str(self._points)) + + def make_new_question(self): + ''' + Prepare a new question: pick a set of cities and update the buttons + ''' + subset = self._data.get_random_subset(4).items() + self._good_answer = 1 + for i in range(1, 5): + (country, rank) = subset[i - 1] + if rank > subset[self._good_answer-1][1]: + self._good_answer = i + self._gui.get_object("button%d" % i).set_label(country) + + def on_button_clicked(self, button, number): + ''' + Function called when one of the buttons is clicked + ''' + # Check the answer picked + if number == self._good_answer: + self.set_score(self.get_score() + 1) + + # Create a new question + self.make_new_question() + |