Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- import random
- GRAVITY = 1
- PLAYER_VELOCITY = 5
- JUMP_POWER = 20
- HEIGHT = 901
- WIDTH = 500
- backgroundColour = (0,215,62)
- platformColour = (0,255,0)
- # self.image = substitute for actual image
- class Platform(pygame.sprite.Sprite):
- def __init__(self, y,pl = 100):
- super().__init__()
- platheight = 10
- platlength = pl
- self.image = pygame.Surface((platlength,platheight))
- self.image.fill(platformColour)
- self.rect = self.image.get_rect() # <-- makes rectangle
- self.rect.left = (random.randrange(0,WIDTH - platlength))
- self.rect.centery = y
- class player(pygame.sprite.Sprite):
- def __init__(self):
- super().__init__()
- self.image = pygame.Surface((50, 90))
- self.image.fill((130, 230, 99))
- self.rect = self.image.get_rect()
- self.rect.center = (485,550)
- self.dx = 0
- self.dy = 0
- self.in_air = True
- self.gravity = GRAVITY
- def update(self):
- self.dx = 0
- keys = pygame.key.get_pressed()
- if keys [pygame.K_a]:
- self.dx = -PLAYER_VELOCITY
- if keys [pygame.K_d]:
- self.dx = PLAYER_VELOCITY
- if keys [pygame.K_SPACE] and not self.in_air:
- self.jump()
- self.dy += self.gravity
- self.rect.move_ip(self.dx,self.dy)
- def jump(self):
- keys = pygame.key.get_pressed() #makes the key function
- if keys [pygame.K_SPACE]:
- self.dy = -JUMP_POWER
- self.in_air = True
- self.gravity = GRAVITY
- pygame.init()
- window = pygame.display.set_mode((WIDTH,HEIGHT)) #makes window
- run = True
- clock = pygame.time.Clock() # <-- makes a clock
- elements = pygame.sprite.Group() #group where all objects are stored
- platforms = pygame.sprite.Group()
- for x in range(5): #value of x will be 0 1 2 3 4 5
- p = Platform((x+1)*150)
- elements.add(p)
- platforms.add(p)
- base = Platform(HEIGHT-20, WIDTH - 1)
- elements.add(base) #adds base to element group
- platforms.add(base) #adds to platforms
- layer = player()
- elements.add(layer)
- while run:
- window.fill(backgroundColour)
- clock.tick(60) # <-- sets FPS to 60
- for event in pygame.event.get(): # <-- gives you all events
- if event.type == pygame.QUIT: # <-- if the event is that you close the program
- run = False # <--shuts down windowplatforms, F
- plat = pygame.sprite.spritecollideany(layer, platforms)
- if plat and layer.dy > 0 and layer.rect.centery <= plat.rect.top:
- layer.in_air = False
- layer.gravity = 0 # accleration
- layer.dy = 0 # velocity
- layer.rect.bottom = plat.rect.top
- else:
- layer.gravity = GRAVITY
- elements.update() # updates all objects in element group
- elements.draw(window) #places objects from elements group into window
- pygame.display.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement