Спрайты не подбираются так как нужно, а улетают за экран

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
Win 10
Python 3.9.5
cycler 0.10.0
kiwisolver 1.3.1
matplotlib 3.4.2
numpy 1.20.3
perlin-noise 1.7
Pillow 8.2.0
pip 21.1.2
pygame 2.0.1
pyparsing 2.4.7
python-dateutil 2.8.1
setuptools 56.0.0
six 1.16.0

Хотел внедрить в свой код игры, код, с помощью которого игрок может поднимать и двигать спрайты, но почему-то при поднятии спрайты просто улетают за экран, вместо того, чтоб "приклеиваться" к игроку.
Может кто знает в чем проблема?



Моя попытка внедрить:

Python:
import pygame
import sys
import time
import random
from pygame import Surface, draw
from pygame.locals import *
from pygame.display import update

WIDTH = 700
HEIGHT = 700
from pygame.constants import K_DOWN, K_LEFT, K_RIGHT, K_SPACE, K_UP, QUIT

ground_img = pygame.image.load('ground3.png')
ground_img.set_colorkey((0, 0, 0))
ground_img2 = pygame.image.load("ground5.png")
ground_img2.set_colorkey((0, 0, 0))
ground_img3 = pygame.image.load("ground_hole.png")

clock = pygame.time.Clock()

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption("game base")
display = pygame.Surface((300, 300))

ground_dict = []  # словарь {ряд-номер клетки-номер слоя: название картинки}

# читаем данные карты из файла и заполняем ими словарь
with open('map.txt') as f:
    map_data = f
    for y, row in enumerate(map_data):
        for x, tile in enumerate(row):
            if tile:
                ground_dict.append([int(f'{y}'),int(f'{x}'), 'stone'])
            if random.randint(0, 2):
                ground_dict.append([int(f'{y}'), int(f'{x}'), 'ground'])

class Wall(pygame.sprite.Sprite):
    """Wall a player can run into."""
    def __init__(self, x, y):
        colli_list = [random.randint(1, 150), random.randint(0, 100)]
        x,  y = colli_list
        super().__init__()
        self.image = ground_img
        # Make the "passed-in" location the top left corner.
        self.rect = self.image.get_rect(center=(x, y))
        
class Player(pygame.sprite.Sprite):
    carry_block_list = []
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = player_img
        self.image.set_colorkey((0, 0, 0))
        self.rect = self.image.get_rect()
        self.speedx = 0
        self.speedy = 0
        
    def update(self):
        self.rect.x += self.speedx

        # Did this update cause us to hit a wall?
        block_hit_list = pygame.sprite.spritecollide(self, self.walls, False, pygame.sprite.collide_mask)
        for block in block_hit_list:
            # If we are moving right, set our right side to the left side of
            # the item we hit
            if self.speedx > 0:
                self.rect.right = block.rect.right
            else:
                # Otherwise if we are moving left, do the opposite.
                self.rect.left = block.rect.left

        # Move up/down.
        self.rect.y += self.speedy
        # Check and see if we hit anything.
        block_hit_list = pygame.sprite.spritecollide(self, self.walls, False, pygame.sprite.collide_mask)
        for block in block_hit_list:
            # Reset our position based on the top/bottom of the object.
            if self.speedy > 0:
                self.rect.bottom = block.rect.bottom
            else:
                self.rect.top = block.rect.top
        self.mask = pygame.mask.from_surface(self.image)
        
        
        for grape in self.carry_block_list:
            grape.rect.x += x
            grape.rect.y += y
        
        for wall in self.carry_block_list:
            wall.rect.x += x
            wall.rect.y += y


class Bush(pygame.sprite.Sprite):
    def __init__(self, x, y):
        rand_list = [random.randint(1, 400), random.randint(0, 400)]
        x,  y = rand_list
        super().__init__()
        self.image = bush_img
        self.image.set_colorkey((0, 0, 0))
        self.rect = self.image.get_rect(center=(x +  50, y + 50))

class Bush2(pygame.sprite.Sprite):
    def __init__(self, x, y):
        rand_list = [random.randint(1, 400), random.randint(0, 400)]
        x,  y = rand_list
        super().__init__()
        self.image = bush2_img
        self.image.set_colorkey((0, 0, 0))
        self.rect = self.image.get_rect(topleft=(x, y))

grape_img = pygame.image.load('grapes.png')


class Grape(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super(Grape, self).__init__()
        self.image = grape_img
        
        self.rect = self.image.get_rect(topleft=(x, y))

wall_list = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
collactable_list = pygame.sprite.Group()

for i in range(50):
    grape = Grape(x, y)

    grape.rect.x = random.randrange(WIDTH)
    grape.rect.y = random.randrange(HEIGHT)
    collactable_list.add(grape)
    all_sprites.add(grape)

GRAPE = 1
resources = [GRAPE]


inventory = {
    GRAPE: 0
}

textures = {GRAPE: pygame.image.load('grapes.png')}


bush_img = pygame.image.load('bush.png')
bush_img = pygame.transform.scale(bush_img, (50, 50))

bush2_img = pygame.image.load('bush2.png')
bush2_img = pygame.transform.scale(bush2_img, (50, 50))




ground_img = pygame.image.load('ground3.png')


player_img = pygame.image.load('mainhero.png').convert()
player = Player()
player.walls = wall_list
all_sprites.add(player)


walls = [Wall(x, y), Wall(x, y), Wall(x, y), Bush2(x, y), Bush(x, y)]
wall_list.add(walls)
collactable_list.add(walls)
all_sprites.add(walls)

WHITE = (255,255,255)
BLACK = (0,0,0)
INVFONT = pygame.font.Font('freesansbold.ttf', 18)

while True:
    display.fill(BLACK)
    # проходим в цикле по словарю
    for key, value, type in ground_dict:
        # получаем ряд, номер клетки и номер слоя
        y, x, n = key, value, type

        # определяем нужную картинку для клетки
        z = ground_img2 if type == 'ground' else ground_img
        # отрисовываем в зависимости от номера слоя
        if z == ground_img2:
            display.blit(z, (150 + x * 10 - y * 10, 100 + x * 5 + y * 5 - 14))
        elif z == ground_img:
            display.blit(z, (150 + x * 10 - y * 10, 100 + x * 5 + y * 5 - 14)) 
    
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                player.speedx = -3
            elif event.key == pygame.K_d:
                player.speedx = 3
            elif event.key == pygame.K_w:
                player.speedy = -3
            elif event.key == pygame.K_s:
                player.speedy = 3

            #if event.key == pygame.K_SPACE:
                # inventory[GRAPE] += 1
                # blocks_hit_list = pygame.sprite.spritecollide(player, collactable_list, False) 
                # player.carry_block_list = blocks_hit_list

            if event.key == pygame.K_e:
                # When the mouse button is pressed, see if we are in contact with
                # other sprites:
                blocks_hit_list = pygame.sprite.spritecollide(player, wall_list, False)                 
                # Set the list of blocks we are in contact with as the list of
                # blocks being carried.
                player.carry_block_list = blocks_hit_list   
            if event.key == pygame.K_q:
                # When we let up on the mouse, set the list of blocks we are
                # carrying as empty.
                player.carry_block_list = [] 
                
        elif event.type == pygame.KEYUP:
                if event.key == pygame.K_a and player.speedx < 0:
                    player.speedx = 0
                elif event.key == pygame.K_d and player.speedx > 0:
                    player.speedx = 0
                elif event.key == pygame.K_w and player.speedy < 0:
                    player.speedy = 0
                elif event.key == pygame.K_s and player.speedy > 0:
                    player.speedy = 0
            
                
    


    all_sprites.update()   
    clock.tick(60)
    
    screen.blit(pygame.transform.scale(display, screen.get_size()), (0, 0))
    all_sprites.draw(screen)

    placePosition = 10
    for item in resources:
        screen.blit(textures[item], (placePosition, 15*40+20))
        placePosition += 30
        textObj = INVFONT.render(str(inventory[item]), True, BLACK, WHITE)
        screen.blit(textObj,(placePosition,15*40+20))
        placePosition += 100
    pygame.display.update()
    time.sleep(0)
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
спрайты просто улетают за экран, вместо того, чтоб "приклеиваться" к игроку
Так происходит потому что в коде вы увеличиваете координаты этих спрайтов больше размеров экрана.
Может кто знает в чем проблема?
Проблема в этих строках кода:
Python:
for grape in self.carry_block_list:
    grape.rect.x += x       
    grape.rect.y += y
        
for wall in self.carry_block_list:
    wall.rect.x += x
    wall.rect.y += y
Сделать чтобы спрайты приклеивались к игроку можно так например:
задать смещение игроку чтобы спрайт не накладывался на игрока
Python:
class Player(pygame.sprite.Sprite):
    carry_block_list = []

    def __init__(self):
        ...
        self.shift = 20
и потом задавать перемещаемому спрайту координаты равные координатам игрока плюс смещение:
Python:
for grape in self.carry_block_list:
    grape.rect.x += self.rect.x + self.shift       
    grape.rect.y += self.rect.y
        
for wall in self.carry_block_list:
    wall.rect.x += self.rect.x + self.shift
    wall.rect.y += self.rect.y
 
  • Мне нравится
Реакции: Student

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
Так происходит потому что в коде вы увеличиваете координаты этих спрайтов больше размеров экрана.

Проблема в этих строках кода:
Python:
for grape in self.carry_block_list:
    grape.rect.x += x      
    grape.rect.y += y
       
for wall in self.carry_block_list:
    wall.rect.x += x
    wall.rect.y += y
Сделать чтобы спрайты приклеивались к игроку можно так например:
задать смещение игроку чтобы спрайт не накладывался на игрока
Python:
class Player(pygame.sprite.Sprite):
    carry_block_list = []

    def __init__(self):
        ...
        self.shift = 20
и потом задавать перемещаемому спрайту координаты равные координатам игрока плюс смещение:
Python:
for grape in self.carry_block_list:
    grape.rect.x += self.rect.x + self.shift      
    grape.rect.y += self.rect.y
       
for wall in self.carry_block_list:
    wall.rect.x += self.rect.x + self.shift
    wall.rect.y += self.rect.y
Добавил то что вы написали, но ничего не изменилось, все также спрайты улетают
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
Добавил то что вы написали, но ничего не изменилось, все также спрайты улетают
Ошибся немного, вот так нужно было:
Python:
for grape in self.carry_block_list:
    grape.rect.x = self.rect.x + self.shift       
    grape.rect.y = self.rect.y
        
for wall in self.carry_block_list:
    wall.rect.x = self.rect.x + self.shift
    wall.rect.y = self.rect.y
 

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
Ошибся немного, вот так нужно было:
Python:
for grape in self.carry_block_list:
    grape.rect.x = self.rect.x + self.shift      
    grape.rect.y = self.rect.y
       
for wall in self.carry_block_list:
    wall.rect.x = self.rect.x + self.shift
    wall.rect.y = self.rect.y
Добавил, теперь игрок поднимает спрайт и улетает вместе с ним)
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
Добавил, теперь игрок поднимает спрайт и улетает вместе с ним)
Видимо не так добавили или не туда - нужно вместо этих строк кода:
Python:
for grape in self.carry_block_list:
    grape.rect.x += x       
    grape.rect.y += y
        
for wall in self.carry_block_list:
    wall.rect.x += x
    wall.rect.y += y
 

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
Видимо не так добавили или не туда - нужно вместо этих строк кода:
Python:
for grape in self.carry_block_list:
    grape.rect.x += x      
    grape.rect.y += y
       
for wall in self.carry_block_list:
    wall.rect.x += x
    wall.rect.y += y
вот весь код, вроде туда добавил
Python:
import pygame
import sys
import time
import random
from pygame import Surface, draw
from pygame.locals import *
from pygame.display import update

WIDTH = 700
HEIGHT = 700
from pygame.constants import K_DOWN, K_LEFT, K_RIGHT, K_SPACE, K_UP, QUIT

ground_img = pygame.image.load('ground3.png')
ground_img.set_colorkey((0, 0, 0))
ground_img2 = pygame.image.load("ground5.png")
ground_img2.set_colorkey((0, 0, 0))
ground_img3 = pygame.image.load("ground_hole.png")

clock = pygame.time.Clock()

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption("game base")
display = pygame.Surface((300, 300))

ground_dict = []  # словарь {ряд-номер клетки-номер слоя: название картинки}

# читаем данные карты из файла и заполняем ими словарь
with open('map.txt') as f:
    map_data = f
    for y, row in enumerate(map_data):
        for x, tile in enumerate(row):
            if tile:
                ground_dict.append([int(f'{y}'),int(f'{x}'), 'stone'])
            if random.randint(0, 2):
                ground_dict.append([int(f'{y}'), int(f'{x}'), 'ground'])

