def __init__(self, hud: HudManager): self.hud = hud self.window = hud.get_window() self.mouse = hud.get_window().get_mouse() self.fundo = GameImage(BACKGROUND_HOME) self.time = 0 self.select = False points_background = pygame.transform.scale( GameImage(SOUND_BACKGROUND).image, (1100, 800)) self.point_background = GameImage(SOUND_BACKGROUND) self.point_background.image = points_background self.point_background.set_position( self.window.width / 2 - points_background.get_width() / 2, 0) self.text = CenterText(hud.get_window(), WIDTH_DIV, 300, text="Escolha qual será sua próxima nave") self.jet_g_bool = False self.jet_green = Sprite(*JET_GREEN_FLY) self.jet_green.set_position( WIDTH_DIV - WIDTH_DIV / 2 - self.jet_green.width + 200, 350) self.jet_y_bool = False self.jet_yellow = Sprite(*JET_YELLOW_FLY) self.jet_yellow.set_position(WIDTH_DIV + WIDTH_DIV / 2 - 200, 350)
class ButtonClick(Button): def __init__(self, button_image, window, x, y): super().__init__(window, x, y, "") self.button = GameImage(button_image) self.button.set_position(x - self.button.width / 2, y - self.button.height / 2) def draw(self): self.button.draw() self.update() def is_button_pressed(self): if self.is_button_press: self.is_button_press = False BUTTON_SOUND.play() return True return False def update(self): self.debug_time -= self.window.delta_time() if self.mouse.is_over_object(self.button): if not self.mouse.is_button_pressed(self.mouse.BUTTON_LEFT): self.is_button_press = False elif self.debug_time <= 0: self.debug_time = 1 self.is_button_press = True
class SpecialHud: def __init__(self): self.bar = GameImage(SPECIAL_HUD) self.bar.set_position(4, 76) self.value = Sprite(*SPECIAL_POINTS) self.value.set_position(-6, 65) self.value.set_curr_frame(0) def draw(self): self.bar.draw() self.value.draw() def addSpecial(self): point = self.value.curr_frame + 1 self.value.set_curr_frame(self.__checkLife(point)) def loseSpecial(self): self.value.set_curr_frame(0) def current_special(self): return self.value.curr_frame def __checkLife(self, point): if point < 0: return 0 elif point > 4: return 4 else: return point
class GameOverScene(SceneInterface): def __init__(self, hud: HudManager): self.hud = hud self.window = hud.get_window() self.background = GameImage(BACKGROUND_HOME_OVER) self.text = CenterText(self.window, self.window.width / 2, 50, WHITE, text="Você perdeu!") self.voltar_button = Button(self.window, self.window.width / 2, self.window.height / 2, "VOLTAR") def handle_event(self, fps, state): if self.voltar_button.is_button_pressed(): self.window.main_scene.change_scene('Main') def draw(self, state): self.background.draw() self.text.draw() self.voltar_button.draw() def update(self, state): self.voltar_button.update()
def __init__(self, hud: HudManager): self.hud = hud self.window = hud.get_window() self.key_board = hud.get_window().get_keyboard() self.background = BackgroundModel(BACKGROUND_BATTLE1) self.air_plane = AirPlaneModel(shoot=self.hud.get_special_look(), sprite=self.hud.get_ship_look()) self.enemy_plane = EnemyAirPlaneModel(*ENEMY_PLANE_FIRST_POSITION) self.coin = CoinModel() self.life = LifeModel(WIDTH_SCREEN, HEIGHT_SCREEN / 2, True) self.special = SpecialModel(WIDTH_SCREEN / 2, HEIGHT_SCREEN / 2, True) self.point = 0 points_background = pygame.transform.scale( GameImage(SOUND_BACKGROUND).image, (250, 90)) self.point_background = GameImage(SOUND_BACKGROUND) self.point_background.image = points_background self.point_background.set_position( self.window.width / 2 - points_background.get_width() / 2, -15) self.shot_time = 0.0 self.game_objects = [ self.background, self.enemy_plane, self.air_plane, self.coin, self.life, self.special, self.air_plane.get_shot(), self.air_plane.get_shot_special(), self.enemy_plane.get_shot() ] self.enemys = [self.enemy_plane] self.enemy_shot_times = [0.0]
class HistoryScene(SceneInterface): def __init__(self, hud: HudManager, imageHistory, nextScene, continue_game=True): self.hud = hud self.window = hud.get_window() self.fundo = GameImage(imageHistory) self.nextScene = nextScene self.continue_game = continue_game if self.continue_game: self.button_continuar = Button(self.window, WINDOW_SIZE[0] - 200, WINDOW_SIZE[1] - 100, "CERTO!") def handle_event(self, speed: int, scene: bool): pass def draw(self, state: bool): self.fundo.draw() if self.continue_game: self.button_continuar.draw() def update(self, state: bool): if self.continue_game: if self.button_continuar.is_button_pressed(): self.window.main_scene.change_scene(self.nextScene)
def __init__(self): from binary_break import SpecialBlock SpecialBlock.add_special_item = self.add_special_item self.window = globals.window self.window.set_title("Space Breakout") self.background = GameImage("images/background.jpg") self.lateral_bar = GameImage("images/back2.jpg") self.sound = Sound("sound/gametheme.wav") self.sound.loop = True quantity_columns = 10 self.game_width = SpecialBlock().width * quantity_columns self.blocks = BlockMatrix(quantity_columns) x_start_point = self.window.width - self.game_width self.pad = Pad(x_start_point) self.ball = Ball() self.ball.min_x = self.blocks.x = x_start_point self.put_ball_over_pad() for i in range(5): self.blocks.add_line() self.game_started = False self.lives = 3 self.score = 0 self.score_increment_rate = 0.1 self.game_over = False self.block_rain_counter = Counter(1.5) self.rain_line_counter = Counter(0.03) self.items = [] durable_effects = ("unstoppable", ) self.effects = {effect: Counter() for effect in durable_effects}
def __init__(self, lado, x, y): image_paths = ('sprite/galhos/galhodireitanew.png', 'sprite/galhos/galhoesquerdanew.png', 'sprite/galhos/semgalho.png') self.texture = GameImage(image_paths[lado]) self.lado = lado self.texture.set_position(x, y)
def __init__(self): self.bgmenu = GameImage("Images/bgmenutd.png") self.buttonPlay = TextButton("Play", (200, 200, 200), Config.GAME_WIDTH / 2, 400, True, False) self.buttonOptions = TextButton("Options", (200, 200, 200), Config.GAME_WIDTH / 2, 440, True, False) self.buttonExit = TextButton("Exit", (200, 200, 200), Config.GAME_WIDTH / 2, 480, True, False)
def __init__(self, janela, lado): self.lado = lado self.janela = janela self.sprites = (GameImage('sprite/bambam/be1.png', 0, 512 - 150), GameImage('sprite/bambam/be3.png', 0, 512 - 150), GameImage('sprite/bambam/bd1.png', 0, 512 - 150), GameImage('sprite/bambam/bd3.png', 0, 512 - 150)) self.batendo = False self.sprite_atual = 0 self.tempo_soco = 0
def __init__(self, popup, janela, nome_image, mult_y, add_y, mult_x, add_x): self.janela = janela self.popup = popup self.objeto = GameImage(nome_image) self.largura = self.objeto.width self.altura = self.objeto.height self.x = self.janela.width / 2 - popup.largura / 2 + mult_x * self.largura + add_x self.y = self.janela.height / 2 - popup.altura / 2 + mult_y * self.altura + add_y self.objeto.set_position(self.x, self.y)
def __init__(self, bar_x=4, bar_y=0, life_hud=LIFE_HUD, life_points=LIFE_POINTS): self.bar = GameImage(life_hud) self.bar.set_position(bar_x, bar_y) self.value = Sprite(*life_points) self.value.set_position(bar_x - 10, bar_y - 10) self.value.set_curr_frame(4)
def __init__(self, window, x, y, text): self.window = window self.mouse = window.get_mouse() self.button = GameImage(NORMAL_BUTTON) self.button.set_position(x - self.button.width / 2, y - self.button.height / 2) self.is_normal = True self.is_button_press = False self.debug_time = 0 self.x = x - self.button.width / 2 self.y = y - self.button.height / 2 self.text_str = text
def __init__(self): self.window = globals.window self.window.set_title("Space Breakout Menu") self.sound = Sound("sound/menutheme.wav") self.play = Button("images/menu/play.png") self.rank = Button("images/menu/rank.png") self.quit = Button("images/menu/quit.png") self.background = GameImage("images/menu/background.png") self.put_button_on_position(self.play, 0.23) self.put_button_on_position(self.rank, 0.43) self.put_button_on_position(self.quit, 0.63)
def __init__(self, hud: HudManager): self.hud = hud self.window = hud.get_window() self.background = GameImage(BACKGROUND_HOME_OVER) self.text = CenterText(self.window, self.window.width / 2, 50, WHITE, text="Você perdeu!") self.voltar_button = Button(self.window, self.window.width / 2, self.window.height / 2, "VOLTAR")
def __init__(self, y, pos): self.pos = pos # left or right self.y = y # y coordinate if pos == "left": self.type = 0 else: self.type = 1 # Retrieves snowflake image self.texture = GameImage(self.flakeImage[self.type]) self.set_position()
def __init__(self, y, pos): self.y = y # y-coordinate (distance from top of screen) self.pos = pos if pos == "left": # branch 'left' to tree self.type = 1 elif pos == "right": # branch 'right' to tree self.type = 0 else: self.type = 2 # no branch if position is 'middle' # Assigns an image to each object self.texture = GameImage(self.tree_types[self.type]) self.texture.set_position(0, self.y)
def __init__(self, hud: HudManager, imageHistory, nextScene, continue_game=True): self.hud = hud self.window = hud.get_window() self.fundo = GameImage(imageHistory) self.nextScene = nextScene self.continue_game = continue_game if self.continue_game: self.button_continuar = Button(self.window, WINDOW_SIZE[0] - 200, WINDOW_SIZE[1] - 100, "CERTO!")
class Galho: def __init__(self, lado, x, y): image_paths = ('sprite/galhos/galhodireitanew.png', 'sprite/galhos/galhoesquerdanew.png', 'sprite/galhos/semgalho.png') self.texture = GameImage(image_paths[lado]) self.lado = lado self.texture.set_position(x, y) def set_position(self, x, y): self.texture.set_position(x, y) def get_lado(self): return self.lado def draw(self): self.texture.draw() def draw_rotated(self, angle): self.texture.draw_rotated(angle) def get_x(self): return self.texture.x def get_y(self): return self.texture.y
def update(self): self.debug_time -= self.window.delta_time() if self.mouse.is_over_object(self.button): if not self.mouse.is_button_pressed(self.mouse.BUTTON_LEFT): self.button = GameImage(HOVER_BUTTON) self.button.set_position(self.x, self.y) self.is_normal = False self.is_button_press = False elif self.debug_time <= 0: self.debug_time = 1 self.is_button_press = True self.is_normal = False elif not self.is_normal: self.button = GameImage(NORMAL_BUTTON) self.button.set_position(self.x, self.y) self.is_normal = True self.is_button_press = False
def __init__(self, window): self.window = window self.button = GameImage(PAUSE_HUD) self.button.set_position(self.window.width - self.button.width - 10, self.window.height - 130) self.points = 0 self.menu_screen = GameImage(PAUSE_SCREEN) self.menu_screen.set_position( self.window.width / 2 - self.menu_screen.width / 2, 85) self.menu_button = Button(self.window, self.window.width / 2, 320, "MENU") self.return_button = Button(self.window, self.window.width / 2, 500, "VOLTAR") self.show_menu = False
class OptionsScreen: def __init__(self, window): self.bg = GameImage("Images/bgmenutdorig.jpg") self.bg.resize(window.width, window.height) def start(self, window, gs): self.draw(window) self.update(window, gs) window.set_title("Options") window.update() def draw(self, window): self.bg.draw() self.buttonBack.draw(window) def update(self, window, gs): if self.buttonBack.clicked(): gs.enter_menu() window.update()
class Button: def __init__(self, window, x, y, text): self.window = window self.mouse = window.get_mouse() self.button = GameImage(NORMAL_BUTTON) self.button.set_position(x - self.button.width / 2, y - self.button.height / 2) self.is_normal = True self.is_button_press = False self.debug_time = 0 self.x = x - self.button.width / 2 self.y = y - self.button.height / 2 self.text_str = text def draw(self): self.button.draw() color = NEAR_BLACK if self.mouse.is_over_object(self.button): color = ORANGE text = CenterText(self.window, self.x + self.button.width / 2, self.y + self.button.height / 2, color=color, size=80, text=self.text_str) text.draw() self.update() def is_button_pressed(self): if self.is_button_press: self.is_button_press = False BUTTON_SOUND.play() return True return False def update(self): self.debug_time -= self.window.delta_time() if self.mouse.is_over_object(self.button): if not self.mouse.is_button_pressed(self.mouse.BUTTON_LEFT): self.button = GameImage(HOVER_BUTTON) self.button.set_position(self.x, self.y) self.is_normal = False self.is_button_press = False elif self.debug_time <= 0: self.debug_time = 1 self.is_button_press = True self.is_normal = False elif not self.is_normal: self.button = GameImage(NORMAL_BUTTON) self.button.set_position(self.x, self.y) self.is_normal = True self.is_button_press = False
class TimeHud: def __init__(self, window): self.window = window self.bar = GameImage(TIME_HUD) self.bar.set_position(self.window.width / 2 - self.bar.width / 2, 6) self.time = TIME def draw(self): self.bar.draw() self.time = self.time - self.window.delta_time() seconds = self.time if int(seconds) == 0: self.window.main_scene.change_scene('City') text = CenterText(self.window, self.window.width / 2, 46, text=int(seconds)) text.draw()
class Botao: def __init__(self, popup, janela, nome_image, mult_y, add_y, mult_x, add_x): self.janela = janela self.popup = popup self.objeto = GameImage(nome_image) self.largura = self.objeto.width self.altura = self.objeto.height self.x = self.janela.width / 2 - popup.largura / 2 + mult_x * self.largura + add_x self.y = self.janela.height / 2 - popup.altura / 2 + mult_y * self.altura + add_y self.objeto.set_position(self.x, self.y) def draw(self): self.objeto.draw() def is_clicked(self, mouse): mouse_p = mouse.get_position() if (self.x <= mouse_p[0] <= self.x + self.largura and self.y + self.altura >= mouse_p[1] >= self.y and mouse.is_button_pressed(1)): return True
class Snowman: # Images for snowman sprites = (GameImage('sprite/snowman/snowmanLeft.png', snowmanDist, snowmanY), GameImage('sprite/snowman/snowmanRight.png', -snowmanDist, snowmanY), GameImage('sprite/snowman/meltyLeft.png', snowmanDist, snowmanY), GameImage('sprite/snowman/meltyRight.png', -snowmanDist, snowmanY)) def __init__(self, pos): self.pos = pos # Snowman position is left or right of tree # Draws snowman on correct side of tree def paint(self): if self.pos == "left": self.sprites[0].draw() else: self.sprites[1].draw()
class Menu: def __init__(self): self.window = globals.window self.window.set_title("Space Breakout Menu") self.sound = Sound("sound/menutheme.wav") self.play = Button("images/menu/play.png") self.rank = Button("images/menu/rank.png") self.quit = Button("images/menu/quit.png") self.background = GameImage("images/menu/background.png") self.put_button_on_position(self.play, 0.23) self.put_button_on_position(self.rank, 0.43) self.put_button_on_position(self.quit, 0.63) def render(self): self.update_logic() self.sound.play() self.background.draw() self.play.render() self.rank.render() self.quit.render() def update_logic(self): if self.play.clicked(): from binary_break.screens.game import Game self.sound.set_volume(0) self.sound.stop() globals.currentContainer = Game() elif self.rank.clicked(): from binary_break.screens.rank import Rank globals.currentContainer = Rank() elif self.quit.clicked(): self.window.close() def put_button_on_position(self, button, height_percentage): half_width = self.window.width / 2 button.set_position(half_width - button.width / 2, self.window.height * height_percentage)
class MenuGame: def __init__(self): self.bgmenu = GameImage("Images/bgmenutd.png") self.buttonPlay = TextButton("Play", (200, 200, 200), Config.GAME_WIDTH / 2, 400, True, False) self.buttonOptions = TextButton("Options", (200, 200, 200), Config.GAME_WIDTH / 2, 440, True, False) self.buttonExit = TextButton("Exit", (200, 200, 200), Config.GAME_WIDTH / 2, 480, True, False) def start(self, window, gs): self.draw(window) self.update(window, gs) window.set_title("Menu") def draw(self, window): self.bgmenu.draw() for button in self.buttons: button.draw(window) window.update() def update(self, run, menu, options): if (self.getButtonClicked(2)): run = False menu = False elif (self.getButtonClicked(1)): menu = False options = True def update(self, window, gs): if self.buttonExit.clicked(): gs.exit_game() window.update() if self.buttonOptions.clicked(): gs.enter_options() window.update()
class PointHud: def __init__(self, window): self.window = window self.bar = GameImage(POINTS_HUD) self.bar.set_position(self.window.width - self.bar.width, 0) self.points = 0 def draw(self): self.bar.draw() text = CenterText(self.window, self.window.width - self.bar.width / 2 - 8, 40, text=self.points) text.draw() def addPoint(self, amount): self.points += amount def get_point(self): return self.points def remove_point(self, amount: int): self.points -= amount
def set_popup(self, tipo, soldado): self.tipo = tipo if (self.tipo == 1): self.texto = None self.objeto = GameImage(Popup_Images.inventario['fundo']) self.largura = self.objeto.width self.altura = self.objeto.height self.objeto.set_position( (self.janela.width / 2 - self.largura / 2), self.janela.height / 2 - self.altura / 2) self.bt_repor = Botao(self, self.janela, Popup_Images.inventario['bt_repor'], 2, 0, 0, 10) self.bt_dormir = Botao(self, self.janela, Popup_Images.inventario['bt_dormir'], 3, 1, 0, 10) self.bt_comer = Botao(self, self.janela, Popup_Images.inventario['bt_comer'], 4, 2, 0, 10) self.bt_ok = None self.bt_cancelar = None if (self.tipo == 2): self.texto = str(soldado.prontuario) self.objeto = GameImage(Popup_Images.prontuario['fundo']) self.largura = self.objeto.width self.altura = self.objeto.height self.objeto.set_position( (self.janela.width / 2 - self.largura / 2), self.janela.height / 2 - self.altura / 2) self.bt_ok = Botao(self, self.janela, Popup_Images.prontuario['bt_ok'], 13, 0, 0.5, 0) self.bt_cancelar = Botao(self, self.janela, Popup_Images.prontuario['bt_cancelar'], 14, 1, 0.5, 0) self.bt_repor = None self.bt_dormir = None self.bt_comer = None if (self.tipo == 0): self.texto = "" self.objeto = GameImage(Popup_Images.start['fundo']) self.largura = self.objeto.width self.altura = self.objeto.height self.objeto.set_position( (self.janela.width / 2 - self.largura / 2), self.janela.height / 2 - self.altura / 2) self.bt_ok = Botao(self, self.janela, Popup_Images.prontuario['bt_ok'], 10, 0, 0.7, 0) self.bt_cancelar = Botao(self, self.janela, Popup_Images.prontuario['bt_cancelar'], 13, 0, 0.7, 0) self.bt_repor = None self.bt_dormir = None self.bt_comer = None
def __init__(self, console): # Inicializa o Console self.console = console # Inicialização dos elementos da janela self.fundo = GameImage("Imagens/Cenarios/FLOOR1/FUNDO.jpg") # Inicializa os objetos nao interativos self.criaParedes() self.criaForniture() # Inicaliza todos os objetos interativos self.criaObjetosInterativos() # Apos inicializado dos os objetos, aquels q forem solidos serao colocados aqui self.objetosSolidos = [] # Inicialização dos personagens... a criaçao de personagem requer q seja dito quais sets d botoes sao usados self.wolf = Boneco("WOLF", 1) # qsui esta sendo usado o set d botoes 1 para o personagem WOLF self.gang = Boneco("GANG", 2) # Ja inicializa as proximas fases acessiveis atraves dessa fase self.floor2 = Floor2(console, self.wolf, self.gang) self.fporao = Porao(console, self.wolf, self.gang) # neste ponto a tela da fase atual ja foi interiamente montada # A primeira fez q a fase FLOOR1 è iniciada uma sequencia da dialogos é iniciada self.atualizaJanela() Mensagem("AHH!!", self.gang, self.console) Mensagem("A porta se fechou atras de nos!", self.gang, self.console) Mensagem("E agora?! O que fazemos?!", self.gang, self.console) Mensagem("Eu nao sei... E a culpa disso é toda sua.", self.wolf, self.console) Mensagem("Eu avisei que nao era uma boa ideia entrar nessa casa.", self.wolf, self.console) Mensagem("De qualquer forma...", self.wolf, self.console) Mensagem("Deve haver um jeito de sair daqui.", self.wolf, self.console) Mensagem("Vamos procurar.", self.wolf, self.console) Mensagem("Sim... Vamos!", self.gang, self.console) # comando q de fato inicializa o jogo com a jogabilidade self.play()
class Floor1: # O console é aquela classe q faz o controle das janelas e dos outputs e inputs do jogo console = None # Estados -- Esses estados servem para o controle d fluxo dos loops rodando = False pausado = False # Essa variavel so serve para ativar ou desativar o modo Developer do jogo. O mode Dev somente mostra algumas informaçoes a mais na tela para auxilio dev = False # Criacao elementos da janela -- Aqui sao todos os elementos e objetos q serao impressos na tela fundo = None # Essa é a imagem d fundo da fase # Esse objetos nao sao interativos paredes = None # aqui sao todas as paredes q compoem a fase. Serve para realizar as colisoes dos personagens com os paredes de forma mais eficiente forniture = None # aqui sao todos os moveis da fase # Esses objetos sao interativos portas = None # aqui sao todas as portas da fase alavancas = None # aqui sao todas as alavancasa da fase notas = None # aqui sao todas as notas... itens q podem ser visuzlizados por cima da tela... esse objeto nao é solido... o personagem pode passar por cima deles objetosSolidos = None # aqui é a soma de todas as outras listas d objetos q sao solidos... ou seja... aqueles q o bonoco n pode passar atraves # Esses objetos Sprite q serao usados para colisoes e decidir as mudanças de fase.. Ex: escada é u Sprite q leva a para o segundo andar escada = None porao = None # Essas sao as instancias das fases acessiveis atraves da fase atual floor2 = None fporao = None # Criação dos 2 personagens wolf = None gang = None # __________________________________________________________________________________________________________________ # Aqui temos inicializaçao de todas as variaveis q foram declaradas a cima def __init__(self, console): # Inicializa o Console self.console = console # Inicialização dos elementos da janela self.fundo = GameImage("Imagens/Cenarios/FLOOR1/FUNDO.jpg") # Inicializa os objetos nao interativos self.criaParedes() self.criaForniture() # Inicaliza todos os objetos interativos self.criaObjetosInterativos() # Apos inicializado dos os objetos, aquels q forem solidos serao colocados aqui self.objetosSolidos = [] # Inicialização dos personagens... a criaçao de personagem requer q seja dito quais sets d botoes sao usados self.wolf = Boneco("WOLF", 1) # qsui esta sendo usado o set d botoes 1 para o personagem WOLF self.gang = Boneco("GANG", 2) # Ja inicializa as proximas fases acessiveis atraves dessa fase self.floor2 = Floor2(console, self.wolf, self.gang) self.fporao = Porao(console, self.wolf, self.gang) # neste ponto a tela da fase atual ja foi interiamente montada # A primeira fez q a fase FLOOR1 è iniciada uma sequencia da dialogos é iniciada self.atualizaJanela() Mensagem("AHH!!", self.gang, self.console) Mensagem("A porta se fechou atras de nos!", self.gang, self.console) Mensagem("E agora?! O que fazemos?!", self.gang, self.console) Mensagem("Eu nao sei... E a culpa disso é toda sua.", self.wolf, self.console) Mensagem("Eu avisei que nao era uma boa ideia entrar nessa casa.", self.wolf, self.console) Mensagem("De qualquer forma...", self.wolf, self.console) Mensagem("Deve haver um jeito de sair daqui.", self.wolf, self.console) Mensagem("Vamos procurar.", self.wolf, self.console) Mensagem("Sim... Vamos!", self.gang, self.console) # comando q de fato inicializa o jogo com a jogabilidade self.play() # _____________________________________________________________________________________________________________ def play(self): self.rodando = True # seta a varivel q gerecnia o loop principal dessa fase para True Sons.fundo.play() # faz a chamada para a classe d Sons e inicia a musica d fundo dessa fase while self.rodando: Constantes.delta = self.console.delta() # Joga o delta do jogo para um Classe global q sera acessada por todas as fase q precisarao fazer uso do msm delta q essa tela gerou # Nos proximos 2 IFs sao verificadas colisoes com os Sprites para decidir a mudanca das fases # Decide se ira para os egundo andar if self.wolf.colidiu(self.escada) and self.gang.colidiu(self.escada): self.floor2.play() if self.floor2.esc: self.rodando = False else: self.rodando = True # Decide se ira oara o porao if self.wolf.colidiu(self.porao) and self.gang.colidiu(self.porao): self.fporao.play() if self.fporao.esc: self.rodando = False else: self.rodando = True self.checaComandos() # A partir dessa chamada serao efetuados das as checagens de jogabilidade da fase self.atualizaJanela() # A partir dessa chamda serao feitas as exibiçoes do elemtnos na tela # ________________________________________________________________________________________________________________ # Esse metodo foi chamado antes no __init__... aqui q serao Inicializadas as paredes da fase def criaParedes(self): letras = list(string.ascii_uppercase[:23]) self.paredes = [] for x in letras: self.paredes += [Parede("Imagens\Objetos\Paredes\FLOOR1/" + x + ".png")] posicoes = [[50, 50], [50, 50], [50, 200], [50, 300], [50, 500], [125, 200], [150, 200], [225, 200], [250, 200], [250, 500], [250, 550], [325, 200], [390, 200], [400, 200], [400, 275], [400, 300], [400, 500], [400, 500], [350, 550], [500, 200], [750, 50], [650, 300], [650, 300]] for i in range(len(self.paredes)): self.paredes[i].setXY(posicoes[i][0], posicoes[i][1]) # ________________________________________________________________________________________________________________ # Esse metodo foi chamado antes no __init__... aqui q serao Inicializadas os moveis da fase def criaForniture(self): letras = list(string.ascii_uppercase[:20]) self.forniture = [] for x in letras: self.forniture += [Parede("Imagens\Objetos\Forniture\FLOOR1/" + x + ".png")] posicoes = [[60, 60], [100, 60], [160, 280], [60, 310], [100, 350], [60, 385], [110, 400], [100, 470], [200, 315], [410, 315], [530, 410], [610, 415], [620, 480], [460, 275], [465, 215], [589, 120], [550, 140], [670, 135], [605, 90], [605, 254]] for i in range(len(self.forniture)): self.forniture[i].setXY(posicoes[i][0], posicoes[i][1]) # ________________________________________________________________________________________________________________ # Esse metodo foi chamado antes no __init__... aqui q serao Inicializadas todos os obejetos interativos da fase def criaObjetosInterativos(self): # Aqui sao criadas as portas self.portas = [] # de fato inicializa a variavel das portas portaEntrada = Porta("H", 300, 550, True, "impossivel") # para iniciar uma porta é preciso dizer se sera uma porta Vertical("V") ou Horizontal("H") portaSalaDeVisita = Porta("V", 250, 450, False, None) # tambem é preciso determinar a posiçao da porta portaSalaDeEstar = Porta("V", 400, 450, False, None) # também é preciso dizer se a porta estara travada ou nao portaBanheiro = Porta("V", 400, 225, False, None) # e por ultimo, se a porta for travada, inserio o codigo q ira destravar ela portaLavanderia = Porta("H", 75, 200, True, "chaveDourada") # esse codigo pode vim na forma de uma chave ou de um evento externo qualquer portaArmazem = Porta("H", 175, 200, True, "alavancaLavanderia") # como por exemplo uma alavanca q abre a porta portaCozinha = Porta("H", 340, 200, False, None) portaSalaDeJantar = Porta("H", 600, 300, False, None) self.portas += [portaSalaDeVisita, portaSalaDeEstar, portaBanheiro, portaLavanderia, portaArmazem, portaCozinha, portaSalaDeJantar, portaEntrada] # Aqui sao criadas as alavancas da fase self.alavancas = [] alavanca = Alavanca("L", 150 - 20, 250) self.alavancas += [alavanca] # Aqui sao criados os sprites usados para colisoes para entrar em outras fases self.escada = Sprite("Imagens\Objetos\Interativos\ESCADA.png") self.escada.x = 260 self.escada.y = 210 self.porao = Sprite("Imagens\Objetos\Interativos\PORAO.png") self.porao.x = 200 self.porao.y = 250 # _____________________________________________________________________________________________________________ # Esse metodo checa todos os comando possiveis no jogo... def checaComandos(self): self.console.resetaUlt() # Esse comando esta relacionado a utilizaçao do metodo console.apertou. # Esse metodo reconhece somente uma pressioanda d botao e para isso precisa deste restaUlt # Seta o desseta o modo Developer if self.console.apertou("L"): if self.dev: self.dev = False else: self.dev = True # Pausa o jogo if self.console.apertou("ESC"): self.pausa() # Faz a chamada do metodo q verifica se cada um dos personagens interagiu com algum dos objetos interativos da fase self.checaInteratividade(self.wolf) self.checaInteratividade(self.gang) # È e agora de fato q os objetos solidos sao colocados dentro da lista de objetos solidos... # Isso é ideal de se fazer so agora porque é logo antes de verificar colisoes dos personagens com os objetos solidos self.objetosSolidos.clear() self.objetosSolidos += self.paredes + self.portas + self.alavancas + self.forniture # Faz a chamda do metodo q se responsabiliza por movimentar os personagem verificando as colisoes com objetos solidos self.checaMovimento(self.wolf) self.checaMovimento(self.gang) # ________________________________________________________________________________________________________________ # Metodo q verifica se cada um dos personagens interagiu com algum dos objetos interativos da fase def checaInteratividade(self, personagem): if self.console.apertou(personagem.interact): # verifica se o personage de fato a pertou o seu respectivo botao d interaçao # Verifica intetação com Alavancas alavanca = self.alavancas[0] if personagem.colidiu(alavanca.sprite): Sons.alavancaAtiva.play() alavanca.ativa() if self.portas[4].travada: self.portas[4].destrava("alavancaLavanderia") Mensagem("Parece que algo foi destravado", personagem, self.console) # Verifica interaçao com as portas for porta in self.portas: if personagem.colidiu(porta.sprite): if not porta.travada: Sons.portaAbrir.play() porta.abre() else: if not len(personagem.inventario) == 0: for objeto in personagem.inventario: if isinstance(objeto, Chave): if porta.destrava(objeto.codigo): personagem.inventario.remove(objeto) Sons.portaDestrava.play() Mensagem("Oh... A porta abriu.", personagem, self.console) if porta.travada: Sons.portaTravada.play() Mensagem("A porta esta trancada.", personagem, self.console) else: Sons.portaTravada.play() Mensagem("A porta esta trancada.", personagem, self.console) # ____________________________________________________________________________________________________________ # Metodo q se responsabiliza por movimentar os personagem verificando as colisoes com objetos solidos def checaMovimento(self, personagem): if self.console.pressionou(personagem.up): # Verifica se boneco pode ir para cima e se possivel ele vai b = False for objeto in self.objetosSolidos: if personagem.colideNorte(objeto.sprite): b = True break if not b: personagem.andaNorte() if self.console.pressionou(personagem.down): # Verifica se boneco pode ir para baixo e se possivel ele vai b = False for objeto in self.objetosSolidos: if personagem.colideSul(objeto.sprite): b = True break if not b: personagem.andaSul() if self.console.pressionou(personagem.left): # Verifica se boneco pode ir para esquerda e se possivel ele vai b = False for objeto in self.objetosSolidos: if personagem.colideOeste(objeto.sprite): b = True break if not b: personagem.andaOeste() if self.console.pressionou(personagem.right): # Verifica se boneco pode ir para direita e se possivel ele vai b = False for objeto in self.objetosSolidos: if personagem.colideLeste(objeto.sprite): b = True break if not b: personagem.andaLeste() # _____________________________________________________________________________________________________________ # Metodo q exibe os elementos na tela def atualizaJanela(self): self.fundo.draw() for porta in self.portas: porta.desenha() for alavanca in self.alavancas: alavanca.desenha() if self.dev: self.desenhaAuxilio() self.wolf.desenha() self.wolf.desenhaInventario(Constantes.larguraJanela * 0.1) self.gang.desenha() self.gang.desenhaInventario(Constantes.larguraJanela * 0.8) self.console.atualizaJanela() # _____________________________________________________________________________________________________________ # Metodo q so exibe os elemntos do modoDeveloper def desenhaAuxilio(self): for x in self.paredes: x.sprite.draw() self.escada.draw() self.porao.draw() self.wolf.desenhaAuxilio() self.gang.desenhaAuxilio() # ______________________________________________________________________________________________________________ # Metodo responsavel pare efetuar a pausa def pausa(self): fundo = Sprite("Imagens\Cenarios\Mensagem\FUNDOMENSAGEM.jpg") fundo.x = 10 fundo.y = 200 while self.checaComandosPausado(): fundo.draw() self.console.janela.draw_text("Aperte O para sair", fundo.x + 20, fundo.y + 50, 36, Cores.branco, "Arial", False, False) self.console.atualizaJanela() self.console.atualizaJanela() def checaComandosPausado(self): self.console.resetaUlt() if self.console.apertou("SPACE"): return False if self.console.apertou("O"): self.rodando = False return False return True
def __init_components__(self): #sessão de janela self._window = Window(640, 480) self._window.title = "Crystal Path -" self._fundo_sound = Sound("../Sounds/menuprincipal.ogg") self._fundo_sound.sound.set_volume(10/100) #janela Menu Principal self._window_background_menu_initial = GameImage("../MENU/Background.png") self._logo = GameImage("../MENU/LOGO.png") self._new_game_button = GameImage("../MENU/BOTAO - Iniciar.png") self._continue_game_button = GameImage("../MENU/BOTAO - Continuar.png") self._exit_game_button = GameImage("../MENU/BOTAO - Sair.png") #janela Seleção de personagens self._window_background_menu_char = GameImage("../CharMenu/Background.png") self._guerreiro_menu = GameImage("../CharMenu/Guerreiromenu.png") self._feiticeira_menu = GameImage("../CharMenu/Feiticeiramenu.png") self._arqueiro_menu = GameImage("../CharMenu/Arqueiromenu.png") #seleção de fase self._fase_1 = GameImage("../FaseMenu/fase1.png") self._fase_2 = GameImage("../FaseMenu/fase2.png") self._fase_3 = GameImage("../FaseMenu/fase3.png") self._mapa = GameImage("../FaseMenu/mapa.png") self._mapa_som = Sound("../Sounds/teriasong.ogg") self._mapa_som.sound.set_volume(15/100) #seleção do jogo #jogo #personagens self._guerreiro = GameImage("../CharMenu/Guerreiromenu.png") self._feiticeira = GameImage("../CharMenu/Feiticeiramenu.png") self._arqueiro = GameImage("../CharMenu/Arqueiromenu.png") #Controle self._execute = True self._window_to_display_ = 1 self._mouse = Window.get_mouse() self._keyboard = Window.get_keyboard() #Não tem player selecionado. Será : # 1. Guerreiro # 2. Feiticeiro # 3. Arqueiro self._current_player_type_ = False self._current_game_option_ = False
class GameLoop: def __init__(self): self.__init_components__() self.FPS = 25 self.WINDOWWIDTH = 640 self.WINDOWHEIGHT = 480 self.BOXSIZE = 15 self.BOARDWIDTH = 10 self.BOARDHEIGHT = 20 self.BLANK = '.' self.MOVESIDEWAYSFREQ = 0.15 self.MOVEDOWNFREQ = 0.1 self.XMARGIN = int((self.WINDOWWIDTH - self.BOARDWIDTH * self.BOXSIZE) / 2) self.TOPMARGIN = self.WINDOWHEIGHT - (self.BOARDHEIGHT * self.BOXSIZE) - 5 # R G B self.WHITE = (255, 255, 255) self.GRAY = (185, 185, 185) self.BLACK = ( 0, 0, 0) self.RED = (155, 0, 0) self.LIGHTRED = (175, 20, 20) self.GREEN = ( 0, 155, 0) self.LIGHTGREEN = ( 20, 175, 20) self.BLUE = ( 0, 0, 155) self.LIGHTBLUE = ( 20, 20, 175) self.YELLOW = (155, 155, 0) self.LIGHTYELLOW = (175, 175, 20) self.BORDERCOLOR = self.BLUE self.BGCOLOR = self.BLACK self.TEXTCOLOR = self.WHITE self.TEXTSHADOWCOLOR = self.GRAY self.COLORS = ( self.BLUE, self.GREEN, self.RED, self.YELLOW) self.LIGHTCOLORS = (self.LIGHTBLUE, self.LIGHTGREEN, self.LIGHTRED, self.LIGHTYELLOW) assert len(self.COLORS) == len(self.LIGHTCOLORS) # each color must have light color self.TEMPLATEWIDTH = 5 self.TEMPLATEHEIGHT = 5 self.A_SHAPE_TEMPLATE = [['.....', '.....', '..OO.', '.....', '.....'], ['.....', '..O..', '..O..', '.....', '.....']] self.B_SHAPE_TEMPLATE = [['.....', '.....', '..O..', '..O..', '.....'], ['.....', '.....', '.OO..', '.....', '.....']] self.PIECES = {'A': self.A_SHAPE_TEMPLATE, 'B': self.B_SHAPE_TEMPLATE,} #Initial Fucntions def __init_components__(self): #sessão de janela self._window = Window(640, 480) self._window.title = "Crystal Path -" self._fundo_sound = Sound("../Sounds/menuprincipal.ogg") self._fundo_sound.sound.set_volume(10/100) #janela Menu Principal self._window_background_menu_initial = GameImage("../MENU/Background.png") self._logo = GameImage("../MENU/LOGO.png") self._new_game_button = GameImage("../MENU/BOTAO - Iniciar.png") self._continue_game_button = GameImage("../MENU/BOTAO - Continuar.png") self._exit_game_button = GameImage("../MENU/BOTAO - Sair.png") #janela Seleção de personagens self._window_background_menu_char = GameImage("../CharMenu/Background.png") self._guerreiro_menu = GameImage("../CharMenu/Guerreiromenu.png") self._feiticeira_menu = GameImage("../CharMenu/Feiticeiramenu.png") self._arqueiro_menu = GameImage("../CharMenu/Arqueiromenu.png") #seleção de fase self._fase_1 = GameImage("../FaseMenu/fase1.png") self._fase_2 = GameImage("../FaseMenu/fase2.png") self._fase_3 = GameImage("../FaseMenu/fase3.png") self._mapa = GameImage("../FaseMenu/mapa.png") self._mapa_som = Sound("../Sounds/teriasong.ogg") self._mapa_som.sound.set_volume(15/100) #seleção do jogo #jogo #personagens self._guerreiro = GameImage("../CharMenu/Guerreiromenu.png") self._feiticeira = GameImage("../CharMenu/Feiticeiramenu.png") self._arqueiro = GameImage("../CharMenu/Arqueiromenu.png") #Controle self._execute = True self._window_to_display_ = 1 self._mouse = Window.get_mouse() self._keyboard = Window.get_keyboard() #Não tem player selecionado. Será : # 1. Guerreiro # 2. Feiticeiro # 3. Arqueiro self._current_player_type_ = False self._current_game_option_ = False #Funções game loop def Run(self): while self._execute: self.__draw_window_components_() #Private Functions def __draw_window_components_(self): #Menu Principal if self._window_to_display_ == 1: self.__main_menu_listener() self.__main_menu_position() self.__draw_main_menu__() #Seleção de personagens elif self._window_to_display_ == 2: self.__char_menu_listener() self.__char_menu_position() self.__draw_char_menu__() #Seleção da fase elif self._window_to_display_ == 3: self.__game_option_listener_() self.__game_option_position__() self.__draw_game_option__() #Janela do jogo elif self._window_to_display_ == 4: self.__draw_game_view__() self._window.update() def __main_menu_listener(self): #PEGANDO POSIÇÂO DO MOUSE mx,my = self._mouse.get_position() if mx >= self._new_game_button.x and mx <= (self._new_game_button.x + self._new_game_button.width): if my >= self._new_game_button.y and my <= (self._new_game_button.y + self._new_game_button.height): if (self._mouse.is_button_pressed(1)): self._window_to_display_ = 2 #LOAD GAME if mx >= self._continue_game_button.x and mx <= (self._continue_game_button.x + self._continue_game_button.width): if my >= self._continue_game_button.y and my <= (self._continue_game_button.y + self._continue_game_button.height): if (self._mouse.is_button_pressed(1)): self._window_to_display_ = 6 if mx >= self._exit_game_button.x and mx <= (self._exit_game_button.x + self._exit_game_button.width): if my >= self._exit_game_button.y and my <= (self._exit_game_button.y + self._exit_game_button.height): if (self._mouse.is_button_pressed(1)): self._window.close() #Private Functions Menu Principal def __main_menu_position(self): self._new_game_button.x = self._window.width/2 - self._new_game_button.width/2 self._new_game_button.y = (2*self._window.height)/3 self._continue_game_button.x = self._window.width/2 - self._continue_game_button.width/2 self._continue_game_button.y = (2*self._window.height)/3 + self._new_game_button.height + 20 self._exit_game_button.x = self._window.width/2 - self._exit_game_button.width/2 self._exit_game_button.y = (2*self._window.height)/3 + self._new_game_button.height + 20 + self._continue_game_button.height + 20 self._logo.x = self._window.width/2 - self._logo.width/2 self._logo.y = self._logo.height + 20 def __draw_main_menu__(self): self._fundo_sound.play() self._window_background_menu_initial.draw() self._logo.draw() self._new_game_button.draw() self._continue_game_button.draw() self._exit_game_button.draw() #Private Functions Menu Personagens def __char_menu_listener(self): mx,my = self._mouse.get_position() if mx >= self._guerreiro_menu.x and mx <= self._guerreiro_menu.x + self._guerreiro_menu.width: if my >= self._guerreiro_menu.y and my <= self._guerreiro_menu.y + self._guerreiro_menu.height: if ( self._mouse.is_button_pressed(1)): self._current_player_type_ = self._guerreiro elif mx >= self._feiticeira_menu.x and mx <= self._feiticeira_menu.x + self._feiticeira_menu.width: if my >= self._feiticeira_menu.y and my <= self._feiticeira_menu.y + self._feiticeira_menu.height: if ( self._mouse.is_button_pressed(1)): self._current_player_type_ = self._feiticeira elif mx >= self._arqueiro_menu.x and mx <= self._arqueiro_menu.x + self._arqueiro_menu.width: if my >= self._arqueiro_menu.y and my <= self._arqueiro_menu.y + self._arqueiro_menu.height: if ( self._mouse.is_button_pressed(1)): self._current_player_type_ = self._arqueiro if self._current_player_type_: self._window_to_display_ = 3 def __char_menu_position(self): self._guerreiro_menu.x = self._window.width/8 self._guerreiro_menu.y = 0.18 * self._window.height self._feiticeira_menu.x = (self._window.width / 8) + self._guerreiro_menu.width self._feiticeira_menu.y = 0.18 * self._window.height self._arqueiro_menu.x = (self._window.width/8) + self._guerreiro_menu.width + self._feiticeira_menu.width self._arqueiro_menu.y = 0.18 * self._window.height def __draw_char_menu__(self): self._window_background_menu_char.draw() self._guerreiro_menu.draw() self._feiticeira_menu.draw() self._arqueiro_menu.draw() #Privae Functions Menu Escolha da Fase def __game_option_listener_(self): #PEGANDO POSIÇÂO DO MOUSE mx,my = self._mouse.get_position() if mx >= self._fase_1.x and mx <= (self._fase_1.x + self._fase_1.width): if my >= self._fase_1.y and my <= (self._fase_1.y + self._fase_1.height): if (self._mouse.is_button_pressed(1)): self._current_game_option_ = 1 if mx >= self._fase_2.x and mx <= (self._fase_2.x + self._fase_2.width): if my >= self._fase_2.y and my <= (self._fase_2.y + self._fase_2.height): if (self._mouse.is_button_pressed(1)): self._current_game_option_ = 2 if mx >= self._fase_3.x and mx <= (self._fase_3.x + self._fase_3.width): if my >= self._fase_3.y and my <= (self._fase_3.y + self._fase_3.height): if (self._mouse.is_button_pressed(1)): self._current_game_option_ = 3 if self._current_game_option_: self._window_to_display_ = 4 def __game_option_position__(self): self._fase_1.x = self._window.width/3 self._fase_1.y = self._window.height*2 / 3 self._fase_2.x = self._window.width / 2 self._fase_2.y = self._window.height / 2 self._fase_3.x = self._window.width - self._fase_2.width - 50 self._fase_3.y = self._window.height*2 / 3 def __draw_game_option__(self): self._fundo_sound.sound.stop() self._mapa_som.play() self._mapa.draw() self._fase_1.draw() self._fase_2.draw() self._fase_3.draw() #Private Functions Janela do Tetris def __draw_game_view__(self): self._mapa_som.sound.stop() pygame.init() self.FPSCLOCK = pygame.time.Clock() self.DISPLAYSURF = pygame.display.set_mode((self.WINDOWWIDTH, self.WINDOWHEIGHT)) self.BASICFONT = pygame.font.Font('freesansbold.ttf', 18) self.BIGFONT = pygame.font.Font('freesansbold.ttf', 50) pygame.display.set_caption('Teste Laboratório') self.showTextScreen('Testando Tetris') while True: # game loop self.runGame() self.showTextScreen('Game Over') def runGame(self): # setup variables for the start of the game board = self.getBlankBoard() lastMoveDownTime = time.time() lastMoveSidewaysTime = time.time() lastFallTime = time.time() movingDown = False # note: there is no movingUp variable movingLeft = False movingRight = False score = 0 level, fallFreq = self.calculateLevelAndFallFreq(score) fallingPiece = self.getNewPiece() nextPiece = self.getNewPiece() while True: # game loop if fallingPiece == None: # No falling piece in play, so start a new piece at the top fallingPiece = nextPiece nextPiece = self.getNewPiece() lastFallTime = time.time() # reset lastFallTime if not self.isValidPosition(board, fallingPiece): return # can't fit a new piece on the board, so game over self.checkForQuit() for event in pygame.event.get(): # event handling loop if event.type == KEYUP: if (event.key == K_p): # Pausing the game self.DISPLAYSURF.fill(self.BGCOLOR) pygame.mixer.music.stop() self.showTextScreen('Paused') # pause until a key press pygame.mixer.music.play(-1, 0.0) lastFallTime = time.time() lastMoveDownTime = time.time() lastMoveSidewaysTime = time.time() elif (event.key == K_LEFT or event.key == K_a): movingLeft = False elif (event.key == K_RIGHT or event.key == K_d): movingRight = False elif (event.key == K_DOWN or event.key == K_s): movingDown = False elif event.type == KEYDOWN: # moving the piece sideways if (event.key == K_LEFT or event.key == K_a) and self.isValidPosition(board, fallingPiece, adjX=-1): fallingPiece['x'] -= 1 movingLeft = True movingRight = False lastMoveSidewaysTime = time.time() elif (event.key == K_RIGHT or event.key == K_d) and self.isValidPosition(board, fallingPiece, adjX=1): fallingPiece['x'] += 1 movingRight = True movingLeft = False lastMoveSidewaysTime = time.time() # rotating the piece (if there is room to rotate) elif (event.key == K_UP or event.key == K_w): fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(self.PIECES[fallingPiece['shape']]) if not self.isValidPosition(board, fallingPiece): fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(self.PIECES[fallingPiece['shape']]) elif (event.key == K_q): # rotate the other direction fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(self.PIECES[fallingPiece['shape']]) if not self.isValidPosition(board, fallingPiece): fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(self.PIECES[fallingPiece['shape']]) # making the piece fall faster with the down key elif (event.key == K_DOWN or event.key == K_s): movingDown = True if self.isValidPosition(board, fallingPiece, adjY=1): fallingPiece['y'] += 1 lastMoveDownTime = time.time() # move the current piece all the way down elif event.key == K_SPACE: movingDown = False movingLeft = False movingRight = False for i in range(1, self.BOARDHEIGHT): if not self.isValidPosition(board, fallingPiece, adjY=i): break fallingPiece['y'] += i - 1 # handle moving the piece because of user input if (movingLeft or movingRight) and time.time() - lastMoveSidewaysTime > self.MOVESIDEWAYSFREQ: if movingLeft and self.isValidPosition(board, fallingPiece, adjX=-1): fallingPiece['x'] -= 1 elif movingRight and self.isValidPosition(board, fallingPiece, adjX=1): fallingPiece['x'] += 1 lastMoveSidewaysTime = time.time() if movingDown and time.time() - lastMoveDownTime > self.MOVEDOWNFREQ and self.isValidPosition(board, fallingPiece, adjY=1): fallingPiece['y'] += 1 lastMoveDownTime = time.time() # let the piece fall if it is time to fall if time.time() - lastFallTime > fallFreq: # see if the piece has landed if not self.isValidPosition(board, fallingPiece, adjY=1): # falling piece has landed, set it on the board self.addToBoard(board, fallingPiece) score += self.removeCompleteLines(board) level, fallFreq = self.calculateLevelAndFallFreq(score) fallingPiece = None else: # piece did not land, just move the piece down fallingPiece['y'] += 1 lastFallTime = time.time() # drawing everything on the screen self.DISPLAYSURF.fill(self.BGCOLOR) self.drawBoard(board) self.drawStatus(score, level) self.drawNextPiece(nextPiece) if fallingPiece != None: self.drawPiece(fallingPiece) pygame.display.update() self.FPSCLOCK.tick(self.FPS) def makeTextObjs(self,text, font, color): surf = font.render(text, True, color) return surf, surf.get_rect() def terminate(self): pygame.quit() sys.exit() def checkForKeyPress(self): # Go through event queue looking for a KEYUP event. # Grab KEYDOWN events to remove them from the event queue. self.checkForQuit() for event in pygame.event.get([KEYDOWN, KEYUP]): if event.type == KEYDOWN: continue return event.key return None def showTextScreen(self,text): # This function displays large text in the # center of the screen until a key is pressed. # Draw the text drop shadow titleSurf, titleRect = self.makeTextObjs(text, self.BIGFONT, self.TEXTSHADOWCOLOR) titleRect.center = (int(self.WINDOWWIDTH / 2), int(self.WINDOWHEIGHT / 2)) self.DISPLAYSURF.blit(titleSurf, titleRect) # Draw the text titleSurf, titleRect = self.makeTextObjs(text, self.BIGFONT, self.TEXTCOLOR) titleRect.center = (int(self.WINDOWWIDTH / 2) - 3, int(self.WINDOWHEIGHT / 2) - 3) self.DISPLAYSURF.blit(titleSurf, titleRect) # Draw the additional "Press a key to play." text. pressKeySurf, pressKeyRect = self.makeTextObjs('Press a key to play.', self.BASICFONT, self.TEXTCOLOR) pressKeyRect.center = (int(self.WINDOWWIDTH / 2), int(self.WINDOWHEIGHT / 2) + 100) self.DISPLAYSURF.blit(pressKeySurf, pressKeyRect) while self.checkForKeyPress() == None: pygame.display.update() self.FPSCLOCK.tick() def checkForQuit(self): for event in pygame.event.get(QUIT): # get all the QUIT events self.terminate() # terminate if any QUIT events are present for event in pygame.event.get(KEYUP): # get all the KEYUP events if event.key == K_ESCAPE: self.terminate() # terminate if the KEYUP event was for the Esc key pygame.event.post(event) # put the other KEYUP event objects back def calculateLevelAndFallFreq(self,score): # Based on the score, return the level the player is on and # how many seconds pass until a falling piece falls one space. level = int(score / 10) + 1 fallFreq = 0.27 - (level * 0.02) return level, fallFreq def getNewPiece(self): # return a random new piece in a random rotation and color shape = random.choice(list(self.PIECES.keys())) newPiece = {'shape': shape, 'rotation': random.randint(0, len(self.PIECES[shape]) - 1), 'x': int(self.BOARDWIDTH / 2) - int(self.TEMPLATEWIDTH / 2), 'y': -2, # start it above the board (i.e. less than 0) 'color': random.randint(0, len(self.COLORS)-1)} return newPiece def addToBoard(self,board, piece): # fill in the board based on piece's location, shape, and rotation for x in range(self.TEMPLATEWIDTH): for y in range(self.TEMPLATEHEIGHT): if self.PIECES[piece['shape']][piece['rotation']][y][x] != self.BLANK: board[x + piece['x']][y + piece['y']] = piece['color'] def getBlankBoard(self): # create and return a new blank board data structure board = [] for i in range(self.BOARDWIDTH): board.append([self.BLANK] * self.BOARDHEIGHT) return board def isOnBoard(self,x, y): return x >= 0 and x < self.BOARDWIDTH and y < self.BOARDHEIGHT def isValidPosition(self,board, piece, adjX=0, adjY=0): # Return True if the piece is within the board and not colliding for x in range(self.TEMPLATEWIDTH): for y in range(self.TEMPLATEHEIGHT): isAboveBoard = y + piece['y'] + adjY < 0 if isAboveBoard or self.PIECES[piece['shape']][piece['rotation']][y][x] == self.BLANK: continue if not self.isOnBoard(x + piece['x'] + adjX, y + piece['y'] + adjY): return False if board[x + piece['x'] + adjX][y + piece['y'] + adjY] != self.BLANK: return False return True def isCompleteLine(self,board, y): # Return True if the line filled with boxes with no gaps. for x in range(self.BOARDWIDTH): if board[x][y] == self.BLANK: return False return True def removeCompleteLines(self,board): # Remove any completed lines on the board, move everything above them down, and return the number of complete lines. numLinesRemoved = 0 y = self.BOARDHEIGHT - 1 # start y at the bottom of the board while y >= 0: if self.isCompleteLine(board, y): # Remove the line and pull boxes down by one line. for pullDownY in range(y, 0, -1): for x in range(self.BOARDWIDTH): board[x][pullDownY] = board[x][pullDownY-1] # Set very top line to blank. for x in range(self.BOARDWIDTH): board[x][0] = self.BLANK numLinesRemoved += 1 # Note on the next iteration of the loop, y is the same. # This is so that if the line that was pulled down is also # complete, it will be removed. else: y -= 1 # move on to check next row up return numLinesRemoved def convertToPixelCoords(self,boxx, boxy): # Convert the given xy coordinates of the board to xy # coordinates of the location on the screen. return (self.XMARGIN + (boxx * self.BOXSIZE)), (self.TOPMARGIN + (boxy * self.BOXSIZE)) def drawBox(self,boxx, boxy, color, pixelx=None, pixely=None): if color == self.BLANK: return if pixelx == None and pixely == None: pixelx, pixely = self.convertToPixelCoords(boxx, boxy) pygame.draw.rect(self.DISPLAYSURF, self.COLORS[color], (pixelx + 1, pixely + 1, self.BOXSIZE - 1, self.BOXSIZE - 1)) pygame.draw.rect(self.DISPLAYSURF, self.LIGHTCOLORS[color], (pixelx + 1, pixely + 1, self.BOXSIZE - 4, self.BOXSIZE - 4)) def drawBoard(self,board): # draw the border around the board pygame.draw.rect(self.DISPLAYSURF, self.BORDERCOLOR, (self.XMARGIN - 3, self.TOPMARGIN - 7, (self.BOARDWIDTH * self.BOXSIZE) + 8, (self.BOARDHEIGHT * self.BOXSIZE) + 8), 5) # fill the background of the board pygame.draw.rect(self.DISPLAYSURF, self.BGCOLOR, (self.XMARGIN, self.TOPMARGIN, self.BOXSIZE * self.BOARDWIDTH, self.BOXSIZE * self.BOARDHEIGHT)) # draw the individual boxes on the board for x in range(self.BOARDWIDTH): for y in range(self.BOARDHEIGHT): self.drawBox(x, y, board[x][y]) def drawStatus(self,score, level): # draw the score text scoreSurf = self.BASICFONT.render('Score: %s' % score, True, self.TEXTCOLOR) scoreRect = scoreSurf.get_rect() scoreRect.topleft = (self.WINDOWWIDTH - 150, 20) self.DISPLAYSURF.blit(scoreSurf, scoreRect) # draw the level text levelSurf = self.BASICFONT.render('Level: %s' % level, True, self.TEXTCOLOR) levelRect = levelSurf.get_rect() levelRect.topleft = (self.WINDOWWIDTH - 150, 50) self.DISPLAYSURF.blit(levelSurf, levelRect) def drawPiece(self,piece, pixelx=None, pixely=None): shapeToDraw = self.PIECES[piece['shape']][piece['rotation']] if pixelx == None and pixely == None: # if pixelx & pixely hasn't been specified, use the location stored in the piece data structure pixelx, pixely = self.convertToPixelCoords(piece['x'], piece['y']) # draw each of the boxes that make up the piece for x in range(self.TEMPLATEWIDTH): for y in range(self.TEMPLATEHEIGHT): if shapeToDraw[y][x] != self.BLANK: self.drawBox(None, None, piece['color'], pixelx + (x * self.BOXSIZE), pixely + (y * self.BOXSIZE)) def drawNextPiece(self,piece): # draw the "next" text nextSurf = self.BASICFONT.render('Next:', True, self.TEXTCOLOR) nextRect = nextSurf.get_rect() nextRect.topleft = (self.WINDOWWIDTH - 120, 80) self.DISPLAYSURF.blit(nextSurf, nextRect) # draw the "next" piece self.drawPiece(piece, pixelx=self.WINDOWWIDTH-120, pixely=100)