2015-04-02 85 views
0

我需要創建一個旋轉框,但我只是不知道如何開始!我一直在尋找一些信息,但我什麼都找不到,我會提供任何幫助! 謝謝!Pygame和旋轉框

PD:這是真的重要

回答

3

您可以創建一個名爲spinBox類。該類包括

  • 一個class attribute稱爲font其保持pygame的字體對象。
  • 四種方法

    • .draw():繪製spinBox到通過表面
    • .increment().decrement():增加或減少紡紗器的當前狀態
    • .__call__():手柄單擊事件


    以及

    • __init__()方法。
  • 笛實例屬性

    • self.rect
    • self.image
    • self.buttonRects
    • self.state
    • self.step

spinBox類:

class spinBox: 
    font = pygame.font.Font(None, 50) 

    def __init__(self, position): 
     self.rect = pygame.Rect(position, (85, 60)) 
     self.image = pygame.Surface(self.rect.size) 
     self.image.fill((55,155,255)) 

     self.buttonRects = [pygame.Rect(50,5,30,20), 
          pygame.Rect(50,35,30,20)] 

     self.state = 0 
     self.step = 1 

    def draw(self, surface): 
     #Draw SpinBox onto surface 
     textline = spinBox.font.render(str(self.state), True, (255,255,255)) 

     self.image.fill((55,155,255)) 

     #increment button 
     pygame.draw.rect(self.image, (255,255,255), self.buttonRects[0]) 
     pygame.draw.polygon(self.image, (55,155,255), [(55,20), (65,8), (75,20)]) 
     #decrement button 
     pygame.draw.rect(self.image, (255,255,255), self.buttonRects[1]) 
     pygame.draw.polygon(self.image, (55,155,255), [(55,40), (65,52), (75,40)]) 

     self.image.blit(textline, (5, (self.rect.height - textline.get_height()) // 2)) 

     surface.blit(self.image, self.rect) 

    def increment(self): 
     self.state += self.step 

    def decrement(self): 
     self.state -= self.step 

    def __call__(self, position): 
     #enumerate through all button rects 
     for idx, btnR in enumerate(self.buttonRects): 
      #create a new pygame rect with absolute screen position 
      btnRect = pygame.Rect((btnR.topleft[0] + self.rect.topleft[0], 
            btnR.topleft[1] + self.rect.topleft[1]), btnR.size) 

      if btnRect.collidepoint(position): 
       if idx == 0: 
        self.increment() 
       else: 
        self.decrement() 

實例:

#import pygame and init modules 
import pygame 
pygame.init() 

#create pygame screen 
screen = pygame.display.set_mode((500,300)) 
screen.fill((255,255,255)) 

#create new spinBox instance called *spinBox1* 
spinBox1 = spinBox((20, 50)) 
spinBox1 .draw(screen) 

pygame.display.flip() 

while True: 
    #wait for single event 
    ev = pygame.event.wait() 

    #call spinBox1 if pygame.MOUSEBUTTONDOWN event detected 
    if ev.type == pygame.MOUSEBUTTONDOWN and ev.button == 1: 
     spinBox1(pygame.mouse.get_pos()) 
     spinBox1.draw(screen) 

     #updtae screen 
     pygame.display.flip() 

    if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE: 
     pygame.quit() 
     exit() 

請注意,這是僅是示例代碼。無論如何,我希望我可以幫你一點:)

+0

非常感謝你...... !! – Shape

+0

@Shape:沒問題,我很高興能幫助你! :)如果你想讓你接受這個答案(點擊答案旁邊的綠色勾號)。如果您將來有任何問題,請告訴我們。 :D – elegent

+0

這個例子太棒了。謝謝!你能給我一個關於如何讓用戶在旋轉框中輸入一個值的提示嗎? – user2738748