class Wall(pygame.sprite.Sprite):
    """Wall a player can run into."""
    def __init__(self, x, y):
        colli_list = [random.randint(1, 150), random.randint(0, 100)]
        x,  y = colli_list
        super().__init__()
        self.image = ground_img
        # Make the "passed-in" location the top left corner.
        self.rect = self.image.get_rect(center=(x, y))
        
class Player(pygame.sprite.Sprite):
    carry_block_list = []
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = player_img
        self.image.set_colorkey((0, 0, 0))
        self.rect = self.image.get_rect()
        self.speedx = 0
        self.speedy = 0
        self.shift = 20
        
    def update(self):
        self.rect.x += self.speedx

        # Did this update cause us to hit a wall?
        block_hit_list = pygame.sprite.spritecollide(self, self.walls, False, pygame.sprite.collide_mask)
        for block in block_hit_list:
            # If we are moving right, set our right side to the left side of
            # the item we hit
            if self.speedx > 0:
                self.rect.right = block.rect.right
            else:
                # Otherwise if we are moving left, do the opposite.
                self.rect.left = block.rect.left

        # Move up/down.
        self.rect.y += self.speedy
        # Check and see if we hit anything.
        block_hit_list = pygame.sprite.spritecollide(self, self.walls, False, pygame.sprite.collide_mask)
        for block in block_hit_list:
            # Reset our position based on the top/bottom of the object.
            if self.speedy > 0:
                self.rect.bottom = block.rect.bottom
            else:
                self.rect.top = block.rect.top
        self.mask = pygame.mask.from_surface(self.image)
        
        
        for grape in self.carry_block_list:
            grape.rect.x = self.rect.x + self.shift       
            grape.rect.y = self.rect.y
        
        for wall in self.carry_block_list:
            wall.rect.x = self.rect.x + self.shift
            wall.rect.y = self.rect.y


class Bush(pygame.sprite.Sprite):
    def __init__(self, x, y):
        rand_list = [random.randint(1, 400), random.randint(0, 400)]
        x,  y = rand_list
        super().__init__()
        self.image = bush_img
        self.image.set_colorkey((0, 0, 0))
        self.rect = self.image.get_rect(center=(x +  50, y + 50))

class Bush2(pygame.sprite.Sprite):
    def __init__(self, x, y):
        rand_list = [random.randint(1, 400), random.randint(0, 400)]
        x,  y = rand_list
        super().__init__()
        self.image = bush2_img
        self.image.set_colorkey((0, 0, 0))
        self.rect = self.image.get_rect(topleft=(x, y))

grape_img = pygame.image.load('grapes.png')


class Grape(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super(Grape, self).__init__()
        self.image = grape_img
        
        self.rect = self.image.get_rect(topleft=(x, y))

wall_list = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
collactable_list = pygame.sprite.Group()

for i in range(50):
    grape = Grape(x, y)

    grape.rect.x = random.randrange(WIDTH)
    grape.rect.y = random.randrange(HEIGHT)
    collactable_list.add(grape)
    all_sprites.add(grape)

GRAPE = 1
resources = [GRAPE]


inventory = {
    GRAPE: 0
}

textures = {GRAPE: pygame.image.load('grapes.png')}


bush_img = pygame.image.load('bush.png')
bush_img = pygame.transform.scale(bush_img, (50, 50))

bush2_img = pygame.image.load('bush2.png')
bush2_img = pygame.transform.scale(bush2_img, (50, 50))




ground_img = pygame.image.load('ground3.png')


player_img = pygame.image.load('mainhero.png').convert()
player = Player()
player.walls = wall_list
all_sprites.add(player)


walls = [Wall(x, y), Wall(x, y), Wall(x, y), Bush2(x, y), Bush(x, y)]
wall_list.add(walls)
collactable_list.add(walls)
all_sprites.add(walls)

WHITE = (255,255,255)
BLACK = (0,0,0)
INVFONT = pygame.font.Font('freesansbold.ttf', 18)

while True:
    display.fill(BLACK)
    # проходим в цикле по словарю
    for key, value, type in ground_dict:
        # получаем ряд, номер клетки и номер слоя
        y, x, n = key, value, type

        # определяем нужную картинку для клетки
        z = ground_img2 if type == 'ground' else ground_img
        # отрисовываем в зависимости от номера слоя
        if z == ground_img2:
            display.blit(z, (150 + x * 10 - y * 10, 100 + x * 5 + y * 5 - 14))
        elif z == ground_img:
            display.blit(z, (150 + x * 10 - y * 10, 100 + x * 5 + y * 5 - 14)) 
    
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                player.speedx = -3
            elif event.key == pygame.K_d:
                player.speedx = 3
            elif event.key == pygame.K_w:
                player.speedy = -3
            elif event.key == pygame.K_s:
                player.speedy = 3

            if event.key == pygame.K_SPACE:
                 inventory[GRAPE] += 1
                 blocks_hit_list = pygame.sprite.spritecollide(player, collactable_list, False) 
                 player.carry_block_list = blocks_hit_list

            if event.key == pygame.K_e:
                # When the mouse button is pressed, see if we are in contact with
                # other sprites:
                blocks_hit_list = pygame.sprite.spritecollide(player, wall_list, False)                 
                # Set the list of blocks we are in contact with as the list of
                # blocks being carried.
                player.carry_block_list = blocks_hit_list   
            if event.key == pygame.K_q:
                # When we let up on the mouse, set the list of blocks we are
                # carrying as empty.
                player.carry_block_list = [] 
                
        elif event.type == pygame.KEYUP:
                if event.key == pygame.K_a and player.speedx < 0:
                    player.speedx = 0
                elif event.key == pygame.K_d and player.speedx > 0:
                    player.speedx = 0
                elif event.key == pygame.K_w and player.speedy < 0:
                    player.speedy = 0
                elif event.key == pygame.K_s and player.speedy > 0:
                    player.speedy = 0
            
                
    


    all_sprites.update()   
    clock.tick(60)
    
    screen.blit(pygame.transform.scale(display, screen.get_size()), (0, 0))
    all_sprites.draw(screen)

    placePosition = 10
    for item in resources:
        screen.blit(textures[item], (placePosition, 15*40+20))
        placePosition += 30
        textObj = INVFONT.render(str(inventory[item]), True, BLACK, WHITE)
        screen.blit(textObj,(placePosition,15*40+20))
        placePosition += 100
    pygame.display.update()
    time.sleep(0)
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
вот весь код, вроде туда добавил
Проверил спрайты не улетают. Перетаскивание работает. Может вы другой файл запускаете.
 

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
Проверил спрайты не улетают. Перетаскивание работает. Может вы другой файл запускаете.
вот видео с демонстрацией проблемы
1
 

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
вот видео с демонстрацией проблемы
1
сейчас исправлю, ибо не записалась сама игра
 

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
Проверил спрайты не улетают. Перетаскивание работает. Может вы другой файл запускаете.
вот
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
В видео у вас версия pygame 2.01. Я проверял на 1.9.6 возможно из-за этого поведение отличается. Нужно проверить.
 

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
В видео у вас версия pygame 2.01. Я проверял на 1.9.6 возможно из-за этого поведение отличается. Нужно проверить.
а может быть из-за того что и у игрока и у блока есть коллизия? И может они как-то друг друга толкают и из-за этого улетают?
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
Проверил на версии pygame 2.0.1 тоже все работает.
а может быть из-за того что и у игрока и у блока есть коллизия? И может они как-то друг друга толкают и из-за этого улетают?
Попробуйте убрать коллизии. У меня вашу ошибку воспроизвести не получается (работает и с коллизиями и без).
 

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
Проверил на версии pygame 2.0.1 тоже все работает.

Попробуйте убрать коллизии. У меня вашу ошибку воспроизвести не получается (работает и с коллизиями и без).
изменил эту часть кода и вот что вышло
Python:
for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                player.speedx = -3
            elif event.key == pygame.K_d:
                player.speedx = 3
            elif event.key == pygame.K_w:
                player.speedy = -3
            elif event.key == pygame.K_s:
                player.speedy = 3

            if event.key == pygame.K_SPACE:
                 inventory[GRAPE] += 1
                 blocks_hit_list = pygame.sprite.spritecollide(player, collactable_list, False) 
                 player.carry_block_list = blocks_hit_list

            if event.key == pygame.K_e:
                # When the mouse button is pressed, see if we are in contact with
                # other sprites:
                blocks_hit_list = pygame.sprite.spritecollide(player, wall_list, False)                 
                # Set the list of blocks we are in contact with as the list of
                # blocks being carried.
                player.carry_block_list = blocks_hit_list   
            if event.key == pygame.K_q:
                # When we let up on the mouse, set the list of blocks we are
                # carrying as empty.
                player.carry_block_list = [] 
                
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_a and player.speedx < 0:
                player.speedx = 0
            elif event.key == pygame.K_d and player.speedx > 0:
                player.speedx = 0
            elif event.key == pygame.K_w and player.speedy < 0:
                player.speedy = 0
            elif event.key == pygame.K_s and player.speedy > 0:
                player.speedy = 0

            
            if event.key == pygame.K_SPACE:
                 inventory[GRAPE] += 1
                 blocks_hit_list = pygame.sprite.spritecollide(player, collactable_list, False) 
                 player.carry_block_list = blocks_hit_list

            if event.key == pygame.K_e:
                # When the mouse button is pressed, see if we are in contact with
                # other sprites:
                blocks_hit_list = pygame.sprite.spritecollide(player, wall_list, False)                 
                # Set the list of blocks we are in contact with as the list of
                # blocks being carried.
                player.carry_block_list = blocks_hit_list   
            if event.key == pygame.K_q:
                # When we let up on the mouse, set the list of blocks we are
                # carrying as empty.
                player.carry_block_list = []

и теперь с обьектом без коллизии (Grape) работает, а со "стенами" нет. игрок сам начинает двигаться за экран, но если нажать кнопку влево то он все-таки идет, если отпустить он улетает.
 

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
Проверил на версии pygame 2.0.1 тоже все работает.

Попробуйте убрать коллизии. У меня вашу ошибку воспроизвести не получается (работает и с коллизиями и без).
понял в чем была проблема, self.shift нужно было изменить, чтоб коллизии игрока и спрайта не пересекались, теперь все работает как нужно
 

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
Проверил на версии pygame 2.0.1 тоже все работает.

Попробуйте убрать коллизии. У меня вашу ошибку воспроизвести не получается (работает и с коллизиями и без).
У меня остался еще один вопрос, как сделать так чтоб игрок клал блоки только по нужным мне координатам, а не там где он находиться сейчас. Я хочу чтоб блоки нельзя было класть друг в друга, чтоб они по определенным координатам укладывались, не подскажете как это можно реализовать?
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
понял в чем была проблема, self.shift нужно было изменить, чтоб коллизии игрока и спрайта не пересекались, теперь все работает как нужно
У меня такой проблемы не было видимо потому что расположение спрайтов в файле map.txt другое и возможно размер спрайтов тоже отличался.
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
Я хочу чтоб блоки нельзя было класть друг в друга, чтоб они по определенным координатам укладывались, не подскажете как это можно реализовать?
Можно попробовать проверять что игрок не пересекается с блоком и только тогда отпускать блок.
Примерно так:
Python:
if event.key == pygame.K_q:
    # When we let up on the mouse, set the list of blocks we are
    # carrying as empty.
    blocks_hit_list = pygame.sprite.spritecollide(player, wall_list, False)
    # если игрок не пересекается со спрайтом блока
    if len(blocks_hit_list) == 0:
        player.carry_block_list = []
 

григорий5643

Новичок
Пользователь
Июн 23, 2021
33
1
8
Можно попробовать проверять что игрок не пересекается с блоком и только тогда отпускать блок.
Примерно так:
Python:
if event.key == pygame.K_q:
    # When we let up on the mouse, set the list of blocks we are
    # carrying as empty.
    blocks_hit_list = pygame.sprite.spritecollide(player, wall_list, False)
    # если игрок не пересекается со спрайтом блока
    if len(blocks_hit_list) == 0:
        player.carry_block_list = []
почему-то теперь не получается поставить блок, он никак не реагирует на кнопку
 

Форум IT Специалистов