Created
April 18, 2022 14:05
-
-
Save mirwox/7fe298b69c384a1815f172c747c776aa to your computer and use it in GitHub Desktop.
Exemplo de Pygame - pré aula
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pygame | |
from random import randint, choice | |
WIDTH = 640 | |
HEIGHT = 480 | |
def inicializa(): | |
pygame.init() | |
w = pygame.display.set_mode((640, 480)) | |
pygame.key.set_repeat(50) | |
assets = { | |
'player': pygame.image.load('player.png'), | |
'meteoro': pygame.image.load('meteorSmall.png'), | |
} | |
#44X42 | |
state = { | |
'nave_x':640/2 - (99/2), | |
'nave_y': 480 - 75, | |
'last_updated': 0, | |
'meteors': [ (randint(0, WIDTH-44), -100, choice(range(100, 300, 50))), | |
(randint(0, WIDTH-44), -130, choice(range(100, 300, 50))), | |
(randint(0, WIDTH-44), -160, choice(range(100, 300, 50))), | |
(randint(0, WIDTH-44), -190, choice(range(100, 300, 50))), | |
(randint(0, WIDTH-44), -210, choice(range(100, 300, 50))), | |
], | |
} | |
return w, assets, state | |
def finaliza(): | |
pygame.quit() | |
def desenha(window: pygame.Surface, assets, state): | |
window.fill((0,0,0)) | |
window.blit(assets['player'], (state['nave_x'], state['nave_y'])) | |
for meteor in state['meteors']: | |
x, y, speed = meteor | |
window.blit(assets['meteoro'], (x, y)) | |
pygame.display.update() | |
def atualiza_posicao_meteoros(state, delta_t): | |
for index in range(len(state['meteors'])): | |
x, y, speed = state['meteors'][index] | |
y = y + speed * (delta_t/1000) | |
if y > HEIGHT: | |
x = (randint(0, WIDTH-44)) | |
y = -100 | |
state['meteors'][index] = (x, y, speed) | |
def recebe_eventos(state): | |
now = pygame.time.get_ticks() | |
delta_t = now - state["last_updated"] | |
for ev in pygame.event.get(): | |
if ev.type == pygame.QUIT: | |
return False | |
elif ev.type == pygame.KEYDOWN: | |
if ev.key == pygame.K_LEFT: | |
state['nave_x']-=8 | |
elif ev.key == pygame.K_RIGHT: | |
state['nave_x']+=8 | |
state['last_updated'] = now | |
atualiza_posicao_meteoros(state, delta_t) | |
return True | |
def gameloop(window, assets, state): | |
while recebe_eventos(state): | |
desenha(window, assets, state) | |
if __name__ == '__main__': | |
window, assets, state = inicializa() | |
gameloop(window, assets, state) | |
finaliza() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment