首页 > 解决方案 > 尝试使用 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")

标签: pythonpygame

解决方案


您必须在每一帧中对游戏循环中的所有现有障碍进行blit,而不仅仅是在创建新障碍时。

创建一个障碍物列表 ( 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, y, size, speed = obstacle_list[i]
        new_y = y - speed
        obstacle_list[i] = (x, new_y, size, speed)

    # [...]

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

    # [...]

推荐阅读