I apologize for the vague title, but essentially I want to exit a game loop in several different ways using pygame. Given the following code, I want to avoid writing "running = False" twice. A very minor thing I know, but I would like to write both "if" conditions in less lines with "and" and "or", if possible.
running = True
while running:
for e in pg.event.get():
if e.type == pg.QUIT:
running = False
if e.type == pg.KEYDOWN:
if e.key == pg.K_ESCAPE:
running = False
pg.quit()
This is my first time asking a question, so please excuse me if this is too vague or just a dumb question. Thanks anyway in advance!
Use some good old Boolean algebra, with parens for grouping!
I think this does the exact same thing, but you might want to double-check:
while True:
for e in pg.event.get():
if e.type == pg.QUIT or (e.type == pg.KEYDOWN and e.key == pg.K_ESCAPE):
pg.quit()
If the goal it to exit on either of those cases this would work:
running = True
while running:
for e in pg.event.get():
if e.type == pg.QUIT or (e.type == pg.KEYDOWN and e.key == pg.K_ESCAPE):
running = False
pg.quit()
You could shorten it even more using:
while True:
for e in pg.event.get():
if e.type == pg.QUIT or (e.type == pg.KEYDOWN and e.key == pg.K_ESCAPE):
break
pg.quit()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.