Win 10
Python 3.9.5
Хотел внедрить в свой код игры, код, с помощью которого игрок может поднимать и двигать спрайты, но почему-то при поднятии спрайты просто улетают за экран, вместо того, чтоб "приклеиваться" к игроку.
Может кто знает в чем проблема?
Моя попытка внедрить:
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
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)