1

This code is from the book "Beginning Game Development with Python and Pygame", the following script displays the events that are generated by the mouse and the keyboard on the screen:

import pygame 
from pygame.locals import *  
from sys import exit

pygame.init() 
SCREEN_SIZE = (800, 600) 
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)

font = pygame.font.SysFont("arial", 16)
font_height = font.get_linesize() 
event_text = []

while True:

    event = pygame.event.wait() 
    event_text.append(str(event)) 
    event_text = event_text[-SCREEN_SIZE[1]/font_height:]

I have a problem with this line:

event_text = event_text[-SCREEN_SIZE[1]/font_height:]

Could someone explain it? Thanks in advance :)

dǝɥɔS ʇoıןןƎ
  • 1,674
  • 5
  • 19
  • 42
Belle
  • 451
  • 1
  • 4
  • 9

2 Answers2

1

It appears to be finding out how many lines of text can appear on your screen by getting the screen height, dividing it by the height of one line of text, and slicing the event_text list to get only the last how ever many lines of text.

DavidG
  • 24,279
  • 14
  • 89
  • 82
Brett Beatty
  • 5,690
  • 1
  • 23
  • 37
1

event_text is a list. It supports not only subscripting (ie "mylist[4]" to get the fifth element) but also slicing (getting a subpart - or "slice" - of the list) with the list\[start:stop:step\] syntax

In this example, the start value is computed as -SCREEN_SIZE[1]/font_height. SCREEN_SIZE[1] is the height of the screen (600 in this case), font_height is, well, the height of the font used - if we assume a font height of say 20, -SCREEN_SIZE[1] / 20 => -600 / 20 => -30, so we well get event_text[-30:], which is actually "the last 30 elements in event_text".

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Dividing the screen size on the font height, Is this some kind of a well known mathematical algorithm ? – Belle Jun 08 '17 at 00:07