2017-08-19 80 views
0

我正在做一個骰子滾動程序,當骰子滾動時,它顯示它的隨機面,然後是最後的面。但問題是當骰子滾動時它只顯示第一張臉並且不會更新到其他臉部。有人知道爲什麼會發生這種情況?pygame窗口不會更新圖像

下面的代碼:

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

的問題與你的代碼,該代碼在運行之前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()