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()
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
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 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)
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 Snowflake: flakeImage = ('sprite/scenario/flakeL.png', 'sprite/scenario/flakeR.png') endOfScreen = False # Checks if snowflake is at end of screen global startSpeed changeY = startSpeed # Snowflake speed 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() # Changes position def set_position(self): if self.pos == "left": self.texture.set_position(flakeDist, self.y) else: self.texture.set_position(-flakeDist, self.y) # Displays snowflake def paint(self): self.set_position() self.texture.draw() # Moves snowflake def move(self, snowmanPos): newY = self.y + self.changeY lowerBound = newY + branchHeight # y coordinate for bottom of flake bottomOfSnowman = snowmanY + snowmanH # y value for bottom of snowman # New flake would be in snowmans space if lowerBound > snowmanY and newY < bottomOfSnowman \ and snowmanPos == self.pos: # Gain points and health by catching snowflakes scorer.snowflake_calc() # This allows us to delete snowflake later self.endOfScreen = True elif (lowerBound > sHeight): # Snowflake reaches end of screen self.endOfScreen = True else: # Snowflake moves down self.y += self.changeY self.paint()
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
def show_lives(self): life = GameImage("images/life.png") life.set_position(78, 170) life.draw() text = "LIFE:{}".format(self.lives) # text_space = len(text) * 14 self.window.draw_text(text=text, x=60, y=245, size=24, color=(200, 200, 200), font_name="Monospace", bold=True)
class LifeHud: 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 draw(self): self.bar.draw() self.value.draw() def add_life(self): point = self.value.curr_frame + 1 self.value.set_curr_frame(self.__checkLife(point)) def full_life(self): self.value.set_curr_frame(4) def lose_life(self): point = self.value.curr_frame - 1 if point >= 0: self.value.set_curr_frame(self.__checkLife(point)) return point def is_empty_life(self): return self.value.curr_frame == 0 def empty_life(self): self.value.set_curr_frame(0) def __checkLife(self, point): if point < 0: return 0 elif point > 4: return 4 else: return point def move(self, x, y): self.bar.set_position(x, y) self.value.set_position(x - 10, y - 10)
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 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 Tela(object): def __init__(self, window): self.window = window #self.setFundo() self.setSolo() self.fundo = [] def setTela(self): self.window.set_title("Ninja's Life") def setTelaRank(self): self.fundo = GameImage("img/fundo_rank.png") self.fundo.draw() self.window.set_title("Ninja's Life") def setTelaDificuldade(self): self.fundo = GameImage("img/fundo_1.png") self.fundo.draw() self.window.set_title("Ninja's Life") def setFundo(self): self.fundo_atual = Animation("img/Fundo_1.png", 1, loop=False) self.fundo.append(self.fundo_atual) def getFundo(self): self.fundo[globais.FUNDO_ATUAL].draw() self.solo_0.draw() def setSolo(self): self.solo_0 = Animation("img/chao_1.png", 4, loop=False) self.solo_0.set_position(-10, globais.HEIGHT - self.solo_0.height) globais.HEIGHT_S = self.solo_0.height def getSolo(self): return self.solo_0 def novaTela(self): if (globais.POS_X + globais.WIDTH_P > globais.WIDTH): self.setFundo() globais.FUNDO_ATUAL += 1 globais.POS_X = 0
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 MenuHud: 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 def draw(self): self.button.draw() if self.show_menu: self.menu_screen.draw() self.menu_button.draw() self.return_button.draw() def update(self): if self.window.get_mouse().is_button_pressed( 1) and self.window.get_mouse().is_over_object(self.button): BUTTON_SOUND.play() self.window.main_scene.running = False self.show_menu = True elif self.window.get_keyboard().key_pressed( "ESCAPE") or self.return_button.is_button_pressed(): self.window.main_scene.running = True self.show_menu = False elif self.menu_button.is_button_pressed(): self.window.main_scene.running = True self.show_menu = False self.window.main_scene.change_scene()
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
class Branches: global startSpeed changeY = startSpeed # Speed at which branch moves down direction = "up" #Determines whether speed increases or decreases over time # Images for branches tree_types = ('sprite/branches/right.png', 'sprite/branches/left.png', 'sprite/branches/middle.png') endOfScreen = False # Records if branch has reached end of screen 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) # Change position of object def set_position(self, x, y): self.texture.set_position(x, y) # Display branch def paint(self): self.set_position(0, self.y) self.texture.draw() # Move branch def move(self, snowmanPos): global game_state # Finds new y value (which defines top of branch) newY = self.y + self.changeY lowerBound = newY + branchHeight # y coordinate for bottom of branch bottomOfSnowman = snowmanY + snowmanH # y value for bottom of snowman if lowerBound > snowmanY and newY < bottomOfSnowman \ and snowmanPos == self.pos: # New branch would be in snowmans space (snowman hits branch) game_state = 0 # Game over gameEnd.play() # Play sound effect # Branch reaches end of screen so starts at top again elif (newY > sHeight): # Useful for objects of type 'middle' which create tree self.y = -64 self.paint() # Useful for other objects which are actual branches self.endOfScreen = True else: # Branch moves down self.y += self.changeY self.paint()
class Popup: def __init__(self, janela): self.janela = janela self.objeto = GameImage(Popup_Images.inventario['fundo']) # popup(1) -> inventário # popup(2) -> prontuario 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 draw(self): self.objeto.draw() self.janela.draw_text(self.texto, self.janela.width / 2 - self.largura / 2 + self.texto.__sizeof__() * 2, self.janela.height / 2 - self.altura / 4 + 40, size=20, color=(0, 0, 0), bold=True) if (self.tipo == 1): self.bt_repor.draw() self.bt_dormir.draw() self.bt_comer.draw() elif (self.tipo == 2 or self.tipo == 0): self.bt_cancelar.draw() self.bt_ok.draw() def bt_clicked(self): mouse = self.janela.get_mouse() if (self.tipo == 1): if self.bt_comer.is_clicked(mouse): return 3 if self.bt_dormir.is_clicked(mouse): return 2 if self.bt_repor.is_clicked(mouse): return 1 elif (self.tipo == 2 or self.tipo == 0): if self.bt_cancelar.is_clicked(mouse): return 0 if self.bt_ok.is_clicked(mouse): return 4 return 0
class Game: 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 update_counters(self): self.block_rain_counter.update_logic() self.rain_line_counter.update_logic() for counter in self.effects.values(): counter.update_logic() def update_effects(self): self.ball.unstoppable = self.effects["unstoppable"].active def update_score(self, score): if not self.game_over: self.score += score def update_logic(self): self.update_counters() self.update_effects() if not self.game_started and self.lives > 0: self.detect_game_start() return if self.ball.collided(self.pad): self.ball.handle_collision(self.pad) if self.ball.collided_with_bottom(): self.lives -= 1 self.ball.collision_change("VERTICAL") self.game_started = False if self.lives <= 0 and not self.game_over: self.game_over = True self.block_rain_counter.start() if self.window.get_keyboard().key_pressed("ESC"): from binary_break.screens.menu import Menu globals.currentContainer = Menu() self.blocks.update_logic() if self.block_rain_counter.active: self.run_block_rain() if self.game_over: if not self.block_rain_counter.active: self.register_score() from binary_break.screens.menu import Menu globals.currentContainer = Menu() return for line in self.blocks: for block in line: if block and self.ball.collided(block): block.handle_collision(self.ball, self.blocks) self.update_score(block.score_value) for item in self.items: if item.collided(self.pad): item.handle_effect(self) self.score_increment_rate -= globals.delta_time if self.score_increment_rate < 0: self.score_increment_rate = 0.1 self.update_score(1) def render(self): self.update_logic() self.window.set_background_color(globals.backgroundColor) self.background.draw() self.lateral_bar.draw() self.pad.render() if self.game_started: self.ball.render() else: self.put_ball_over_pad() self.ball.draw() for line in self.blocks: for block in line: block.render() if block else None if not self.game_over: for item in self.items: item.render() self.show_score() self.show_lives() self.sound.set_volume(20) self.sound.play() self.sound.set_repeat(True) def detect_game_start(self): if self.window.get_keyboard().key_pressed("SPACE"): self.game_started = True def run_block_rain(self): if not self.rain_line_counter.active: self.blocks.add_line() self.rain_line_counter.start() def show_score(self): text = "SCORE:{}".format(self.score) # text_space = len(text) * 14 self.window.draw_text(text=text, x=45, y=40, size=24, color=(200, 200, 200), font_name="Monospace", bold=True) def register_score(self): name = input("Por favor, digite seu nome/nickname: ").strip() score_file = open("data/score.txt", "a+") score_file.write("{} {}\n".format(name, self.score)) score_file.close() def add_special_item(self, item): if not self.game_over: self.items.append(item) def put_ball_over_pad(self): self.ball.set_position( self.pad.x + self.pad.width / 2 - self.ball.width / 2, self.pad.y - self.ball.height) def show_lives(self): life = GameImage("images/life.png") life.set_position(78, 170) life.draw() text = "LIFE:{}".format(self.lives) # text_space = len(text) * 14 self.window.draw_text(text=text, x=60, y=245, size=24, color=(200, 200, 200), font_name="Monospace", bold=True)
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
while True: if game_state == 0: if teclado.key_pressed('left') or teclado.key_pressed('right'): if not teclado_pressionado: lado = 1 if teclado.key_pressed('left') else 0 lado_bambam = 'esquerda' if teclado.key_pressed('left') else 'direita' lado_atingido_1, lado_atingido_2 = arvore.hit(lado) bambam.hit(lado_bambam) pontuador.pontuar() if lado == lado_atingido_1 or lado == lado_atingido_2: game_state = 1 teclado_pressionado = True else: teclado_pressionado = False background.draw() arvore.update() arvore.draw() bambam.update() bambam.draw() pontuador.update() if not pontuador.bambam_alive(): game_state = 1 pontuador.draw() elif game_state == 1: if not record_checked: if pontuador.get_pontuacao() > score_manager.get_recorde(): score_manager.set_new_record(pontuador.get_pontuacao()) record_checked = True
class SelectPlaneScene(SceneInterface): 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) def handle_event(self, speed: int, scene: bool): if self.mouse.is_over_object(self.jet_green): self.jet_g_bool = True self.jet_y_bool = False if self.mouse.is_button_pressed(mouse.BUTTON_LEFT): self.hud.set_ship_look(JET_GREEN_FLY) self.select = True elif self.mouse.is_over_object(self.jet_yellow): self.jet_y_bool = True self.jet_g_bool = False if self.mouse.is_button_pressed(mouse.BUTTON_LEFT): self.hud.set_ship_look(JET_YELLOW_FLY) self.select = True else: self.time = 2 self.jet_g_bool = False self.jet_y_bool = False def __draw_jet(self, jet: Sprite, enabled: bool): if enabled: if self.time >= 0.0: self.time -= self.window.delta_time() if 1.7 <= self.time <= 2.0: jet.draw() elif 1.1 <= self.time <= 1.4: jet.draw() elif 0.5 <= self.time <= 0.8: jet.draw() elif self.time <= 0.0: jet.draw() else: jet.draw() def draw(self, state: bool): self.fundo.draw() self.point_background.draw() self.__draw_jet(self.jet_yellow, self.jet_y_bool) self.__draw_jet(self.jet_green, self.jet_g_bool) self.text.draw() def update(self, state: bool): if self.select: self.window.main_scene.change_scene('Desert')
def draw_sprite(self, sprite: GameImage, position: Vec): sx, sy = self.get_screen_position(*position) sprite.set_position(sx, sy) sprite.draw()
class ShopHud: def __init__(self, window): self.window = window self.mouse = window.get_mouse() self.button = GameImage(SHOP_HUD) self.button.set_position(10, self.window.height - 130) self.shop_screen = GameImage(SHOP_SCREEN) self.shop_screen.set_position( self.window.width / 2 - self.shop_screen.width / 2, 85) self.blue_fire_shop = GameImage(BLUE_FIRE_SHOP) self.blue_fire_shop.set_position( self.window.width / 2 - self.shop_screen.width / 2, 140) self.blue_fire_shop_b = GameImage(BLUE_FIRE_SHOP_B) self.blue_fire_shop_b.set_position( self.window.width / 2 - self.shop_screen.width / 2, 140) self.blue_text = CenterText(self.window, self.window.width / 2 + 20, 294, color=SKY_BLUE, size=46, text="10 C") self.pink_fire_shop = GameImage(PINK_FIRE_SHOP) self.pink_fire_shop.set_position( self.window.width / 2 - self.shop_screen.width / 2, 140) self.pink_fire_shop_b = GameImage(PINK_FIRE_SHOP_B) self.pink_fire_shop_b.set_position( self.window.width / 2 - self.shop_screen.width / 2, 140) self.pink_text = CenterText(self.window, self.window.width / 2 + 20, 370, color=PURPLE, size=46, text="10 C") self.torpedo_shop = GameImage(TORPEDO_SHOP) self.torpedo_shop.set_position( self.window.width / 2 - self.shop_screen.width / 2, 140) self.torpedo_shop_b = GameImage(TORPEDO_SHOP_B) self.torpedo_shop_b.set_position( self.window.width / 2 - self.shop_screen.width / 2, 140) self.torpedo_text = CenterText(self.window, self.window.width / 2 + 20, 446, color=FOREST_GREEN, size=46, text="10 C") self.torpedo_black_shop = GameImage(TORPEDO_BLACK_SHOP) self.torpedo_black_shop.set_position( self.window.width / 2 - self.shop_screen.width / 2, 140) self.torpedo_black_shop_b = GameImage(TORPEDO_BLACK_SHOP_B) self.torpedo_black_shop_b.set_position( self.window.width / 2 - self.shop_screen.width / 2, 140) self.torpedo_black_text = CenterText(self.window, self.window.width / 2 + 20, 522, color=BLACK, size=46, text="10 C") self.choose_skin = [True, False, False, False] self.time_delay = 0 self.points = 0 self.show_shop = False def draw_shop(self): if self.choose_skin[0]: self.blue_fire_shop_b.draw() self.pink_fire_shop.draw() self.torpedo_shop.draw() self.torpedo_black_shop.draw() elif self.choose_skin[1]: self.blue_fire_shop.draw() self.pink_fire_shop_b.draw() self.torpedo_shop.draw() self.torpedo_black_shop.draw() elif self.choose_skin[2]: self.blue_fire_shop.draw() self.pink_fire_shop.draw() self.torpedo_shop_b.draw() self.torpedo_black_shop.draw() elif self.choose_skin[3]: self.blue_fire_shop.draw() self.pink_fire_shop.draw() self.torpedo_shop.draw() self.torpedo_black_shop_b.draw() self.blue_text.draw() self.pink_text.draw() self.torpedo_text.draw() self.torpedo_black_text.draw() def draw(self): self.button.draw() if self.show_shop: self.shop_screen.draw() self.draw_shop() def update(self): if self.__is_clicking(self.button): BUTTON_SOUND.play() self.window.main_scene.running = not self.window.main_scene.running self.show_shop = not self.show_shop elif self.window.get_keyboard().key_pressed("ESCAPE"): self.window.main_scene.running = True self.show_shop = False elif self.__is_clicking_shop(0): if self.window.main_scene.get_hud().set_special_look(0): self.choose_skin = [True, False, False, False] elif self.__is_clicking_shop(1): if self.window.main_scene.get_hud().set_special_look(1): self.choose_skin = [False, True, False, False] elif self.__is_clicking_shop(2): if self.window.main_scene.get_hud().set_special_look(2): self.choose_skin = [False, False, True, False] elif self.__is_clicking_shop(3): if self.window.main_scene.get_hud().set_special_look(3): self.choose_skin = [False, False, False, True] def __is_clicking(self, button: GameImage): self.time_delay -= self.window.delta_time() if self.mouse.is_over_object(button) and self.mouse.is_button_pressed( self.mouse.BUTTON_LEFT): if self.time_delay <= 0: self.time_delay = 0.5 return True return False def __is_clicking_shop(self, pos: int): if self.choose_skin[pos]: return False if pos == 0: if self.mouse.is_over_area( (480, 250), (800, 330)) and self.mouse.is_button_pressed( self.mouse.BUTTON_LEFT): return True elif pos == 1: if self.mouse.is_over_area( (480, 331), (800, 410)) and self.mouse.is_button_pressed( self.mouse.BUTTON_LEFT): return True elif pos == 2: if self.mouse.is_over_area( (480, 411), (800, 480)) and self.mouse.is_button_pressed( self.mouse.BUTTON_LEFT): return True else: if self.mouse.is_over_area( (480, 481), (800, 560)) and self.mouse.is_button_pressed( self.mouse.BUTTON_LEFT): return True return 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)
# If snowie is no longer alive, game ends if not scorer.snowie_alive(): game_state = 0 # Game over gameEnd.play() # Plays sound effect counter += 1 # Shows any changes made pygame.display.flip() window.update() elif game_state == 2: # Menu screen background.draw() if counter < 500: # Initially display instructions for some time menu_bg.draw() window.draw_text(str(score_manager.get_records()), 512 - 260, 320, color=(255, 255, 255), font_file='font.TTF', size=20) else: # Then show 'press enter to play' button button.draw() pygame.display.flip() counter += 1
class BattleSceneFirst(SceneInterface): 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] def handle_event(self, speed, state): if not state: return self.shot_time -= self.hud.get_window().delta_time() for i in range(len(self.enemys)): self.enemy_shot_times[i] -= self.hud.get_window().delta_time() if self.air_plane.get_shot().collide(self.enemys[i]): self.point += 1 if self.point % 4 == 0: self.special.change_visibility(self.enemys[i].animation.x, self.enemys[i].animation.y) if self.point % 5 == 0: self.life.change_visibility(self.enemys[i].animation.x, self.enemys[i].animation.y) if (self.enemys[i].lifeModel.lose_life()) == 0: self.enemys[i].hidden() if self.air_plane.get_shot_special().collide(self.enemys[i]): self.point += 3 self.enemys[i].lifeModel.empty_life() self.enemys[i].hidden() if self.enemys[i].get_shot().collide(self.air_plane): self.hud.lose_life() if self.enemy_shot_times[i] <= 0.0: self.enemys[i].can_shot(self.air_plane) self.enemy_shot_times[i] = 2 if self.key_board.key_pressed("UP"): # Direcional ^ self.air_plane.up(speed * 2) if self.key_board.key_pressed("DOWN"): self.air_plane.down(speed * 2) if self.key_board.key_pressed("RIGHT"): self.air_plane.forward(speed * 2) if self.key_board.key_pressed("LEFT"): self.air_plane.backward(speed * 2) if self.shot_time <= 0.0: if self.key_board.key_pressed("SPACE"): self.air_plane.shot() self.shot_time = 1 if self.key_board.key_pressed("S") and self.hud.get_special() >= 4: self.hud.lose_special() self.air_plane.shot_special() for game_object in self.game_objects: game_object.move(speed) if self.coin.collide(self.air_plane): self.hud.point.addPoint(1) if self.life.collide(self.air_plane): self.life.change_visibility() self.hud.add_life() if self.special.collide(self.air_plane): self.special.change_visibility() self.hud.add_special() def draw(self, state): for game_object in self.game_objects: game_object.draw() for enemy in self.enemys: enemy.get_life().draw() self.hud.draw() self.point_background.draw() CenterText(self.hud.get_window(), self.hud.get_window().width / 2, 30, GOLD, 64, "Pontos " + str(self.point)).draw() def update(self, state): if not state: return if self.point >= POINTS: self.hud.get_window().main_scene.change_scene('SecondHistory') for game_object in self.game_objects: game_object.update()