# Strongly inspired by a program by Al Sweigart, see # https://inventwithpython.com/pygame/chapter6.html # Creative Commons BY-NC-SA 3.0 US import random, pygame from pygame.locals import * FRAMES_PER_SECOND = 25 ANZAHL_BOXEN_X = 10 ANZAHL_BOXEN_Y = 6 BOX_BREITE = 60 BOX_HOEHE = 60 FENSTER_BREITE = ANZAHL_BOXEN_X * BOX_BREITE FENSTER_HOEHE = ANZAHL_BOXEN_Y * BOX_HOEHE # Farben per Rot-, Grün- und Blauwert # (jeweils auf Skala von 0 bis 255). # rot grün blau ROT = (255, 0, 0) GRUEN = ( 0, 255, 0) BLAU = ( 0, 0, 255) WEISS = (255, 255, 255) SCHWARZ = ( 0, 0, 0) GRAU = (150, 150, 150) HINTERGRUND_FARBE = SCHWARZ def zeichneBox(x, y, farbe): Rechteck = pygame.Rect(x * BOX_BREITE + 1, y * BOX_HOEHE + 1, BOX_BREITE - 1, BOX_HOEHE - 1) pygame.draw.rect(leinwand, farbe, Rechteck) def zeichneGitter(): for x in range(ANZAHL_BOXEN_X + 1): pygame.draw.line(leinwand, GRAU, (x * BOX_BREITE, 0), (x * BOX_BREITE, FENSTER_HOEHE)) for y in range(ANZAHL_BOXEN_Y + 1): pygame.draw.line(leinwand, GRAU, (0, y * BOX_HOEHE), (FENSTER_BREITE, y * BOX_HOEHE)) pygame.init() uhr = pygame.time.Clock() leinwand = pygame.display.set_mode((FENSTER_BREITE + 1, FENSTER_HOEHE + 1)) pygame.display.set_caption('Red boxy') xpos = random.randint(0, ANZAHL_BOXEN_X) ypos = random.randint(0, ANZAHL_BOXEN_Y) farbe = ROT spielEnde = False while not spielEnde: leinwand.fill(HINTERGRUND_FARBE) zeichneGitter() zeichneBox(xpos, ypos, farbe) pygame.display.update() uhr.tick(FRAMES_PER_SECOND) for ereignis in pygame.event.get(): if ereignis.type == QUIT: print("Button zum Schliessen des Pygame-Fensters angeklickt.") elif ereignis.type == KEYDOWN: if ereignis.key == K_LEFT: print("Pfeiltaste links gedrückt.") elif ereignis.key == K_RIGHT: print("Pfeiltaste rechts gedrückt.") elif ereignis.key == K_UP: print("Pfeiltaste hoch gedrückt.") elif ereignis.key == K_DOWN: print("Pfeiltaste runter gedrückt.") elif ereignis.key == K_ESCAPE: print("Escape-Taste gedrückt.") elif ereignis.key == K_q: print("Taste 'q' gedrückt.")