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")
解决方案
您必须在每一帧中对游戏循环中的所有现有障碍进行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))
# [...]
推荐阅读
- django-rest-framework - 我在 django rest 框架中遇到错误
- python - 为什么我无法通过 flask_login 在网站上正确授权用户
- c# - 如何使用 DateTimeFormat.DayNames 获取一周中所有天的整数值?C#
- c# - It.IsAny
用于类型的单元测试:- params Action [] - angular - Angular - 当另一个模态对话框打开时以编程方式关闭打开的模态对话框
- web-scraping - 需要帮助 网页提取
- 和
- 使用scrapy
- javascript - 如何使用角度中的类名将单击事件附加到多个控件
- angular - 浏览器的Angular2后退和前进按钮不适用于查询参数
- java - 启动应用程序时始终显示某些活动(而不是在从活动导航到活动时)
- ionic3 - 无法通过 Ionic 应用验证 Google 用户,收到“无法登录”错误