不能再点击图片了,我的pygame代码怎么了?

2024-10-03 13:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我正在用pygame库创建一个Tom和Jerry游戏。你知道吗

游戏的重点是抓住老鼠,当它们出现在洞里的时候点击它们。问题 有时会出现一只猫而不是一只鼠标,玩家是否应该错误地点击鼠标 他失去了所有赢得的分数,但比赛仍在继续。 老鼠是老鼠的形象,猫是猫的形象。 如果你点击鼠标,你得到鼠标,否则猫得到点。 代码乱七八糟,这是因为我不知道我在做什么,只是设置了另一个事件循环,因为这样它就工作了,因为它在我创建鼠标之后运行。它的工作方式是点击鼠标,然后你点击其他地方,然后就好像你没有点击鼠标一样。你知道吗

鼠标是在循环中创建的,应该等待5秒钟,如果您在这几秒钟内单击鼠标,则会在控制台中打印一条相应的消息,“,”Jerry clicked!“否则“单击1次”。如果你没有在5秒内点击鼠标,一个图像就会覆盖鼠标,这样她就会消失。你知道吗

现在,我正在尝试做的是打印消息1点击当玩家没有点击任何东西,但打印1点击杰里点击当玩家点击鼠标。我有一个鼠标孔的图像,然后我把鼠标放在鼠标孔上,也就是说,在另一个图像上。你知道吗

此代码至少适用于一个图像:

pygame.init()
width=350;
height=400
screen = pygame.display.set_mode( (width, height ) )
pygame.display.set_caption('clicked on image')
redSquare = pygame.image.load("images/red-square.png").convert()

x = 20; # x coordnate of image
y = 30; # y coordinate of image
screen.blit(redSquare ,  ( x,y)) # paint to screen
pygame.display.flip() # paint screen one time

running = True
while (running):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            # Set the x, y postions of the mouse click
            x, y = event.pos
            if redSquare.get_rect().collidepoint(x, y):
                print('clicked on image')
#loop over, quite pygame
pygame.quit()

我的问题是,当我点击鼠标,然后我不点击鼠标,我不能再点击鼠标在另一个位置。你知道吗

怎么了?我做错什么了?你知道吗

这是我的密码:

import pygame
from pygame import *
from random import *

init()

run = True
screen = (800,800)
screen = display.set_mode(screen)
xpos = 0
ypos = 0
mouseorcatxpos = 5
mouseorcatypos = 0

mousehole = image.load("mousehole.png").convert()

cat = image.load("tom.png")
jerry = image.load("jerry.png")

def makeholes():
    global ypos
    global xpos

    for holey in range(1,9):

        for holex in range(1,9):
            screen.blit(mousehole,(xpos,ypos))
            display.flip()

            xpos += 100

        ypos += 100
        xpos = 0

def mouseorcat():
    global xpos
    mouseorcatxpos = 5
    ypos = 0

    for mousecaty in range(1,9):

            pygame.event.pump()

            for mousecatx in range(1,9):

                randommouse = randint(1, 3)
                randomcat = randint(1, 10)

                if(randommouse == 2):

                    screen.blit(jerry, (mouseorcatxpos, ypos))
                    display.flip()

                    for event in pygame.event.get():

                        if (event.type == MOUSEBUTTONDOWN):

                            if jerry.get_rect().collidepoint(xpos, ypos) == False:

                               print("l clicked!")

                            x, y = event.pos

                            if jerry.get_rect().collidepoint(xpos, y):
                                print("JERRY CLICKED!!")
                                x, y = event.pos
                                print(x, y)


                    time.wait(5000)
                    #screen.blit(mousehole, (mouseorcatxpos - 5, ypos))
                    display.flip()

                elif(randomcat == 2):
                    screen.blit(cat, (mouseorcatxpos, ypos))
                    display.flip()
                    time.wait(1500)
                    screen.blit(mousehole, (mouseorcatxpos-5, ypos))
                    display.flip()

                mouseorcatxpos += 100
            mouseorcatxpos = 0
            ypos += 100


makeholes()


while run == True:


    for event in pygame.event.get():
        mouseorcat()

        if event.type == QUIT:
            run = False

Tags: inimageeventforgetifdisplay鼠标
1条回答
网友
1楼 · 发布于 2024-10-03 13:19:48

我重写了你的游戏来告诉你我会怎么做。你知道吗

为了记录时间和限制帧速率,我使用了游戏时间时钟和一个定时器变量。时钟返回自上次调用clock.tick以来的时间(毫秒),用于增加计时器变量。猫只是在两秒钟后替换鼠标,鼠标被设置到一个新的位置。我使用pygame.Rect存储位置,但也可以使用列表或元组。你知道吗

import sys
import random
import pygame


pygame.init()

size = (800, 800)
screen = pygame.display.set_mode(size)

# Images replaced by pygame.Surface. Do that too
# in the future before you post your code.
mousehole = pygame.Surface((40, 40)).convert()
mousehole.fill(pygame.Color(30, 30, 30))
cat = pygame.Surface((40, 40)).convert()
cat.fill(pygame.Color(110, 110, 130))
jerry = pygame.Surface((40, 40)).convert()
jerry.fill(pygame.Color(190, 130, 0))
# Create the background image and blit the holes.
background = pygame.Surface(size).convert()
for holey in range(8):
    for holex in range(8):
        background.blit(mousehole, (holex*100, holey*100))


def new_position():
    """Return a random position between 0-700 in steps of 100."""
    return (random.randrange(0, 701, 100), random.randrange(0, 701, 100))


def main():
    fps = 30
    clock = pygame.time.Clock()

    jerry_rect = jerry.get_rect()  # Stores jerry's position and size.
    jerry_rect.topleft = new_position() # New random position.
    # The cat is outside of the screen first.
    cat_rect = cat.get_rect(topleft=(-100, -100))
    points = 0
    timer = 0

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                if jerry_rect.collidepoint(event.pos):
                    points += 1
                    print('Jerry caught! Points:', points)
                    timer = 0
                    jerry_rect.topleft = new_position()
                else:
                    print('Missed. Points:', points)

        # Run logic.
        timer += clock.tick(fps) / 1000  # timer + seconds since last tick.
        if timer > 2:  # Cat catches mouse after 2 seconds.
            cat_rect.topleft = jerry_rect.topleft
            jerry_rect.topleft = new_position()
            timer = 0
            points = 0
            print('Tom caught Jerry.')
        # Draw.
        # Clear the screen by blitting the bg.
        screen.blit(background, (0, 0))  
        screen.blit(jerry, jerry_rect)
        screen.blit(cat, cat_rect)
        pygame.display.flip()

if __name__ == '__main__':
    main()
    pygame.quit()
    sys.exit()

旁注:

不要使用星型导入(from module import *),因为那样会使代码更难阅读。如果你想你可以使用from pygame.locals import *,如果它是唯一的星导入。你知道吗

不要使用全局变量,因为它们会使代码更难阅读、理解和维护。将变量作为参数传递给函数,然后返回结果。你知道吗


更新:有关您的程序的一些说明:

第一个大问题是您的游戏有两个事件循环,而重要的一个是深入嵌套在另外两个for循环和if中。事件循环应该直接在main while循环下(一个缩进级别(当您有更多经验时,可以将其放入函数或类方法中))。你知道吗


两个for循环的目的似乎是让代码运行到randommouse或randomcat为2。while循环的目的是运行代码直到满足条件。但在这种情况下,您最好选择一个随机数并编写if/elif条件,以便它们始终适用。例如,你想给老鼠2/3的机会,给猫1/3的机会

random_number = random.randint(1, 3)
if random_number < 3:
    print("2/3 probability. It's a mouse")
else:
    print("1/3 probability. It's a cat")

或者将random.choice与列表一起使用:

>>> random.choice(['mouse', 'mouse', 'cat'])
'mouse'

你知道吗时间。等等(5000)不应该被使用,因为这个时候游戏挂起了。你连窗户都关不上。限制帧速率并用pygame.time.Clock获取自上次勾选以来的时间。你知道吗


你知道吗pygame.event.pump泵()不需要。你知道吗


如果在没有参数的情况下调用get\ rect(),则rect位于(0,0)。你知道吗

if jerry.get_rect().collidepoint(xpos, y):

这就是为什么点击jerry只在最上面一行起作用的原因,因为你在这里使用全局xpo。因为xpos是0,所以最上面的一行都算作Jerry。你知道吗

您可以像这样将坐标传递给get_rect(也可以使用center或其他args而不是topleft):

jerry_rect = jerry.get_rect(topleft=(50, 100))

对不起,我想我不能简单地修改你的代码。我试过好几次,但最后总是完全重写。你知道吗

我首先从两个嵌套for循环中提取事件循环,然后移除这些循环,为鼠标和cat创建矩形,修复冲突检测,添加计时器等等。仔细看看我的例子,试着用类似的方式重写你的游戏,如果你不懂的话,继续问问题。你知道吗

相关问题 更多 >