的Python / pygame的; MOUSEBUTTONDOWN事件

时间:2015-04-08 09:06:44

标签: python python-2.7 pygame

好吧我对使用Pygame很新,我真的只是在玩一些方法和事件。到目前为止,我几乎有一个图像在pygame框架周围移动,并在框架碰到它时从框架的任何边缘反弹。如果图像接触到帧的顶部,它将使计数变量增加1,这将显示在屏幕上。然后我想添加一个功能,如果我点击正在移动的图像,它也会在count变量上添加一个。然而,当我添加此代码时(我认为因为函数在循环上运行),根据您按住鼠标的时间长短,计数增加了8的倍数。我想这样做,无论我持有多长时间鼠标按下,MOUSEBUTTONDOWN处理程序中存储的事件只会触发一次。我究竟做错了什么?

import pygame, sys
from pygame.locals import *

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
screen =pygame.display.set_mode((600,400))
ball = pygame.image.load("homers.png")
ball = pygame.transform.scale(ball,(225,200))
x=200
y=100
left = True
up = True
color = 67,143,218
def text_objects(text,font):
    text_surface = font.render(text,True, color)
    return text_surface,text_surface.get_rect()

def message_display(text,x,y,z):
    largeText = pygame.font.Font('freesansbold.ttf',z)
    TextSurf,TextRect = text_objects(text,largeText)
    TextRect.center = (x,y)
    screen.blit(TextSurf,TextRect)

def hi(x,y,p,z):

    message_display(x,y,p,z)
count = 0
message_count = str(count)
while True: # main game loop
        screen.fill((180,0,0))
        screen.blit(ball,(x,y))



        for event in pygame.event.get():
                if event.type == QUIT:
                     pygame.quit()
                     sys.exit()

        hi(message_count,x,y,140)
        hi("How Many Times Has Homer Hit His Head?",300,200,20)

        if event.type == pygame.MOUSEBUTTONDOWN:
            # Set the x, y postions of the mouse click

            if ball.get_rect().collidepoint(x, y):
                count = count+1

        if event.type == pygame.MOUSEBUTTONUP:
            0

        if left == True:

            x=x-10
        if x == -100:
            left =False
        if left == False:

            x=x+10
        if x == 450:
            left = True
        if up == True:

            y=y-10
        if y == -20:
            up =False
            count = count+1
            message_count = str(count)
            hi(message_count,x,y,140)
        if up == False:

            y=y+10
        if y== 230:
            up =True
        pygame.display.update()

1 个答案:

答案 0 :(得分:1)

您必须修复代码的缩进:

while True: # main game loop
    screen.fill((180,0,0))
    screen.blit(ball,(x,y))

    hi(message_count,x,y,140)
    hi("How Many Times Has Homer Hit His Head?",300,200,20)

    for event in pygame.event.get():
         if event.type == QUIT:
             pygame.quit()
             sys.exit()

         # this has to be part of the for loop
         if event.type == pygame.MOUSEBUTTONDOWN:
             if ball.get_rect().collidepoint(x, y):
                 count = count+1

    ...