我正在尝试制作一个游戏,其中“玩家”(生成为最右边的月亮)可以使用“WASD”键四处移动,敌人从屏幕顶部掉落以击中玩家并结束游戏。我目前正在为一项任务执行此操作,并且我已经设置了一个测试以查看我是否可以执行此操作,到目前为止,我已经能够创建一个可由“WASD”键控制的“播放器”对象和制作一个要求玩家按“SPACE”来玩游戏的屏幕。我无法让敌人顺利地落在屏幕下方的“Y”轴上。仅当用户按下或释放一个键时,图片才会在屏幕上向下移动,这会产生锯齿状移动,或者当用户将鼠标移到 pygame 屏幕上时,
#import necessary modules and pygame.
import pygame, sys, random
from pygame.locals import *
#set global variables
pygame.init()
WINDOWWIDTH = 800
WINDOWHEIGHT = 800
BACKGROUNDCOLOUR = (255,255,255)
TEXTCOLOUR = (0,0,0)
FPS = 30
ENEMYMINSIZE = 10
BOMBSAWAY = -1
ENEMYMAXSIZE = 40
ENEMYMINSPEED = 1
ENEMYMAXSPEED = 10
ADDNEWENEMYRATE = 5
PLAYERMOVERATE = 5
FSIZE = 48
BLUE = (0,0,255)
global PLAY
PLAY = False
global fpsClock
fpsClock = pygame.time.Clock()
# set up pygame and GUI
MainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
windowSurface.fill(BACKGROUNDCOLOUR)
pygame.display.set_caption('Bubble Dash')
enemy = pygame.image.load('player.jpg')
char = pygame.image.load('player.jpg')
# set up fonts
basicFont = pygame.font.SysFont(None, 48)
# set up the text
text = basicFont.render('Press any key to play!', True, (255,255,0))
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery
# draw the text onto the surface
# set up x and y coordinates
# music
windowSurface.blit(text, textRect)
def playgame(PLAY):
x,y = 0,0
movex,movey = 0,0
charx=300
chary=200
direction = 'down'
enemyx= 10
enemyy=10
while PLAY:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == ord('m'):
pygame.mixer.music.stop()
if event.key == ord('n'):
pygame.mixer.music.play()
if event.key == ord('a'):
movex = -0.5
if event.key == ord('d'):
movex = 0.5
if event.key == ord('w'):
movey = -0.5
if event.key == ord('s'):
movey = 0.5
if event.type ==KEYUP:
if event.key == ord('a'):
movex = 0
if event.key == ord('d'):
movex = 0
if event.key == ord('w'):
movey = 0
if event.key == ord('s'):
movey = 0
if direction == 'down':
enemyy += 7
windowSurface.fill(BLUE)
windowSurface.blit(char, (charx, chary))
windowSurface.blit(enemy, (enemyx, enemyy))
pygame.display.update()
charx+=movex
chary+=movey
def playertopresskey(PLAY):
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_SPACE:
PLAY = True
if PLAY == True:
playgame(PLAY)
pygame.display.update()
playertopresskey(PLAY)
我希望“敌人”对象能够从顶部掉下来,而用户不需要按键或向上键或必须在屏幕上移动鼠标,而“敌人”只会从顶部掉下来只要子程序被调用。
您可能需要对其进行一些调整,因为它目前是为我设置的,但我删除了一些会给您带来麻烦的东西。希望有人可以帮助我。谢谢。
下面是一个类似于我的图片的链接,您可以下载并在代码中替换 'char' 和 'enemy' 变量以自己查看,因为我目前无法访问课程。 http://www.roleplaygateway.com/roleplay/the-five-elements/characters/miss-joy/image