Как добавить код из carinput в cardriver, так чтобы он заменил класс Player и осталась коллизия и слежение за камерой
СARINPUT
import pygame, sys
class Car(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.original_image = pygame.image.load('data/fr1.png')
self.image = self.original_image
self.rect = self.image.get_rect(center = (640, 360))
self.angle = 0
self.rotation_speed = 1.9
self.direction = 0
self.forward = pygame.math.Vector2(0,-1)
self.active = False
def set_rotation(self):
if self.direction == 1:
self.angle -= self.rotation_speed
if self.direction == -1:
self.angle += self.rotation_speed
self.image = pygame.transform.rotozoom(self.original_image,self.angle,1)
self.rect = self.image.get_rect(center = self.rect.center)
def get_rotation(self):
if self.direction == 1:
self.forward.rotate_ip(self.rotation_speed)
if self.direction == -1:
self.forward.rotate_ip(-self.rotation_speed)
def accelerate(self):
if self.active:
self.rect.center += self.forward * 5
def update(self):
self.set_rotation()
self.get_rotation()
self.accelerate()
pygame.init()
screen = pygame.display.set_mode((1280,720))
clock = pygame.time.Clock()
bg_track = pygame.image.load('data/wer.jpg' )
car = pygame.sprite.GroupSingle(Car())
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d: car.sprite.direction += 1
if event.key == pygame.K_a: car.sprite.direction -= 1
if event.key == pygame.K_w: car.sprite.active = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_d: car.sprite.direction -= 1
if event.key == pygame.K_a: car.sprite.direction += 1
if event.key == pygame.K_w: car.sprite.active = False
screen.blit(bg_track,(0,0))
car.draw(screen)
car.update()
pygame.display.update()
clock.tick(120)
CARDRIVER
import os
import pygame
pygame.init()
pygame.key.set_repeat(200, 70)
FPS = 60
WIDTH = 1920
HEIGHT = 1080
title = "CarDriver"
pygame.display.set_caption(title)
def load_image(name, colorkey=None):
# Загрузка спрайтов и их подправка размера
fullname = os.path.join('data', name)
try:
image = pygame.image.load(fullname)
except pygame.error as message:
print('Cannot load image:', name)
raise SystemExit(message)
image = image.convert_alpha()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey)
if name == 'wall1.png':
image = pygame.transform.scale(image, (64, 64))
if name == 'roof.png':
image = pygame.transform.scale(image, (64, 64))
if name == 'roof1.png':
image = pygame.transform.scale(image, (64, 64))
if name == 'water.png':
image = pygame.transform.scale(image, (64, 64))
if name == 'floor.png':
image = pygame.transform.scale(image, (64, 64))
if name == 'floor0.png':
image = pygame.transform.scale(image, (64, 64))
if name == 'Rock.png':
image = pygame.transform.scale(image, (64, 64))
if name == 'Rock1.png':
image = pygame.transform.scale(image, (64, 64))
if name == 'Rock2.png':
image = pygame.transform.scale(image, (64, 64))
if name == 'grass.jpg':
image = pygame.transform.scale(image, (64, 64))
for i in range(1, 7):
if name == 'fr1.png':
image = pygame.transform.scale(image, (45, 75))
return image
def load_level(filename):
filename = "data/" + filename
with open(filename, 'r') as mapFile:
level_map = [line.strip() for line in mapFile]
max_width = max(map(len, level_map))
return list(map(lambda x: x.ljust(max_width, '.'), level_map)) # там где нет знаков будет печатать точки
def generate_level(level):
new_player, x, y = None, None, None
walls = []
global gl_spisok
for y in range(len(level)):
for x in range(len(level[y])):
# Текстуры дорог
if level[y][x] == '.':
Tile('empty', x, y)
elif level[y][x] == '|':
Rock = Tile('Rock', x, y)
elif level[y][x] == ',':
Rock1 = Tile('Rock1', x, y)
elif level[y][x] == '-':
Rock2 = Tile('Rock2', x, y)
elif level[y][x] == 't':
grass = Tile('grass', x, y)
#Дома и вода
elif level[y][x] == 'd':
wall3 = Tile('wall3', x, y)
walls.append(wall3)
elif level[y][x] == '#':
roof1 = Tile('roof1', x, y)
walls.append(roof1)
elif level[y][x] == 'q':
water = Tile('water1', x, y)
walls.append(water)
elif level[y][x] == 'w':
water = Tile('water', x, y)
walls.append(water)
#NPC
elif level[y][x] == '!':
Tile('empty', x, y)
#Player
elif level[y][x] == 'x':
Tile('empty', x, y)
new_player = Player(x, y)
elif level[y][x] == 'e':
Tile('empty', x, y)
elif level[y][x] == 'h':
Tile('empty', x, y)
return new_player, x, y, pygame.sprite.Group(walls)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
player = None
all_sprites = pygame.sprite.Group()
tiles_group = pygame.sprite.Group()
player_group = pygame.sprite.Group()
tile_images = {'roof1': load_image('roof1.png'),
'empty': load_image('floor.png'),
'water': load_image('water.png'),
'Rock': load_image('Rock.png'),
'Rock1': load_image('Rock1.png'),
'Rock2': load_image('Rock2.png'),
'grass': load_image('grass.jpg')}
tile_width, tile_height = 64, 64
class Tile(pygame.sprite.Sprite):
def __init__(self, tile_type, pos_x, pos_y):
super().__init__(tiles_group, all_sprites)
self.image = tile_images[tile_type]
self.rect = self.image.get_rect().move(tile_width * pos_x, tile_height * pos_y)
# Создаем тело объекта и раставляем спрайт на карте
class Player(pygame.sprite.Sprite):
def __init__(self, pos_x, pos_y):
super().__init__(player_group, all_sprites)
self.images = []
for i in range(1, 7):
self.images.append(load_image(f'fr{str(i)}.png'))
self.index = 0
self.image = self.images[self.index]
self.rect = self.image.get_rect().move(tile_width * pos_x + 15, tile_height * pos_y + 5)
self.speed = 30
self.alive = True
def get_position(self, obstacles):
if self.x_vel:
self.check_collisions((self.x_vel, 0), 0, obstacles)
if self.y_vel:
self.check_collisions((0, self.y_vel), 1, obstacles)
def check_keys(self, keys):
self.x_vel = 0
self.y_vel = 0
if self.alive:
if keys == pygame.K_LEFT or keys == pygame.K_a:
self.x_vel -= self.speed
self.image = pygame.transform.flip(self.images[self.index], True, False)
if keys == pygame.K_RIGHT or keys == pygame.K_d:
self.x_vel += self.speed
if keys == pygame.K_UP or keys == pygame.K_w:
self.y_vel -= self.speed
if keys == pygame.K_DOWN or keys == pygame.K_s:
self.y_vel += self.speed
def update(self, obstacles, keys):
self.index += 1
if self.index >= len(self.images):
self.index = 0
self.image = self.images[self.index]
self.check_keys(keys)
self.get_position(obstacles)
def check_collisions(self, offset, index, obstacles):
self.rect[index] += offset[index]
while pygame.sprite.spritecollideany(self, obstacles):
self.rect[index] += (1 if offset[index] < 0 else -1)
class Watch_camera:
def __init__(self, field_size):
self.dx = 0
self.dy = 0
self.field_size = field_size
def apply(self, obj):
obj.rect.x += self.dx
if obj.rect.x < -obj.rect.width:
obj.rect.x += (self.field_size[0] + 1) * obj.rect.width
if obj.rect.x >= (self.field_size[0]) * obj.rect.width:
obj.rect.x += -obj.rect.width * (1 + self.field_size[0])
obj.rect.y += self.dy
if obj.rect.y < -obj.rect.height:
obj.rect.y += (self.field_size[1] + 1) * obj.rect.height
if obj.rect.y >= (self.field_size[1]) * obj.rect.height:
obj.rect.y += -obj.rect.height * (1 + self.field_size[1])
def update(self, target):
self.dx = -(target.rect.x + target.rect.w // 2 - WIDTH // 2)
self.dy = -(target.rect.y + target.rect.h // 2 - HEIGHT // 2)
def lev1():
player, level_x, level_y, obstacle = generate_level(load_level("lv1.txt"))
camera = Watch_camera((level_x, level_y))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
player.update(obstacle, event.key)
camera.update(player)
for sprite in all_sprites:
camera.apply(sprite)
tiles_group.draw(screen)
if player.alive:
player_group.draw(screen)
pygame.display.flip()
clock.tick(FPS)
lev1()