首页 > 解决方案 > Pygame敌人不在屏幕上移动

问题描述

import pygame, sys

clock = pygame.time.Clock()

from pygame.locals import *
pygame.mixer.pre_init(44100,-16,2,512)
pygame.init()

pygame.display.set_caption('THE GAME')#Window name

walkRight = [pygame.image.load('player_animations/R1.png'), pygame.image.load('player_animations/R2.png'), pygame.image.load('player_animations/R3.png'), pygame.image.load('player_animations/R4.png'), pygame.image.load('player_animations/R5.png'), pygame.image.load('player_animations/R6.png'), pygame.image.load('player_animations/R7.png'), pygame.image.load('player_animations/R8.png'), pygame.image.load('player_animations/R9.png')]
walkLeft = [pygame.image.load('player_animations/L1.png'), pygame.image.load('player_animations/L2.png'), pygame.image.load('player_animations/L3.png'), pygame.image.load('player_animations/L4.png'), pygame.image.load('player_animations/L5.png'), pygame.image.load('player_animations/L6.png'), pygame.image.load('player_animations/L7.png'), pygame.image.load('player_animations/L8.png'), pygame.image.load('player_animations/L9.png')]

Window_SIZE = (900,600)

screen = pygame.display.set_mode(Window_SIZE,0,32)

display = pygame.Surface((900,600))

player_image = pygame.image.load('player_animations/player_image.png')
player_image.set_colorkey((255,255,255))

grass_image = pygame.image.load('Map/Grassblock.png')
grass_image.set_colorkey((255,255,255))

dirt_image = pygame.image.load('Map/Dirtblock.png')

cobble_image = pygame.image.load('Map/Stoneblock.png')

TILE_SIZE = grass_image.get_width()

true_scroll = [0,0]

#ENEMIES
class Enemy(pygame.sprite.Sprite):
    def __init__(self,x,y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('Map/blob.png')
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.move_direction = 1

    def update(self):
        self.rect.x += self.move_direction




def redrawGameWindow():
    global walkCount
    screen.blit(display,(0,0))

    blob_group.draw(screen)
    blob_group.update()

    if walkCount + 1 >=  27:
        walkCount = 0

    if moving_left:
        screen.blit(walkLeft[walkCount // 3],(player_rect.x-scroll[0],player_rect.y-scroll[1] ))
        walkCount += 1
            
    elif moving_right:
        screen.blit(walkRight[walkCount // 3],(player_rect.x-scroll[0],player_rect.y-scroll[1] ))
        walkCount += 1  


    else:
        screen.blit(player_image,(player_rect.x-scroll[0],player_rect.y-scroll[1]))     
    


    pygame.display.update() 
    


def load_map(path):
    f = open(path + '.txt','r')
    data = f.read()
    f.close()
    data = data.split('\n')
    game_map = []
    for row in data:
        game_map.append(list(row))
    return game_map         

game_map = load_map('Map/map')

background_objects = [[0.2,[500,200,250,3000]],[0.5,[750,30,200,4000]],[0.3,[1000,100,235,2000]],[0.5,[130,90,100,4000]],[0.6,[300,100,220,5000]]]

def collision_test(rect,tiles):
    hit_list = []
    for tile in tiles:
        if rect.colliderect(tile):
            hit_list.append(tile)
    return hit_list
    
def move(rect,movement,tiles):
    collision_types = {'top':False,'bottom':False,'right':False,'left':False}
    rect.x += movement[0]
    hit_list = collision_test(rect,tiles)
    for tile in hit_list:
        if movement[0] > 0:
            rect.right = tile.left
            collision_types['right'] = True
        elif movement[0] < 0:
            rect.left = tile.right
            collision_types['left'] = True
    rect.y += movement[1]           
    hit_list = collision_test(rect,tiles)
    for tile in hit_list:
        if movement[1] > 0:
            rect.bottom = tile.top
            collision_types['bottom'] = True
        elif movement[1] < 0:
            rect.top = tile.bottom
            collision_types['top'] = True   

    return rect, collision_types


moving_right = False
moving_left = False

moving_down = False

player_y_momentum = 0
air_timer = 0

player_rect = pygame.Rect(50,50,player_image.get_width(),player_image.get_height())

player_left = False
player_right = False
player_down = False 

jump_sound = pygame.mixer.Sound('jump.wav')
grass_sound = [pygame.mixer.Sound('grass_0.wav'),pygame.mixer.Sound('grass_1.wav')]

pygame.mixer.music.load('music.wav')
pygame.mixer.music.play(-1)



walkCount = 0

vel = 5


#Game loop
while True:
    display.fill((146,244,255))

    true_scroll[0] += (player_rect.x - true_scroll[0]-450)/20
    true_scroll[1] += (player_rect.y - true_scroll[1]-364)/20
 
    scroll = true_scroll.copy()
    scroll[0] = int(scroll[0])
    scroll[1] = int(scroll[1])

    pygame.draw.rect(display,(7,80,75),pygame.Rect(0,400,900,600))
    for background_object in background_objects:
        obj_rect = pygame.Rect(background_object[1][0]-scroll[0]*background_object[0],background_object[1][1]-scroll[1]*background_object[0],background_object[1][2],background_object[1][3])
        if background_objects[0] == 0.5:
            pygame.draw.rect(display,(255,0,0),obj_rect)
        else:
            pygame.draw.rect(display,(9,91,85),obj_rect)    

    
    blob_group = pygame.sprite.Group()
    
    tile_rects = []
    y=0
    for row in game_map:
        x=0
        for tile in row:
            if tile != '0': 
                tile_rects.append(pygame.Rect(x * TILE_SIZE, y * TILE_SIZE,TILE_SIZE,TILE_SIZE))
            if tile == '1':
                display.blit(dirt_image,(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]))
            if tile == '2':
                display.blit(grass_image,(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]))
            if tile == '3':
                display.blit(cobble_image,(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]))            
            if tile == '4':
                blob = Enemy(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]+2)
                blob_group.add(blob)

            x += 1
        y += 1
    
    
    
    
    player_movement = [0,0]
    if moving_right:
        player_movement[0] += vel
    if moving_left:
        player_movement[0] -= vel
    #________________________________________
    if moving_down:
        player_movement[1] += 7

    #________________________________________       
    player_movement[1] += player_y_momentum 
    player_y_momentum += 0.2
    if player_y_momentum > 3:   
        player_y_momentum = 3
      

    player_rect,collisions = move(player_rect,player_movement,tile_rects)           

    if collisions['bottom']:
        player_y_momentum = 0
        air_timer = 0
    else:
        air_timer += 1


    if collisions['top']:
        player_y_momentum = 0
        air_timer = 0
    else:
        air_timer += 0.1


    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                moving_right = True
                player_right = True
                player_left = False
                player_down = False

            elif event.key == K_LEFT:
                moving_left = True
                player_left = True
                player_right = False
                player_down = False

            #_________________________
            elif event.key == K_DOWN:
                moving_down = True
                player_down = True
                player_left = False
                player_right = False


            
            else:
                player_right = False
                player_left = False
                player_down = False
                walkCount = 0   

            if event.key == K_UP:
                if air_timer < 6:
                    player_y_momentum = -7.5
                    player_right = False
                    player_left = False
                    player_down = False
                    walkCount = 0
                    jump_sound.play()
                    jump_sound.set_volume(0.1)



        if event.type == KEYUP:
            if event.key == K_RIGHT:
                moving_right = False
                
            if event.key == K_LEFT:
                moving_left = False 

            if event.key == K_DOWN:
                moving_down = False
            
        
    
                
    
    redrawGameWindow()  
    

    surf = pygame.transform.scale(display,Window_SIZE)
    clock.tick(54)

我的敌人(blob)出现在屏幕上,但它没有在屏幕上移动。它也没有显示任何类型的错误。我在 Enemy 类中创建了一个 update()。实际上我是新手,所以请检查我是否把课弄错了。我是在错误的地方调用这个函数还是别的什么???请帮忙。

标签: pythonpygame

解决方案


您在应用程序循环中不断地在起始位置创建新的敌人。由于也在blob_group每一帧中创建了 ,所以前一帧的敌人被移除了。

在应用程序循环之前创建敌人,但在循环中移动它们:

blob_group = pygame.sprite.Group()    
tile_rects = []
for y, row in enumerate(game_map):
    for x, tile in enumerate(row):
        if tile != '0': 
           tile_rects.append(pygame.Rect(x * TILE_SIZE, y * TILE_SIZE,TILE_SIZE,TILE_SIZE))
        if tile == '4':
            blob = Enemy(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]+2)
            blob_group.add(blob)

#Game loop
while True:
    display.fill((146,244,255))

    # [...]

    # DELETE
    # blob_group = pygame.sprite.Group()
    # tile_rects = []

    for y, row in enumerate(game_map):
        for x, tile in enumerate(row):
            if tile == '1':
                display.blit(dirt_image,(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]))
            if tile == '2':
                display.blit(grass_image,(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]))
            if tile == '3':
                display.blit(cobble_image,(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]))            
    
    # [...]

完整示例:

import pygame, sys

clock = pygame.time.Clock()

from pygame.locals import *
pygame.mixer.pre_init(44100,-16,2,512)
pygame.init()

pygame.display.set_caption('THE GAME')#Window name

walkRight = [pygame.image.load('player_animations/R1.png'), pygame.image.load('player_animations/R2.png'), pygame.image.load('player_animations/R3.png'), pygame.image.load('player_animations/R4.png'), pygame.image.load('player_animations/R5.png'), pygame.image.load('player_animations/R6.png'), pygame.image.load('player_animations/R7.png'), pygame.image.load('player_animations/R8.png'), pygame.image.load('player_animations/R9.png')]
walkLeft = [pygame.image.load('player_animations/L1.png'), pygame.image.load('player_animations/L2.png'), pygame.image.load('player_animations/L3.png'), pygame.image.load('player_animations/L4.png'), pygame.image.load('player_animations/L5.png'), pygame.image.load('player_animations/L6.png'), pygame.image.load('player_animations/L7.png'), pygame.image.load('player_animations/L8.png'), pygame.image.load('player_animations/L9.png')]

Window_SIZE = (900,600)

screen = pygame.display.set_mode(Window_SIZE,0,32)

display = pygame.Surface((900,600))

player_image = pygame.image.load('player_animations/player_image.png')
player_image.set_colorkey((255,255,255))

grass_image = pygame.image.load('Map/Grassblock.png')
grass_image.set_colorkey((255,255,255))

dirt_image = pygame.image.load('Map/Dirtblock.png')

cobble_image = pygame.image.load('Map/Stoneblock.png')

TILE_SIZE = grass_image.get_width()

true_scroll = [0,0]

#ENEMIES
class Enemy(pygame.sprite.Sprite):
    def __init__(self,x,y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('Map/blob.png')
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.move_direction = 1

    def update(self):
        self.rect.x += self.move_direction




def redrawGameWindow():
    global walkCount
    screen.blit(display,(0,0))

    blob_group.draw(screen)
    blob_group.update()

    if walkCount + 1 >=  27:
        walkCount = 0

    if moving_left:
        screen.blit(walkLeft[walkCount // 3],(player_rect.x-scroll[0],player_rect.y-scroll[1] ))
        walkCount += 1
            
    elif moving_right:
        screen.blit(walkRight[walkCount // 3],(player_rect.x-scroll[0],player_rect.y-scroll[1] ))
        walkCount += 1  


    else:
        screen.blit(player_image,(player_rect.x-scroll[0],player_rect.y-scroll[1]))     
    


    pygame.display.update() 
    


def load_map(path):
    f = open(path + '.txt','r')
    data = f.read()
    f.close()
    data = data.split('\n')
    game_map = []
    for row in data:
        game_map.append(list(row))
    return game_map         

game_map = load_map('Map/map')

background_objects = [[0.2,[500,200,250,3000]],[0.5,[750,30,200,4000]],[0.3,[1000,100,235,2000]],[0.5,[130,90,100,4000]],[0.6,[300,100,220,5000]]]

def collision_test(rect,tiles):
    hit_list = []
    for tile in tiles:
        if rect.colliderect(tile):
            hit_list.append(tile)
    return hit_list
    
def move(rect,movement,tiles):
    collision_types = {'top':False,'bottom':False,'right':False,'left':False}
    rect.x += movement[0]
    hit_list = collision_test(rect,tiles)
    for tile in hit_list:
        if movement[0] > 0:
            rect.right = tile.left
            collision_types['right'] = True
        elif movement[0] < 0:
            rect.left = tile.right
            collision_types['left'] = True
    rect.y += movement[1]           
    hit_list = collision_test(rect,tiles)
    for tile in hit_list:
        if movement[1] > 0:
            rect.bottom = tile.top
            collision_types['bottom'] = True
        elif movement[1] < 0:
            rect.top = tile.bottom
            collision_types['top'] = True   

    return rect, collision_types


moving_right = False
moving_left = False

moving_down = False

player_y_momentum = 0
air_timer = 0

player_rect = pygame.Rect(50,50,player_image.get_width(),player_image.get_height())

player_left = False
player_right = False
player_down = False 

jump_sound = pygame.mixer.Sound('jump.wav')
grass_sound = [pygame.mixer.Sound('grass_0.wav'),pygame.mixer.Sound('grass_1.wav')]

pygame.mixer.music.load('music.wav')
pygame.mixer.music.play(-1)



walkCount = 0

vel = 5

blob_group = pygame.sprite.Group()
tile_rects = []
for y, row in enumerate(game_map):
    for x, tile in enumerate(row):
        if tile != '0': 
           tile_rects.append(pygame.Rect(x * TILE_SIZE, y * TILE_SIZE,TILE_SIZE,TILE_SIZE))
        if tile == '4':
            blob = Enemy(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]+2)
            blob_group.add(blob)

#Game loop
while True:
    display.fill((146,244,255))

    true_scroll[0] += (player_rect.x - true_scroll[0]-450)/20
    true_scroll[1] += (player_rect.y - true_scroll[1]-364)/20
 
    scroll = true_scroll.copy()
    scroll[0] = int(scroll[0])
    scroll[1] = int(scroll[1])

    pygame.draw.rect(display,(7,80,75),pygame.Rect(0,400,900,600))
    for background_object in background_objects:
        obj_rect = pygame.Rect(background_object[1][0]-scroll[0]*background_object[0],background_object[1][1]-scroll[1]*background_object[0],background_object[1][2],background_object[1][3])
        if background_objects[0] == 0.5:
            pygame.draw.rect(display,(255,0,0),obj_rect)
        else:
            pygame.draw.rect(display,(9,91,85),obj_rect)    

    for y, row in enumerate(game_map):
        for x, tile in enumerate(row):
            if tile == '1':
                display.blit(dirt_image,(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]))
            if tile == '2':
                display.blit(grass_image,(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]))
            if tile == '3':
                display.blit(cobble_image,(x*TILE_SIZE-scroll[0],y*TILE_SIZE-scroll[1]))            
       
    player_movement = [0,0]
    if moving_right:
        player_movement[0] += vel
    if moving_left:
        player_movement[0] -= vel
    #________________________________________
    if moving_down:
        player_movement[1] += 7

    #________________________________________       
    player_movement[1] += player_y_momentum 
    player_y_momentum += 0.2
    if player_y_momentum > 3:   
        player_y_momentum = 3
      

    player_rect,collisions = move(player_rect,player_movement,tile_rects)           

    if collisions['bottom']:
        player_y_momentum = 0
        air_timer = 0
    else:
        air_timer += 1


    if collisions['top']:
        player_y_momentum = 0
        air_timer = 0
    else:
        air_timer += 0.1


    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                moving_right = True
                player_right = True
                player_left = False
                player_down = False

            elif event.key == K_LEFT:
                moving_left = True
                player_left = True
                player_right = False
                player_down = False

            #_________________________
            elif event.key == K_DOWN:
                moving_down = True
                player_down = True
                player_left = False
                player_right = False


            
            else:
                player_right = False
                player_left = False
                player_down = False
                walkCount = 0   

            if event.key == K_UP:
                if air_timer < 6:
                    player_y_momentum = -7.5
                    player_right = False
                    player_left = False
                    player_down = False
                    walkCount = 0
                    jump_sound.play()
                    jump_sound.set_volume(0.1)



        if event.type == KEYUP:
            if event.key == K_RIGHT:
                moving_right = False
                
            if event.key == K_LEFT:
                moving_left = False 

            if event.key == K_DOWN:
                moving_down = False
            
        
    
                
    
    redrawGameWindow()  
    

    surf = pygame.transform.scale(display,Window_SIZE)
    clock.tick(54)

推荐阅读