Pygame和旋转框

时间:2015-04-02 03:26:57

标签: pygame

我需要创建一个旋转框,但我只是不知道如何开始!我一直在寻找一些信息,但我找不到任何东西,我会帮助你! 谢谢!

PD:这非常重要

1 个答案:

答案 0 :(得分:3)

您可以创建一个名为spinBox的类。该课程由

组成
  • 一个class attribute名为font ,其中包含PyGame字体对象。
  • 四种方法

    • .draw():将spinBox绘制到已传递的表面
    • .increment().decrement():递增或递减Spinbox的当前状态
    • .__call__():处理点击事件


    以及

    • __init__()方法。
  • fife实例属性

    • 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()

请注意,这是仅示例代码。无论如何,我希望我可以帮助你一点点:))