微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试使用pygame进行游戏的Python新手

如何解决尝试使用pygame进行游戏的Python新手

我使用PyGame为我的游戏编写了一些代码,以产生障碍并对编码感到陌生。它不会产生障碍,因此我放了一条打印语句以查看它何时产生并且可以打印,但不会显示在屏幕上。这不是全部代码,而是它的简约版本,仅显示有问题的代码。运行代码时没有错误显示

import pygame as pg
import random
pg.init()
obstacle1 = pg.image.load('download1.jpeg')
obstacley = 600#tells object to spawn at top of screen
spawn = random.randint(1,10)
spawned = 0
if spawn == 1 and spawned == 0:
    spawn = 0
    Obstaclex = random.randint(600,800)#determines where on the top of the screen it spawns with rng
    obstaclesize = random.randint(1,5)# determines obstacletype because there are 5 obstacle types that i havent included in this to be as simple as possbile
    obstaclespeed = random.randint(3,8)#determines obstaclespeed using rng
    spawned = 1
    if obstaclesize == 1:       
        gamedisplay.blit(obstacle1,(obstacley,Obstaclex))
        obstacley -= obstaclespeed #changes y position to lower it down the screen to hit player
        print ("i have spawned")

解决方法

您必须封闭游戏循环中所有现有的障碍物,而不仅仅是在创建新障碍物时。

创建一个障碍物列表(obstacle_list)并将新障碍物的坐标附加到列表中。在主应用程序循环中画出所有障碍:

obstacle_list = []

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # [...]

    if len(obstacle_list) < spawn:
        x = random.randint(600,800)
        y = 600
        size = random.randint(1,5)
        speed = random.randint(3,8)
        obstacle_list.append((x,y,size,speed))

    # [...]

    # move obstacles
    for i in range(len(obstacle_list)):
        x,speed = obstacle_list[i]
        new_y = y - speed
        obstacle_list[i] = (x,new_y,speed)

    # [...]

    # draw obstacles
    for x,speed in obstacle_list:
        gameDisplay.blit(obstacle1,(x,y))

    # [...]
,

这只是一个粗略的观点,但我想知道问题是否出在这一行:

gameDisplay.blit(obstacle1,(obstacley,Obstaclex))

.blit()Surface,最好取Rect。我认为您可能需要制作一个Rect对象,使用此功能很容易做到这一点:

pygame.Surface.get_rect()

尝试设置变量以容纳rect对象作为障碍,然后 将(obstacley,Obstaclex)替换为您的rect变量。使用rect的优点是碰撞检测要容易得多。被警告;当您使用的图像也不是矩形时,点击框也开始变得令人困惑。

要移动矩形时,只需更改rect.x

obstacleRect = obstacle1.get_rect()
# --snip--
gameDisplay.blit(obstacle1,obstacleRect)
obstacleRect.y -= 1

要测试您的代码,通常需要更改随机性函数,以产生对象的机会更高。 (尝试random.randint(0,0)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。