如何解决在Pygame中确定敌人名单的时间
在游戏循环之外,我创建了一个函数,该函数创建了200个随机坐标的敌人的列表。这些敌人应该从屏幕顶部开始,然后以随机速度下降。在循环内部,我使用“ for”循环来消灭屏幕上的敌人。它可以正常工作,但是所有200千都同时生成并且掉落,尽管速度不同。所以我知道我需要一个计时器,这就是问题所在。我没有做任何工作。我已经尝试过clock.tick()
,pygame.delay()
,import time
并执行time.time()
方法。频闪或系统崩溃。是什么原因引起的?
[代码]
import pygame
import sys
import random
import time
pygame.init()
#MAIN GAME
game_screen = pygame.display.set_mode((600,600))
pygame.display.set_caption("Beer Goggles")
bg = pygame.image.load("bg.png")
bg_image = pygame.transform.scale(bg,(600,600))
class Object:
def __init__(self,image_path,width,height,x,y):
self.image_path = image_path
self.width = width
self.height = height
self.x = x
self.y = y
player = pygame.image.load(image_path)
self.player_main = pygame.transform.scale(player,(width,height))
def draw(self,background):
background.blit(self.player_main,(self.x,self.y))
#enemies
def enemy():
enemy_list = []
for e in range(200):
x_cor = random.randint(25,361)
e = Object("enemy.png",70,x_cor,25)
enemy_list.append(e)
return enemy_list
#Main Objects
player1 = Object("crate.png",25,500)
list1 = enemy()
#ladies
fat_lady = Object("fat_lady.png",300,360,180)
# Main Loop
direction = 0
game_on = True
while game_on:
clock = pygame.time.Clock()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_on = False
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
direction = 1
elif event.key == pygame.K_LEFT:
direction = -1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
direction = 0
game_screen.fill((0,0))
game_screen.blit(bg_image,(0,0))
#title.draw(game_screen)
player1.draw(game_screen)
fat_lady.draw(game_screen)
#move
if direction > 0:
player1.x = player1.x + 10
elif direction < 0:
player1.x = player1.x - 10
#boundaries
if player1.x <= 25:
player1.x = 25
elif player1.x >= 360:
player1.x = 360
#for enemy in list1:
for enemy in list1:
a = random.randint(1,30)
enemy.draw(game_screen)
enemy.y += a
#collisions
#scoring
pygame.display.update()
quit()
解决方法
在创建enemy
列表的代码中,您可以添加放置开始时间。就像您创建随机x坐标一样,您可以创建一个时间来开始删除它。然后,稍后当您开始更改它们的y位置(放下它们)时,直到该时间过去之后才开始放下它。
顺便说一句,您有一个方法enemy()
,后来又有一个循环迭代器enemy
,它将用该名称覆盖hide方法。此后,如果您尝试调用方法enemy()
,它将失败,而您将访问循环迭代器。它不会影响您的代码,因为您不会在创建循环迭代器变量后尝试访问该方法,但这不是一个好主意,如果您以后更改代码并尝试访问该方法,可能会导致问题。您应该谨慎选择名称。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。