Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- pygame.init()
- win = pygame.display.set_mode((800, 800))
- pygame.display.set_caption("Scrolling game")
- #declare variables
- # for a player
- moving_left = False
- moving_right = False
- jump = False
- TILE_SIZE = 32
- # for a map
- scrollx = 0
- #creating_world
- with open('world.txt') as world:
- reader = world.read()
- world_data = reader.split("\n")
- world.close()
- class Square(pygame.sprite.Sprite):
- def __init__(self, x, y):
- pygame.sprite.Sprite.__init__(self)
- self.rect = pygame.Rect(x, y, 32, 32)
- self.can_jump = True
- self.vely = -30
- def draw(self):
- pygame.draw.rect(win, (255, 80, 80), self.rect)
- def move(self):
- global scrollx, jump
- Gravity = 3
- dx = 0
- dy = 0
- dy += Gravity
- if moving_left:
- dx -= 4
- elif moving_right:
- dx += 4
- if jump:
- dy += self.vely
- self.vely += 1
- if self.vely == 0:
- jump = False
- self.can_jump = True
- self.vely = -30
- for tile in obstacle_list:
- if self.rect.bottom >= tile.y and jump == False:
- dy = 0
- scrollx = -dx
- self.rect.x += dx
- self.rect.y += dy
- class Block(pygame.sprite.Sprite):
- def __init__(self, x, y, width, height, color, name_file):
- pygame.sprite.Sprite.__init__(self)
- self.rect = pygame.Rect(x, y, width, height)
- self.color = color
- self.image = pygame.transform.scale(pygame.image.load(f'blocks/{name_file}'), (width, height))
- def move(self):
- self.rect.x += scrollx
- Player = Square(400, 400)
- run = True
- Dirt_group = pygame.sprite.Group()
- Grass_group = pygame.sprite.Group()
- Clock = pygame.time.Clock()
- obstacle_list = []
- count_loads = 0
- while run:
- Clock.tick(80)
- win.fill((255, 124, 255))
- if count_loads != 1:
- y = 0
- for row in world_data:
- x = 0
- for tile in row:
- if tile == '1':
- dirt = Block(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE, (70, 27, 2), 'dirt.png')
- Dirt_group.add(dirt)
- if tile == '2':
- grass = Block(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE, (29, 194, 12), 'grass.png')
- Grass_group.add(grass)
- if tile != '0':
- obstacle_list.append(pygame.Rect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE))
- x += 1
- y += 1
- count_loads += 1
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- run = False
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_d:
- moving_right = True
- if event.key == pygame.K_a:
- moving_left = True
- if event.key == pygame.K_SPACE and Player.can_jump:
- jump = True
- Player.can_jump = False
- if event.type == pygame.KEYUP:
- if event.key == pygame.K_d:
- moving_right = False
- if event.key == pygame.K_a:
- moving_left = False
- Grass_group.update()
- Dirt_group.update()
- Grass_group.draw(win)
- Dirt_group.draw(win)
- Player.draw()
- Player.move()
- pygame.display.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement