Zur Übung erstelle ich gerade ein Hauptmenü für meinen Reaktionszeittest.
Den Code habe ich entsprechend erweitert:
Code: Alles auswählen
from tkinter import Tk, Button
from random import choice
import time
from statistics import mean
DESIGNATED_COLOR = "red"
SWITCH_TIME = 1000
class Main_Window:
def __init__(self, app_window):
self.app_window = app_window
app_window.title("Game")
app_window.geometry('640x480')
self.start_button = Button(app_window, text="Start", command=game.start_game) # !!!
self.start_button.pack()
self.close_button = Button(app_window, text="Close", command=app_window.quit)
self.close_button.pack()
class Game:
def __init__(self, game_window):
self.game_window = game_window
self.colors = ["green", "red", "blue", "yellow", "black"]
self.color = None
self.reaction_times = []
self.false_positives = 0
self.color_missed = 0
self.key_too_often_pressed = 0
self.stop_test = False
self.color_locked = False
def start_game(self):
self.game_window.attributes("-fullscreen", True)
self.canvas = Tk.Canvas(self.game_window, width=self.game_window.winfo_screenwidth(),
height=self.game_window.winfo_screenheight(),
highlightthickness=0)
self.canvas.pack()
self.change_bg_color(DESIGNATED_COLOR)
def change_bg_color(self, color_locked = False):
if self.stop_test == True:
self.game_window.quit()
if not self.color_locked and self.color == DESIGNATED_COLOR:
self.color_missed += 1
self.color_locked = color_locked
current_color = self.color
while True:
if self.color == current_color:
self.color = choice(self.colors)
else:
break
self.canvas.config(bg=self.color)
self.start_time = time.monotonic() # Ereignis Timer
self.game_window.after(SWITCH_TIME, self.change_bg_color)
def key_pressed(self):
if self.color == DESIGNATED_COLOR:
if self.color_locked:
self.key_too_often_pressed += 1
else:
reaction_time = time.monotonic() - self.start_time
self.reaction_times.append(reaction_time)
self.color_locked = True
else:
self.false_positives += 1
def stop_game(self):
self.stop_test = True
if self.reaction_times:
# mean() auf Liste ohne Einträge führt zu einem Fehler
print("Gemittelte Reaktionszeit:", mean(self.reaction_times))
print("Reaktionszeit pro richtiger Farbe:", self.reaction_times)
print("Bei richtiger Farbe zu oft gedrückt:", self.key_too_often_pressed)
print("Bei richtiger Farbe nicht gedrückt:", self.color_missed)
print("Bei falscher Farbe gedrückt:", self.false_positives)
def main():
root = Tk()
root.bind("<Escape>", lambda e: game.stop_game())
main_window = Main_Window(root)
game = Game(root)
root.bind("<space>", lambda e: game.key_pressed()) # Ereignis Tastendruck
root.mainloop()
if __name__ == '__main__':
main()
Es erscheint folgende Fehlermeldung:
Code: Alles auswählen
NameError: name 'game' is not defined
Gruß
Atalanttore