2015-04-02 22 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