当程序在python中运行时,如何突破无限循环



我在python中制作了一些我不够聪明的东西,我不小心创建了一个无限循环,我无法结束它,因为我正在使用pygame,所以它制作了一个新窗口,我无法关闭它。

(No title)
import pygame
# initialize variables
width = 1366
height = 704
display_surface = pygame.display.set_mode((width, height)) 
screen = pygame.display.set_mode((width, height))  
# this is the block type list
items = [
# building blocks
["grass", "dirt", "stone", "ore", "chest", "item collector", "block placer", "item dropper"],
# technical blocks
["wires", "sensor", "AND gate", "OR gate", "NOT gate", "NOR gate", "XOR gate", "XNOR gate", "NAND gate", "gearbox", "gear - 24 tooth", "gear - 8 tooth", "item pipe", "filter pipe", "delete pipe", "motor", "joint", "bearing", "blueprints", "spring"],
]
# initiallize pygame sttuff
pygame.init() 
# begining of program
import pygame
def init_screen_and_clock():
global screen, display, clock
pygame.init()
pygame.display.set_caption('Game')
clock = pygame.time.Clock()

def create_fonts(font_sizes_list):
"Creates different fonts with one list"
fonts = []
for size in font_sizes_list:
fonts.append(
pygame.font.SysFont("Arial", size))
return fonts

def render(fnt, what, color, where):
"Renders the fonts as passed from display_fps"
text_to_show = fnt.render(what, 0, pygame.Color(color))
screen.blit(text_to_show, where)

def display_fps():
"Data that will be rendered and blitted in _display"
render(
fonts[0],
what=str(int(clock.get_fps())),
color="white",
where=(0, 0))

init_screen_and_clock()
# This create different font size in one line
fonts = create_fonts([32, 16, 14, 8])
loop = 1
while True:  
screen.fill((0, 0, 0))
display_fps()
for event in pygame.event.get():
if event.type == pygame.QUIT:
loop = 0
clock.tick(60)
pygame.display.flip()
pygame.quit()
print("Game over")

问题是您将loop设置为退出/不退出,但代码不是在测试loop,它只是在测试True。。。毫不奇怪,它总是评估为True。

loop = 1
while True:                         # <<-- HERE
screen.fill((0, 0, 0))
display_fps()
for event in pygame.event.get():
if event.type == pygame.QUIT:
loop = 0
clock.tick(60)
pygame.display.flip()

如果你只是简单地将其更改为测试loop,它将正常工作:

loop = 1
while ( loop == 1 ):                         # <<-- HERE
screen.fill((0, 0, 0))
display_fps()
for event in pygame.event.get():
if event.type == pygame.QUIT:
loop = 0
clock.tick(60)
pygame.display.flip()

我在这里仔细研究了语法,以准确地显示发生了什么。你也可以使用while loop:。但代码少并不总是更好的。

最新更新