Pygame Enemys Wont Move Down - Tower Defense Game

女生的网名这么多〃 提交于 2021-02-13 17:30:01

问题


my problem here is that for my last 2 check points for my enemy for my tower defense game the enemys wont move down for the second last go untile they damage the tower video they just move forward idk why they just move out from there
its the same for the last one to




    # move the enemy
    for spider in spiders:
        if spider.x < 230:
            spider.x += spider.speed


            
        elif spider.y < 160:
            spider.x += spider.speed
        elif spider.x > 540:
            spider.y -= spider.speed
        elif spider.y < 566:
            spider.y += spider.speed
        elif spider.y > 290:
            spider.x += spider.speed

        elif spider.y > 566:
            spider.x += spider.speed

        # THIS part isnt working IDK why if the enemy is close to the 4th check point it should go down but it wont??
        elif spider.x < 628:
            spider.y += spider.speed

        # idk if this part will work because the last second part didnt work
        elif spider.y < 550:
            spider.x += spider.speed


my full code


import pygame,random

pygame.init()

# window
window = pygame.display.set_mode((1000,700), pygame.NOFRAME)

red = (0,255,0)

#
class spider:
    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 = 13
        self.rect = pygame.Rect(x,y,height,width)
        self.health = 10 
        self.hitbox = (self.x + 20, self.y, 26,60)


        # image frame
        self.image = [pygame.image.load("weak (1).png"),
                      pygame.image.load("weak (2).png"),
                      pygame.image.load("weak (3).png"),
                      pygame.image.load("weak (4).png"),
                      pygame.image.load("weak (5).png"),
                      pygame.image.load("weak (6).png"),
                      pygame.image.load("weak (7).png"),
                      pygame.image.load("weak (8).png"),
                      pygame.image.load("weak (9).png"),
                      pygame.image.load("weak (10).png"),
                      pygame.image.load("weak (11).png"),
                      pygame.image.load("weak (12).png"),
                      pygame.image.load("weak (13).png"),
                      pygame.image.load("weak (14).png"),
                      pygame.image.load("weak (15).png"),
                      pygame.image.load("weak (16).png"),
                      pygame.image.load("weak (17).png"),
                      pygame.image.load("weak (18).png"),
                      pygame.image.load("weak (19).png")]
        
        
        self.image = [pygame.transform.scale(image,(image.get_width()//2,image.get_height()//2)) for image in self.image]


        self.anim_index = 0
        self.walkrights = 0
        self.fps = 40
        self.clock = pygame.time.Clock()
        self.direction = "up"
        self.direction = "right"
        
        
    def draw(self):
        self.rect.topleft = (self.x,self.y)

        self.clock.tick(self.fps)
        image_list = self.image


        if self.anim_index >= len(image_list):
            self.anim_index = 0

        player_image = image_list[self.anim_index]
        self.anim_index += 1

        
        player_rect = player_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(player_image, player_rect)


        self.hitbox = (self.x + -18, self.y, 46,60)
        pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 40, 40, 13)) # NEW
        pygame.draw.rect(window, (231, 76, 60), (self.hitbox[0], self.hitbox[1] - 40, 80 - (5 * (10 - self.health)), 13))
spiders = []
platformGroup = pygame.sprite.Group
level = [
    "                                                                                                       ",
    "                                                                                                     ",
    "                                                                                                      ",
    "                                                                                                           ",
    "                                                                                                     ",
    "                                                                                                               ",
    "                                                                                                     ",
    "    c         c       c          c           c            c         c           c           c                        ",
    "                                                                                                          ",
    "                                                                                               ",
    "                                                                                                       ",
    "                                                                                                  ",
    "                                                                                                       ",
    "                                                                                                       "]


for iy, row in enumerate(level):
    for ix, col in enumerate(row):
        if col == "c":
            new_platforms = spider(ix*-24, iy*46, 50,50,(23, 32, 42))
            spiders.append(new_platforms)


class tower:
    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)
        self.health = 10
        self.hitbox = (self.x + -18, self.y, 46,60)
        
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        self.hitbox = (self.x + -18, self.y, 46,60)
        pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 40, 140, 25)) # NEW
        pygame.draw.rect(window, (46, 204, 113), (self.hitbox[0], self.hitbox[1] - 40, 140 - (5 * (10 - self.health)), 25))


tower1 = tower(875,450,50,50,red)


# 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)

check1 = check(250,366,50,50,red)
check2 = check(250,566,50,50,red)
check3 = check(540,566,50,50,red)
check4 = check(780,166,50,50,red)
check5 = check(780,550,50,50,red)


checks = [check1,check2,check3,check4,check5]



# the background for my gameee
bg = pygame.image.load("bg2.png")


# redraw window
def draw():
    window.fill((0,0,0))
    window.blit(bg,(0,0))


    for spider in spiders:
        spider.draw()

    for check in checks:
        check.draw()
    tower1.draw()



clock = pygame.time.Clock()
fps = 60

# the main loop
runninggame = True
while runninggame:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False


    # move the enemy
    for spider in spiders:
        if spider.x < 230:
            spider.x += spider.speed


            
        elif spider.y < 160:
            spider.x += spider.speed
        elif spider.x > 540:
            spider.y -= spider.speed
        elif spider.y < 566:
            spider.y += spider.speed
        elif spider.y > 290:
            spider.x += spider.speed

        elif spider.y > 566:
            spider.x += spider.speed

        # THIS part isnt working IDK why if the enemy is close to the 4th check point it should go down but it wont??
        elif spider.x < 628:
            spider.y += spider.speed

        # idk if this part will work because the last second part didnt work
        elif spider.y < 550:
            spider.x += spider.speed




            









    

    # redraw the window
    draw()


    pygame.display.update()
pygame.quit()




回答1:


I recommend to move the scorpion along a list of points (spider_move). Use a variable that states the index of the next point (spider_move_to) and move the scorpion to this point (next_p). Every time when a point is reached, then increment the index (spider_move_to += 1). If no more point is in the list, then stop the movement. To move the scorpion, compute the difference ( dx, dy) between the current position of spider and the point from the list (next_p). Increment or decrement to position of the scorpion (spider.x, spider.y) by spider.speed, dependent on the amount of dx and dy:

spider_move_to = 0
spider_move = [
   (240, 330), (240, 550), (540, 550), (540, 160),
   (770, 160), (770, 550), (870, 550)]

runninggame = True
while runninggame:
   # [...]

   if spider_move_to < len(spider_move):
       next_p = spider_move[spider_move_to] 
       dx, dy = (next_p[0] - spider.x, next_p[1] - spider.y)

       if dx > spider.speed:
           spider.x += spider.speed
       elif dx < -spider.speed:
           spider.x -= spider.speed
       else: 
           spider.x = next_p[0]

       if dy > spider.speed:
           spider.y += spider.speed
       elif dy < -spider.speed:
           spider.y -= spider.speed
       else: 
           spider.y = next_p[1]

       if spider.x == next_p[0] and spider.y == next_p[1]:
           spider_move_to += 1

   # [...]

If you have multiple scorpions, then I recommend to make spider_move_to an attribute of the class spider

class spider:
    def __init__(self,x,y,height,width,color):
        # [...] 

        self.spider_move_to

Use the attribute instead of the global variable:

spider_move = [
   (240, 330), (240, 550), (540, 550), (540, 160),
   (770, 160), (770, 550), (870, 550)]

runninggame = True
while runninggame:
   # [...]

   for spider in spiders:
       if spider.spider_move_to < len(spider_move):
           next_p = spider_move[spider.spider_move_to] 
           dx, dy = (next_p[0] - spider.x, next_p[1] - spider.y)

           # [...]

           if spider.x == next_p[0] and spider.y == next_p[1]:
               spider .spider_move_to += 1

   # [...]  



回答2:


A youtuber Tech With Tim has created a tower defense game with pygame in his 12 hour livestream . You will find his code on this github-link and you can figure it out where is the error.

Note: The assets are not included in this github code doesn't contain the assets(images and sounds)so you can create your assets folder and reference your images and sounds in your game script.




回答3:


When looking at your code I noticed this oddity

elif spider.x > 540:
    spider.y -= spider.speed

...

elif spider.x < 628:
    spider.y += spider.speed

this is based on the order you provided. The second elif can Never run as the spider doesn't ever go - x meaning we will never be able to get a result that is < 540 meaning > 540 is always true which also means that since Elif always runs the first true condition then we cannot actually get a value that will cause the condition < 628 to run before >540. I would suggest modifying the code to remove the possibility of this occurring by adding self.checkpoint as a property of each spider. Then when it reaches a check point you do a check in your if as so

elif spider.x > 540 and (spider.checkpoint = 3 or spider.checkpoint = 4):
    if spider.checkpoint != 4:
        spider.checkpoint = 4
    spider.y -= spider.speed

for each checkpoint this will increment it to the next one for the first run and keep it there so that when you reach the next checkpoint just increment each number by 1 so that the spider always knows which checkpoint it is travelling to.



来源:https://stackoverflow.com/questions/63734280/pygame-enemys-wont-move-down-tower-defense-game

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!