,所以我试图制作一款塔防游戏,并且试图将我的玩家移动到一条路径上,但是我对此有疑问
所以我试图做到这一点,以便每次玩家到达该点时 它会向另一个方向x或y移动,但这种情况正在发生video
我不确定如何有效地使敌人在道路上移动,但这是我的第一次尝试
# move the enemy
if playerman.x < 380:
playerman.x += playerman.speed
else:
playerman.y -= playerman.speed
if playerman.y > 116:
playerman.x += playerman.speed
else:
playerman.x -= playerman.speed
我的完整代码
import pygame,random
pygame.init()
# window
window = pygame.display.set_mode((1000,700))
#
class player:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.speed = 3
self.rect = pygame.Rect(x,y,height,width)
self.image = pygame.image.load("weak1.png")
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect,2)
player_rect = self.image.get_rect(center = self.rect.center)
player_rect.centerx += 3 # 10 is just an example
player_rect.centery += -10 # 15 is just an example
window.blit(self.image, player_rect)
# check points for the player to turn
class check():
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
red = (0,255,0)
check1 = check(380,376,50,50,red)
check2 = check(380,116,50,50,red)
check3 = check(628,116,50,50,red)
check4 = check(640,546,50,50,red)
checks = [check1,check2,check3,check4]
# player
white = (255,255,255)
playerman = player(50,376,50,50,white)
# the background for my gameee
bg = pygame.image.load("bg.png")
# redraw window
def draw():
window.fill((0,0,0))
window.blit(bg,(0,0))
playerman.draw()
# the check points
for check in checks:
check.draw()
# the main loop
runninggame = True
while runninggame:
for event in pygame.event.get():
if event.type == pygame.QUIT:
runninggame = False
# move the enemy
if playerman.x < 380:
playerman.x += playerman.speed
else:
playerman.y -= playerman.speed
if playerman.y > 116:
playerman.x += playerman.speed
else:
playerman.x -= playerman.speed
# redraw the window
draw()
pygame.display.update()
pygame.quit()
答案 0 :(得分:1)
您已经实现了2个if
-else
-statemsts。
if playerman.x < 380: playerman.x += playerman.speed else: playerman.y -= playerman.speed if playerman.y > 116: playerman.x += playerman.speed else: playerman.x -= playerman.speed
这两个语句都被执行,并且播放器每帧执行2次移动。
您必须实现一个if
-elif
声明,其中每帧仅执行一种情况。例如:
while runninggame:
# [...]
if playerman.x < 380:
playerman.x += playerman.speed
elif playerman.y > 116 and playerman.x < 628:
playerman.y -= playerman.speed
elif playerman.x < 628:
playerman.x += playerman.speed
elif playerman.y < 546:
playerman.y += playerman.speed
elif playerman.x < 900:
playerman.x += playerman.speed
# [...]