我试图用pygame制作游戏,但我遇到了敌人产卵的问题。我只是测试它是否会起作用但是当玩家移动游戏时会像这里一样滞后。当我尝试运行程序时,它会给出一个错误,即未定义变量xenemy
。我在运行游戏时把它拿出来,但是在这里添加因为它也是一个错误。
这是我的代码:
import pygame,sys
import random
import time
from pygame.locals import *
pygame.init()
#WINDOW
WIDTH = 352
HEIGHT = 122
pygame.display.set_caption('My First Python Game')
screen=pygame.display.set_mode((WIDTH,HEIGHT))
#LOADING IMAGES
pg = "player.gif"
ey = "enemy.gif"
bg = "y.gif"
a = 0
enemypic = pygame.image.load(ey)
player = pygame.image.load(pg)
spriteWidth, spriteHeight = player.get_rect().size
background = pygame.image.load(bg)
#MUSIC
pygame.mixer.music.load("music.mp3")
pygame.mixer.music.play(-1,0.0)
#X & Y AXIS
x = 0
y = 0
#Enemy
def enemy():
xenemy = random.randrange(24,147)
yenemy = random.randrange(1,135)
global xenemy
global yenemy
#Main Game Loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit
x = min(max(x, 0), WIDTH - spriteWidth)
y = min(max(y, 0), HEIGHT - spriteHeight)
screen.blit(background,[0,0])
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
x += 45
screen.blit(enemypic, (xenemy,yenemy))
screen.blit(player, (y,x))
pygame.display.update()
if x <= WIDTH:
x = 0
if y <= HEIGHT:
y = 0
if a == 0:
pygame.display.flip()
time.sleep(1)