使用pygame在python上运行Monte Carlo,但最终窗口冻结。为什么? [重复]

这是代码,我正在使用Atom。我已经使用pygame很多时间了,这种情况很少发生。我一直不知道问题出在哪里,但直到现在我都不需要。

import pygame
from random import randint as rnd
from colorama import Cursor
import math
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (600,90)


pygame.init()
xsize, ysize = 700, 700
screen = pygame.display.set_mode((xsize, ysize))
screen.fill((0, 0, 0))

def dis(p1, a1):
    return math.sqrt((p1[0] - a1[0])**2 + (p1[1] - a1[1])**2)

inner = 0
tot = 0
pygame.draw.circle(screen, (255, 255, 255), (350, 350), 350, 2)

while True:
    pos = (rnd(0, xsize), rnd(0, ysize))
    if dis((350, 350), pos) < 350:
        color = (50, 255, 50)
        inner += 1
    else:
        color = (50, 50, 250)
    tot += 1
    pygame.draw.circle(screen, color, pos, 2)
    print(" pi = " + str(4 * inner / tot) + "\nnº dots: " + str(tot), Cursor.UP(2))
    pygame.display.flip()
评论
  • msed
    msed 回复

    The window freeze, because you do not handle the events. You have to handle the events by either pygame.event.pump() or pygame.event.get(), to keep the window responding.

    添加一个事件循环,例如:

    run = True
    while run:
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
    
        # [...]