Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Created July 29, 2017 16:16
Show Gist options
  • Save jsbueno/5c8e18cc6c338bdda07447a963f6a4e4 to your computer and use it in GitHub Desktop.
Save jsbueno/5c8e18cc6c338bdda07447a963f6a4e4 to your computer and use it in GitHub Desktop.
space invaders da oficina
import pygame
LARG = 640
ALT = 480
# alterar os numeros para mudar a cor:
cor_da_nave = (0, 255, 0)
fundo = (0, 0, 0)
TAM = LARG / 20
def inicio():
global tela, pontos
tela = pygame.display.set_mode((LARG, ALT))
pontos = 0
class JogadorMorreu(Exception):
pass
class Nave(object):
x = 0
y = 0
cor = cor_da_nave
contador = 4
def get_rect(self):
return pygame.Rect(self.x, self.y, TAM, TAM)
def atualiza(self):
self.contador = self.contador - 1
if self.contador == 0:
self.x = self.x + TAM
if self.x >= LARG:
self.x = 0
self.y = self.y + TAM
if self.y >= ALT:
raise JogadorMorreu
self.contador = 4
pygame.draw.rect(tela, self.cor, self.get_rect())
def cria_naves(quantas):
naves = []
for i in range(quantas):
n = Nave()
n.x = i * TAM * 3
naves.append(n)
return naves
class Tiro(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.cor = (255, 255, 255)
def get_rect(self):
return pygame.Rect(self.x + int(TAM/3), self.y, int(TAM/3), TAM)
def atualiza(self, naves):
global pontos
self.y -= TAM / 2
if self.y <= 0:
return False
rect = self.get_rect()
for nave in naves:
if rect.colliderect(nave.get_rect()):
naves.remove(nave)
pontos += 100
pygame.draw.rect(tela, self.cor, self.get_rect())
return True
class Canhao(object):
def __init__(self):
self.x = LARG / 2
self.y = ALT - TAM
self.cor = (0, 0, 255)
def atualiza(self, teclas, tiros):
if teclas[pygame.K_LEFT]:
self.x -= TAM / 2
if teclas[pygame.K_RIGHT]:
self.x += TAM / 2
if teclas[pygame.K_SPACE]:
tiro = Tiro(self.x, self.y - TAM)
tiros.append(tiro)
pygame.draw.rect(tela, self.cor,
(self.x, self.y, TAM, TAM))
def principal():
naves = cria_naves(6)
canhao = Canhao()
tiros = []
while True:
tela.fill(fundo)
if not naves:
naves = cria_naves(6)
for nave in naves:
nave.atualiza()
for tiro in tiros[:]:
if not tiro.atualiza(naves):
tiros.remove(tiro)
pygame.event.pump()
teclas = pygame.key.get_pressed()
canhao.atualiza(teclas, tiros)
pygame.display.flip()
pygame.time.delay(30)
try:
inicio()
principal()
except JogadorMorreu:
print("Voce morreu. Pontos %d" % pontos)
finally:
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment