2017-06-10 38 views
0

我想在pygame中製作一個按鈕。它應該在每次點擊時顯示三個新圖像。一切正常,除非這些圖像只在點擊按鈕時出現。顯示圖像的代碼如下,它是一個更大的while循環的一部分,現在持續無限。我怎樣才能讓圖像保持到再次按下按鈕並出現新圖像?任何幫助表示讚賞,在此先感謝。如何使pygame中的按鈕顯示和更新圖像?

mouse = pygame.mouse.get_pos() 
    click = pygame.mouse.get_pressed() 

    element = -1 
    if 1120 > mouse [0] > 865 and 330 > mouse [1] > 250: 
     screen.blit (dice_button_light, (870, 250)) 

     if click [0] == 1: 
      dice_choices = Dice.dice_choice() 
      print(dice_choices) 


      element = -1 
      for i in dice_choices: 
       element += 1 
       x = 750 
       if element == 1: 
        x += 100 
       if element == 2: 
        x += 200 
       if i == 1: 
        screen.blit (dice1,(x,100)) 
       elif i == 2: 
        screen.blit (dice2,(x,100)) 
       elif i == 3: 
        screen.blit (dice3,(x,100)) 
       elif i == 4: 
        screen.blit (dice4,(x,100)) 
       elif i == 5: 
        screen.blit (dice5,(x,100)) 
       elif i == 6: 
        screen.blit (dice6,(x,100)) 


    else: 
     screen.blit (dice_button, (870, 250)) 

回答

0

要通過不同的圖像週期,你可以把它們放入一個列表,只要單擊該按鈕RECT,增加的index變量表示當前圖像。在你的while循環中,只需使用索引從列表中獲取正確的圖像即可。

import sys 
import pygame as pg 


# Three images. 
IMG1 = pg.Surface((100, 100)) 
IMG1.fill((240, 240, 240)) 
pg.draw.circle(IMG1, (0, 0, 0), (50, 50), 10) 
IMG2 = pg.Surface((100, 100)) 
IMG2.fill((240, 240, 240)) 
pg.draw.circle(IMG2, (0, 0, 0), (25, 25), 10) 
pg.draw.circle(IMG2, (0, 0, 0), (75, 75), 10) 
IMG3 = pg.Surface((100, 100)) 
IMG3.fill((240, 240, 240)) 
pg.draw.circle(IMG3, (0, 0, 0), (20, 20), 10) 
pg.draw.circle(IMG3, (0, 0, 0), (50, 50), 10) 
pg.draw.circle(IMG3, (0, 0, 0), (80, 80), 10) 
# Put the images into a list or tuple. 
IMAGES = [IMG1, IMG2, IMG3] 


def main(): 
    screen = pg.display.set_mode((640, 480)) 
    clock = pg.time.Clock() 
    bg_color = pg.Color(30, 40, 60) 
    # Use this rect for the collision detection and blitting. 
    img_rect = IMG1.get_rect(topleft=(200, 200)) 
    img_index = 0 
    done = False 

    while not done: 
     for event in pg.event.get(): 
      if event.type == pg.QUIT: 
       done = True 
      if event.type == pg.MOUSEBUTTONDOWN: 
       if img_rect.collidepoint(event.pos): 
        img_index += 1 
        # Modulo to cycle between 0, 1, 2. 
        img_index %= len(IMAGES) 

     screen.fill(bg_color) 
     # Use the index to get the current image and blit 
     # it at the img_rect (topleft) position. 
     screen.blit(IMAGES[img_index], img_rect) 

     pg.display.flip() 
     clock.tick(30) 


if __name__ == '__main__': 
    pg.init() 
    main() 
    pg.quit() 
    sys.exit() 
相關問題