pygame窗口不会更新图像

时间:2017-08-19 23:03:16

标签: python pygame python-3.5 dice self-updating

我正在制作一个骰子滚动程序,当骰子滚动时,它会显示它的随机面,然后是最后的面。但问题是当骰子滚动时它只显示第一张脸并且不会更新到其他脸。谁知道为什么会这样?

这里是代码:

from pygame.locals import *
from random import randint
import pygame
import sys

for x in range(11):
    if x > 1:
        n = randint(1,6)
        print(x,":",n)

pygame.init()

screen = pygame.display.set_mode((500,500),0,32)

one = pygame.image.load("one.png").convert_alpha()
two = pygame.image.load("two.png").convert_alpha()
three = pygame.image.load("three.png").convert_alpha()
four = pygame.image.load("four.png").convert_alpha()
five = pygame.image.load("five.png").convert_alpha()
six = pygame.image.load("six.png").convert_alpha()

while True:
    for evt in pygame.event.get():
        if evt.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()

    if n == 1:
        screen.blit(one,(250,250))
    if n == 2:
        screen.blit(two,(250,250))
    if n == 3:
        screen.blit(three,(250,250))
    if n == 4:
        screen.blit(four,(250,250))
    if n == 5:
        screen.blit(five,(250,250))
    if n == 6:
        screen.blit(six,(250,250))

1 个答案:

答案 0 :(得分:1)

您的代码存在的问题是此代码在安装pygame之前正在运行。

for x in range(11):
    if x > 1:
        n = randint(1,6)
        print(x,":",n)` 

您可以在while语句中管理此问题,仅验证之前显示的骰子数量。

之后,您必须重新绘制所有屏幕,首先再次绘制背景,然后再显示图像。

此代码已经有效。

from pygame.locals import *
from random import randint
import pygame
import sys

pygame.init()

"Set screen"
screen = pygame.display.set_mode((1000,1000),0,32)

"Load images"
one = pygame.image.load("one.png").convert_alpha()
two = pygame.image.load("two.png").convert_alpha()
three = pygame.image.load("three.png").convert_alpha()
four = pygame.image.load("four.png").convert_alpha()
five = pygame.image.load("five.png").convert_alpha()
six = pygame.image.load("six.png").convert_alpha()

"Fill background"
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255, 255, 255))

"Setup Counter"
counterOfDices = 0

while True:
    for evt in pygame.event.get():
        if evt.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.blit(background, (0, 0))

    "Verify How many dices had been displayed"
    if counterOfDices < 11:
        n = randint(1,6)
        counterOfDices += 1

    if n == 1:
        screen.blit(one,(250,250))
    if n == 2:
        screen.blit(two,(250,250))
    if n == 3:
        screen.blit(three,(250,250))
    if n == 4:
        screen.blit(four,(250,250))
    if n == 5:
        screen.blit(five,(250,250))
    if n == 6:
        screen.blit(six,(250,250))

    pygame.time.delay(100)
    pygame.display.update()