def __init__(self, **kw): super().__init__(**kw) if app.root: Clock.schedule_once(self.render_background) self.children[0].children[2].markup = True label = CoreLabel(text=self.icon, font_name='fnt/segmdl2.ttf', font_size=72, color=theme.sec, padding=[18, 18]) label.refresh() self._icon_tex = label.texture self._icon_rect = self.canvas.get_group('icon')[0] # close button texture label = CoreLabel(text='\u00d7', font_size=36, size=(36, 36)) label.refresh() self.canvas.after.get_group('close_button')[0].texture = label.texture self._close_button_color = theme.sec # close button hovering behavior Window.bind(mouse_pos=self.on_mouse_pos) Clock.schedule_interval(self.dance_icon, 2)
def __init__(self, text, pos, font=40, align='left', color=Color(1, 1, 1), anim=None): super(TextLabel, self).__init__() self.t = 0 self.size_func = anim self.font = font label = CoreLabel(text=text, font_size=self.font, font_name='Verdana') label.refresh() self.text = label.texture self.color = color self.add(self.color) self.ratio = self.text.size[0] / self.text.size[1] if align == 'left': self.pos = pos else: self.pos = (pos[0] - self.text.size[0] / 2, pos[1] - self.text.size[1] / 2) self.item = Rectangle(size=self.text.size, pos=self.pos, texture=self.text) self.add(self.item)
def __init__(self, choose_song): super(MainMenuDisplay, self).__init__() self.label = TextLabel( text="Click on a song to select it, and press ENTER to confirm", pos=(0, 0), font=Window.height / 30) self.add(self.label) self.buttons = [] self.choose_song = choose_song x = Window.width - 1 / 6 * Window.width y = 200 i = 0 label = CoreLabel(text="CHOOSE A SONG", font_size=Window.height / 10) label.refresh() text = label.texture title = Rectangle(texture=text, pos=(Window.width / 2 - text.size[0] / 2, Window.height * 3 / 4), size=text.size) self.add(title) for song in songs: button = SongButtons(y=y, song=song, start_end=start_end[i], key=keys[i]) self.buttons.append(button) self.add(button) i += 1 y += Window.height / 7
class Text_Image(Widget): def __init__(self, x, y, txt, src="", fontsize=30): self.live_label = CoreLabel(text=txt, font_size=fontsize) self.live_label.refresh() self.label_instruction = Rectangle(texture=self.live_label.texture, pos=(x, y), size=self.live_label.texture.size) self.image_instruction = Rectangle(source=src, pos=(x + 100, y), size=(30, 30))
def createCoins(self, parts, shape, color): # Шрифт LabelBase.register(name='CG', fn_regular=paths['font']) with self.canvas: Color(0, 0, 0, 1) #black # Базовые размеры w = 595 h = 842 # Размеры жетона x = 94 y = 94 # Отступ от края листа margin = 70 # Фон Color(1, 1, 1, 1) #white self.canvas.add(Rectangle(size=[w, h], pos=[0, 0])) # Жетоны for i in range(len(parts)): # Ряд жетонов на листе row = 1 row += int(i / 6) # Надпись на жетоне name = CoreLabel(font_name='CG', text=parts[i], font_size=45) name.refresh() name = name.texture Color(0, 0, 0, 1) #black if shape == 'round': self.canvas.add( Line(circle=(x * (i - (row - 1) * 6) + margin, y * row, 47), width=1)) if shape == 'square': self.canvas.add( Line(rectangle=(x * (i - (row - 1) * 6) + margin - x / 2, y * row - y / 2, 94, 94), width=1)) Color(rgba=color) self.canvas.add( Rectangle(size=name.size, pos=[(x * (i - (row - 1) * 6) + margin) - (name.size[0] / 2), y * row - name.size[1] / 2], texture=name))
def update_text(self, text, color): label = CoreLabel(text=text, font_size=self.font) label.refresh() self.remove(self.color) self.remove(self.item) self.color = Color(*color) self.add(self.color) self.text = label.texture self.item.texture = self.text self.item.size = self.text.size self.add(self.item) self.ratio = self.text.size[0] / self.text.size[1] # run(MainWidget, None)
def __init__(self, y, text, action): super(GeneralButton, self).__init__() self.action = action self.color = Color(*(1, 1, 1)) self.add(self.color) #added lable for texturing the buttons label = CoreLabel(text=text, font_size=Window.height / 20) label.refresh() text = label.texture self.size = text.size x = Window.width / 2 - text.size[0] / 2 self.pos = (x, y) self.button = Rectangle(texture=text, pos=self.pos, size=text.size) self.add(self.button)
def __init__(self, y, song, start_end, key): super(SongButtons, self).__init__() self.start_end = start_end self.song = song self.key = key self.color = Color(*(1, 1, 1)) self.add(self.color) #added lable for texturing the buttons label = CoreLabel(text=song, font_size=Window.height / 20) label.refresh() text = label.texture self.size = text.size x = Window.width / 2 - text.size[0] / 2 self.pos = (x, y) self.button = Rectangle(texture=text, pos=self.pos, size=text.size) self.add(self.button)
class Progress(ProgressBar): def __init__(self, **kwargs): super(Progress, self).__init__(**kwargs) self.label = CoreLabel(text='Time Left: ', font_size=20) self.texture_size = None self.refresh_text() self.draw() def draw(self): with self.canvas: self.canvas.clear() # Draw no progress bar Color(.188, .209, .148) RoundedRectangle(pos=self.pos, size=self.size) Color(.5, 0, 0) if self.value > 0: var = 100.0 / self.value # Draw progress bar RoundedRectangle(pos=self.pos, size=(self.width / var, self.height)) # Center and draw the text Color(1, 1, 1, 1) RoundedRectangle(texture=self.label.texture, size=self.texture_size, pos=(self.size[0] / 2 - self.texture_size[0] / 2, self.size[1] / 2 - self.texture_size[1] / 2)) def refresh_text(self): # Render the label self.label.refresh() # Set the texture size each refresh self.texture_size = list(self.label.texture.size) def set_value(self, value): self.value = value self.refresh_text() self.size = (400, 30) self.draw()
class Score(Widget): def __init__(self, x, y): self._score_label = CoreLabel(text="Score : 0", font_size=30) self._score_label.refresh() self.score_label_instruction = Rectangle( texture=self._score_label.texture, pos=(x, y), size=self._score_label.texture.size) self._score = 0 @property def score(self): return self._score @score.setter def score(self, val): self._score = val self._score_label.text = "Score : " + str(val) self._score_label.refresh() self.score_label_instruction.texture = self._score_label.texture self.score_label_instruction.size = self._score_label.texture.size
class GameWidget(Widget): def __init__(self, **kwargs): #**kwargs is a dictionary of keyword arguments super(GameWidget,self).__init__(**kwargs) self._keyboard = Window.request_keyboard(self._on_keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_key_down) self._keyboard.bind(on_key_up=self._on_key_up) self._lives_label = CoreLabel(text="Lives: 0", font_size=100, font_name='./fonts/absolutepink.otf') self._lives_label.refresh() self._lives = 3 self._stars = -1 #to initialise, however will never get this value self._levels = 0 #initialise self._num_portals = 0 #Registering event types allows the dispatcher to validate event handler names as they are attached and to search attached objects for suitable handlers. self.register_event_type("on_frame") with self.canvas: self._lives_instruction = Rectangle(texture=self._lives_label.texture, pos=(7, Window.height *0.93), size=self._lives_label.texture.size) self.keysPressed = set() self._entities = set() Clock.schedule_interval(self._on_frame, 0) Clock.schedule_interval(self.checks_win_lose, 0) def checks_win_lose(self, dt): if self.lives == 0: manager.current = "LOSE" self.lives = 3 elif self.stars == 0: if self.levels == 3: #won at level 3 manager.current = "WIN" self.stars = -1 else: #portal appears self.spawn_portal() def spawn_animal(self): animal = Animal() self.add_entity(animal) def spawn_portal(self): #appears as canvas widget if self._num_portals == 0: self._portal = Portal() self.add_entity(self._portal) self._num_portals += 1 #ensures that it only appears once #if position of player within pos of portal, advance to nxt lvl + remove canvas widget if (self.player.pos[0] + self.player.size[0]/2) >= (self._portal.pos[0] + self._portal.size[0]/2): self.stars = -1 #to ensure constant looping self._num_portals -= 1 manager.current = "LEVEL{}".format(self.levels + 1) # Create instance objects from Star class def spawn_stars(self, num_stars): self.stars = num_stars for i in range(num_stars): star = Star() self.add_entity(star) # Create instance objects from Blackhole class def spawn_blackhole(self, num_blackhole): for i in range(num_blackhole): random_x = random.uniform(Window.width*0.15, Window.width*0.85) # randomize x-coordinate random_y = random.uniform(Window.height*0.5, Window.height*0.85) # randomize y-coordinate rand_pos = (random_x, random_y) rand_length = random.uniform(200,250) # randomize size of stars blackhole = Blackhole(rand_pos, rand_length) #called the class Blackhole self.add_entity(blackhole) def remove_all(self): for entity in self._entities.copy(): #.copy() to allow iteration through all elements while elements in original list is being romved if isinstance(entity, Star) or isinstance(entity, Blackhole) or isinstance(entity, Hook) or isinstance(entity, Portal) or isinstance(entity, Animal): self.remove_entity(entity) def _on_frame(self, dt): self.dispatch("on_frame", dt) def on_frame(self, dt): pass @property def lives(self): return self._lives @lives.setter def lives(self,value): self._lives = value self._lives_label.text = "Lives = " + str(value) self._lives_label.refresh() self._lives_instruction.texture = self._lives_label.texture self._lives_instruction.size = self._lives_label.texture.size @property def stars(self): return self._stars @stars.setter def stars(self,value): self._stars = value @property def levels(self): return self._levels @levels.setter def levels(self, value): self._levels = value def add_entity(self, entity): self._entities.add(entity) self.canvas.add(entity._instruction) def remove_entity(self, entity): if entity in self._entities: self._entities.remove(entity) self.canvas.remove(entity._instruction) def collides(self, e1, e2): r1x = e1.pos[0] r1y = e1.pos[1] r2x = e2.pos[0] r2y = e2.pos[1] r1w = e1.size[0] r1h = e1.size[1] r2w = e2.size[0] r2h = e2.size[1] # Center coordinates of the tip of arrow x = r2x + r2w/2 y = r2y + r2h - r2w/2 # Check if tip of arrow is within the target boundary if (r1x < x < r1x + r1w and r1y < y < r1y + r1h): return True else: return False def colliding_entities(self, entity): result = set() for e in self._entities: if self.collides(e, entity) and e != entity: result.add(e) return result def _on_keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_key_down) self._keyboard.unbind(on_key_up=self._on_key_up) self._keyboard = None def _on_key_down(self, keyboard, keycode, text, modifiers): self.keysPressed.add(keycode[1]) def _on_key_up(self, keyboard, keycode): text = keycode[1] if text in self.keysPressed: self.keysPressed.remove(text)
class GameWidget(Widget): def __init__(self, **kwargs): super().__init__(**kwargs) self._keyboard = Window.request_keyboard(self._on_keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_key_down) self._keyboard.bind(on_key_up=self._on_key_up) self._score_label = CoreLabel(text="Score: 0", font_size=20) self._score_label.refresh() self._score = 0 self.register_event_type("on_frame") with self.canvas: Rectangle(source="assets/background.png", pos=(0, 0), size=(Window.width, Window.height)) self._score_instruction = Rectangle( texture=self._score_label.texture, pos=(0, Window.height - 50), size=self._score_label.texture.size) self.keysPressed = set() self._entities = set() Clock.schedule_interval(self._on_frame, 0) self.sound = SoundLoader.load("assets/music.wav") self.sound.play() Clock.schedule_interval(self.spawn_enemies, 2) def spawn_enemies(self, dt): for i in range(5): random_x = random.randint(0, Window.width) y = Window.height random_speed = random.randint(100, 300) self.add_entity(Enemy((random_x, y), random_speed)) def _on_frame(self, dt): self.dispatch("on_frame", dt) def on_frame(self, dt): pass @property def score(self): return self._score @score.setter def score(self, value): self._score = value self._score_label.text = "Score: " + str(value) self._score_label.refresh() self._score_instruction.texture = self._score_label.texture self._score_instruction.size = self._score_label.texture.size def add_entity(self, entity): self._entities.add(entity) self.canvas.add(entity._instruction) def remove_entity(self, entity): if entity in self._entities: self._entities.remove(entity) self.canvas.remove(entity._instruction) def collides(self, e1, e2): r1x = e1.pos[0] r1y = e1.pos[1] r2x = e2.pos[0] r2y = e2.pos[1] r1w = e1.size[0] r1h = e1.size[1] r2w = e2.size[0] r2h = e2.size[1] if (r1x < r2x + r2w and r1x + r1w > r2x and r1y < r2y + r2h and r1y + r1h > r2y): return True else: return False def colliding_entities(self, entity): result = set() for e in self._entities: if self.collides(e, entity) and e != entity: result.add(e) return result def _on_keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_key_down) self._keyboard.unbind(on_key_up=self._on_key_up) self._keyboard = None def _on_key_down(self, keyboard, keycode, text, modifiers): self.keysPressed.add(keycode[1]) def _on_key_up(self, keyboard, keycode): text = keycode[1] if text in self.keysPressed: self.keysPressed.remove(text)
class GameWidget(Widget): def __init__(self, **kwargs): super().__init__(**kwargs) #to use keyboard to play self._keyboard = Window.request_keyboard(self._on_keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_key_down) self._keyboard.bind(on_key_up=self._on_key_up) self._score_label = CoreLabel(text="Score: 0", font_size=20) #init score label self._score_label.refresh() #so can update score self._score = 0 #initial score self._life_label = CoreLabel(text="Life: 10", font_size=20) #init life lbel self._life_label.refresh() #so can update life self._life = 10 #initial life self.register_event_type("on_frame") with self.canvas: #my background Rectangle(source="assets/background.png", pos=(0, 0), size=(Window.width, Window.height)) #my score text on top left self._score_instruction = Rectangle( texture=self._score_label.texture, pos=(0, Window.height - 50), size=self._score_label.texture.size) #life text top left self._life_instruction = Rectangle( texture=self._life_label.texture, pos=(0, Window.height - 75), size=self._life_label.texture.size) self.keysPressed = set() self._entities = set() Clock.schedule_interval(self._on_frame, 0) self.sound = SoundLoader.load("assets/music.WAV") self.sound.play() Clock.schedule_interval(self.spawn_enemies, 1.5) #to spawn enemies every 1.5secs def spawn_enemies(self, dt): if self._score > -1 and self._score < 15: for i in range(self._score + int(2)): random_y = random.randint(10, Window.height - 100) x = Window.width random_speed = random.randint( 150, 400 ) #to spawn enemies with a random speed between 150 to 400 self.add_entity(Enemy((x, random_y), random_speed)) elif self._score > 14 and self._score < 100: for i in range(15): random_y = random.randint(10, Window.height - 100) x = Window.width random_speed = random.randint(350, 500) self.add_entity(Enemy((x, random_y), random_speed)) elif self._score > 99 and self._score < 200: for i in range(14): random_y = random.randint(10, Window.height - 100) x = Window.width random_speed = random.randint(450, 600) self.add_entity(Enemy((x, random_y), random_speed)) elif self._score > 199: for i in range(10): random_y = random.randint(10, Window.height - 100) x = Window.width random_speed = random.randint(650, 800) self.add_entity(Enemy((x, random_y), random_speed)) elif self._score < 0 and self._score > -50: for i in range(10): random_y = random.randint(10, Window.height - 100) x = Window.width random_speed = random.randint(800, 900) self.add_entity(Enemy((x, random_y), random_speed)) elif self._score < -49: for i in range(15): random_y = random.randint(10, Window.height - 100) x = Window.width random_speed = random.randint(800, 1000) self.add_entity(Enemy((x, random_y), random_speed)) def _on_frame(self, dt): self.dispatch("on_frame", dt) def on_frame(self, dt): pass @property def score(self): #score getter return self._score @score.setter def score(self, value): #score setter self._score = value #set private attribute of score self._score_label.text = "Score: " + str( value) #to add a value to 'score' self._score_label.refresh() #update label text self._score_instruction.texture = self._score_label.texture #update texture of instruction self._score_instruction.size = self._score_label.texture.size #update size of instruction @property def life(self): #life getter return self._life @life.setter def life(self, lifes): #life setter self._life = lifes #set private attribute of score self._life_label.text = "Life: " + str( lifes) #to add a value to 'score' self._life_label.refresh() #update label text self._life_instruction.texture = self._life_label.texture #update texture of instruction self._life_instruction.size = self._life_label.texture.size #update size of instruction def add_entity(self, entity): self._entities.add(entity) self.canvas.add(entity._instruction) def remove_entity(self, entity): if entity in self._entities: self._entities.remove(entity) self.canvas.remove(entity._instruction) def collides( self, e1, e2 ): #axis aligned bounding box collision pos,0 position is xvalue,1 position is yvalue r1x = e1.pos[0] r1y = e1.pos[1] r2x = e2.pos[0] r2y = e2.pos[1] r1w = e1.size[0] r1h = e1.size[1] r2w = e2.size[0] r2h = e2.size[1] if (r1x < r2x + r2w and r1x + r1w > r2x and r1y < r2y + r2h and r1y + r1h > r2y): return True else: return False def colliding_entities( self, entity ): #takes in an entity and see if it collides with our entity. result = set() #empty set for e in self._entities: if self.collides( e, entity ) and e != entity: #the entity we checking for will also be in entity list, so we must have !, to show not equal.if not will show self collision result.add(e) return result def _on_keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_key_down) self._keyboard.unbind(on_key_up=self._on_key_up) self._keyboard = None def _on_key_down(self, keyboard, keycode, text, modifiers): self.keysPressed.add(keycode[1]) def _on_key_up(self, keyboard, keycode): text = keycode[1] if text in self.keysPressed: self.keysPressed.remove(text)
class GameWidget(Widget): def __init__(self, **kwargs): super().__init__(**kwargs) Window.maximize() ''' Handling Keyboard Requests ''' # Widgets in Kivy don't normally respond to keyboard input # So we need to make it such that it requests so self._keyboard = Window.request_keyboard(self._on_keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_key_down) self._keyboard.bind(on_key_up=self._on_key_up) ''' Handling Scores ''' # Create a score core label that we can reference and render when we need self._score_label = CoreLabel(text="Score: 0", font_name="Halo3", font_size=50, bold=True, color=(1, 1, 0, 1)) self._score_label.refresh() self._score = 0 # value of score self.score_list = [0] ''' Handling Powerups ''' self._powerup_label = CoreLabel(text="", font_name="Halo3", font_size=50, bold=True, underline=True, color=(0, 1, 1, 1)) self._powerup_label.refresh() self.powerup_active = 0 # state of powerup ''' Handling Levels ''' self._level_label = CoreLabel(text="Level: 1", font_name="Halo3", font_size=50, bold=True, color=(1, 1, 0, 1)) self._level_label.refresh() self._level = 1 self.lvl_list = [1] ''' Handling Health ''' self._health_label = CoreLabel(text="Health: 3", font_name="Halo3", font_size=50, bold=True, color=(1, 0, 0, 1)) self._health_label.refresh() self._health = 3 ''' Global States''' self.pause_state = 0 self.game_state = 1 self.enemyInterval = 3 ''' Drawing Canvas ''' with self.canvas.before: # Add a background # Rectangle(source = "assets/bg.gif", pos = (0,0), size = (Window.width, Window.height)) Image(source="assets/Sequence.zip", pos=self.pos, center=self.center, size=(Window.width, Window.height), allow_stretch=True, anim_delay=0.01) # Rectangle(pos = (0,0), size = (Window.width, Window.height)) self._score_instruction = Rectangle( texture=self._score_label.texture, pos=(50, Window.height - 50), size=self._score_label.texture.size) self._powerup_instruction = Rectangle( texture=self._powerup_label.texture, pos=((Window.width / 2) - 250, Window.height - 100), size=self._powerup_label.texture.size) self._level_instruction = Rectangle( texture=self._level_label.texture, pos=(50, Window.height - 100), size=self._level_label.texture.size) self._health_instruction = Rectangle( texture=self._health_label.texture, pos=(50, Window.height - 150), size=self._health_label.texture.size) ''' Schedule/Register Essential Events ''' self.register_event_type("on_frame") Clock.schedule_interval(self._on_frame, 0) Clock.schedule_interval(self.spawn_enemies, 2) Clock.schedule_interval(self.spawn_pwrups, 5) Clock.schedule_interval(self.check_score, 0) if self.game_state == 1: Clock.schedule_interval(self.check_health, 0) ''' Manager Sets ''' # Keep track of the keys pressed in the set self.keysPressed self.keysPressed = set() self.scoreSet = set() # Keep track of the entities in the game self._entities = set() ''' Play Music ''' self.sound = SoundLoader.load('assets/bgmusic.wav') self.sound.loop = True self.sound.play() ''' Score property ''' @property #getter def score(self): return self._score @score.setter def score(self, value): self._score = value self._score_label.text = "Score: " + str(value) self._score_label.refresh() self._score_instruction.texture = self._score_label.texture self._score_instruction.size = self._score_label.texture.size ''' Power Up Property ''' def powerup_notification(self): self._powerup_label.text = "You got a power up!" self._powerup_label.refresh() self._powerup_instruction.texture = self._powerup_label.texture self._powerup_instruction.size = self._powerup_label.texture.size Clock.schedule_once(self.powerup_notification_off, 3) def powerup_notification_off(self, dt): self._powerup_label.text = "" self._powerup_label.refresh() self._powerup_instruction.texture = self._powerup_label.texture self._powerup_instruction.size = self._powerup_label.texture.size ''' Level Property ''' @property def level(self): return self._level @level.setter def level(self, value): self._level = value self._level_label.text = "Level: " + str(value) self._level_label.refresh() self._level_instruction.texture = self._level_label.texture self._level_instruction.size = self._level_label.texture.size ''' Health Property ''' @property def health(self): return self._health @health.setter #setter def health(self, value): self._health = value self._health_label.text = "Health: " + str(value) self._health_label.refresh() self._health_instruction.texture = self._health_label.texture self._health_instruction.size = self._health_label.texture.size ''' Keyboard Requests ''' # This function unbinds the keyboard and sets it to None def _on_keyboard_closed(self): # Unbind what we bound. Stop Listening to _on_key_down self._keyboard.unbind(on_key_down=self._on_key_down) self._keyboard = None # Because we've lost the key def _on_key_down(self, keyboard, keycode, text, modifiers): # We add this key into the set of keys pressed self.keysPressed.add(keycode[1]) def _on_key_up(self, keyboard, keycode): text = keycode[1] if text in self.keysPressed: self.keysPressed.remove(text) ''' Game Essential Functions ''' def refresh_game(self): game.pause_state = 1 game.game_state = 1 self.health = 3 self.score = 0 self.scoreSet.clear() game.powerup_active = 0 Clock.unschedule(game.powerup_toggle) self.level = 1 self.enemyInterval = 3 game.player.pos = (0, 400) #Clear remaining enemies for e in self._entities.copy(): if isinstance(e, Enemy) or isinstance(e, Bullet) or isinstance( e, Boss): self.remove_entity(e) return def check_health(self, dt): if game.health == 0 and game.game_state == 1: game.pause_state = 1 game.game_state = 0 self.game_end() return def game_end(self): hs = 'High Score: {}'.format(game.score) hl = 'Highest Level: {}'.format(game.level) # Take the score and level and add it global score and level list game.score_list.append(game.score) game.lvl_list.append(game.level) # Update the highscore in a separate func self.updateHighScoreLevel() for w in (list(ge.children)): ge.remove_widget(w) death_lbl = Label(text='Game Over', size_hint=(0.6, 0.2), pos_hint={ "x": 0.2, "top": 1 }, underline=True, bold=True) stats_lbl = Label(text='{:^20}\n{:^20}'.format(hs, hl), size_hint=(0.6, 0.2), pos_hint={ "x": 0.2, "top": 0.8 }) end_game = Button(text='Return to main menu', size_hint=(0.8, 0.2), pos_hint={ "x": 0.1, "y": 0.1 }) end_game.bind(on_release=ge.change_to_menu) # Need to refresh the end game screen each time ge.add_widget(death_lbl) ge.add_widget(stats_lbl) ge.add_widget(end_game) geWindow.open() return def updateHighScoreLevel(self): newHighScore = max(self.score_list) newHighLevel = max(self.lvl_list) hs.HSlbl.text = 'Your high score is: ' + str(newHighScore) hs.LVLlbl.text = 'Your highest level is: ' + str(newHighLevel) ''' Increasing Game Difficulty based on Score''' # Increased chance for more enemies to spawn def increaseDifficulty(self, dt): self.enemyInterval += 1 game.level += 1 return def check_score(self, dt): if (self.score % 5 == 0) and (self.score > 0) and (self.score not in game.scoreSet): game.scoreSet.add(self.score) Clock.schedule_once(game.increaseDifficulty) Clock.schedule_once(game.spawn_boss) return def spawn_enemies(self, dt): x = Window.width _enemyInterval = self.enemyInterval enemyInterval = random.randint(1, _enemyInterval) if sm.current == 'start' and game.pause_state == 0: for i in range(enemyInterval): # a random y coordinate random_y = random.randint(0, Window.height - 50) # Generate a random speed random_speed = random.randint(100, 300) self.add_entity(Enemy((x, random_y), random_speed)) def spawn_boss(self, dt): x = Window.width # Spawn a boss enemy every few scores if sm.current == 'start' and game.pause_state == 0: # a random y coordinate random_y = random.randint(0, Window.height - 200) # Generate a random speed random_speed = random.randint(100, 300) self.add_entity(Boss((x, random_y), random_speed)) def spawn_pwrups(self, dt): if sm.current == 'start' and game.pause_state == 0: random_x = random.randint(200, 1000) random_y = random.randint(200, 700) self.add_entity(PowerUps((random_x, random_y))) def powerup_toggle(self, dt): if game.powerup_active == 1: game.powerup_active = 0 elif game.powerup_active == 0: self.powerup_notification() game.powerup_active = 1 def pause_toggle(self, sender): if game.pause_state == 0: game.pause_state = 1 elif game.pause_state == 1: game.pause_state = 0 def _on_frame(self, dt): self.dispatch("on_frame", dt) def on_frame(self, dt): pass def add_entity(self, entity): self._entities.add(entity) self.canvas.add(entity._instruction) def remove_entity(self, entity): self._entities.remove(entity) self.canvas.remove(entity._instruction) def collides(self, e1, e2): r1x = e1.pos[0] r1y = e1.pos[1] r2x = e2.pos[0] r2y = e2.pos[1] r1w = e1.size[0] r1h = e1.size[1] r2w = e2.size[0] r2h = e2.size[1] if (r1x < r2x + r2w and r1x + r1w > r2x and r1y < r2y + r2h and r1y + r1h > r2y): return True else: return False # This function takes an entity and returns all entity thats colliding with it def colliding_entities(self, entity): ret_val = set() for e in self._entities: if self.collides(e, entity) and e != entity: ret_val.add(e) return ret_val
class Game(FloatLayout): def __init__(self): super().__init__() self.birdy = Bird() self.add_widget(self.birdy) self.birdy.size_hint = (50 / Window.size[0], 50 / Window.size[1]) self.birdy.pos_hint = {'x': 0.5, 'y': 0.5} self.birdy_windowpos = [ self.birdy.pos_hint['x'] * Window.size[0], self.birdy.pos_hint['y'] * Window.size[1] ] self.resetbtn = ResetBtn() self.add_widget(self.resetbtn) self.resetbtn.size_hint = (0.15, 0.06) self.resetbtn.pos_hint = {'x': 0.8, 'y': 0.90} self.walls = [] self.current_bottom_wall = None self.current_top_wall = None self.add_random_wall() self.score = 0 self.score_label = CoreLabel(text="Score:" + str(self.score), font_size=30, color=(1, 0.7, 0, 0.8)) self.score_label.refresh() with self.canvas: self.score_instruction = Rectangle( texture=self.score_label.texture, pos=(20, Window.size[1] - 50), size=self.score_label.texture.size) self.high_score = 0 self.birdy_update = Clock.schedule_interval(self.birdy.update, 0.03) self.wall_update = Clock.schedule_interval(self.update, 0) def add_bottom_wall(self, pos, size): with self.canvas: self.rect = Rectangle(source='Bottom wall.png', pos=pos, size=size) self.walls.append(self.rect) self.current_bottom_wall = self.rect def add_top_wall(self, pos, size): with self.canvas: self.rect = Rectangle(source='Top wall.png', pos=pos, size=size) self.walls.append(self.rect) self.current_top_wall = self.rect # Add wall at random height def add_random_wall(self): height = random.uniform(100, Window.size[1] - 300) self.add_bottom_wall((0.9 * Window.size[0], 0), (50, height)) self.add_top_wall((0.9 * Window.size[0], height + 200), (50, Window.size[1] - height - 200)) def game_speed(self): bds = 0 if self.score % 5 == 0: bds = bds + self.score / 5 else: bds = bds + self.score // 5 bs = bird_stateSM(bds) bs.start() return bs.step(self.score) # Run updates def update(self, dt): self.score_instruction.pos = (20, Window.size[1] - 50) self.birdy_windowpos = [ self.birdy.pos_hint['x'] * Window.size[0], self.birdy.pos_hint['y'] * Window.size[1] ] self.k = self.game_speed() + App.userspeed * 20 # move the wall for wall in self.walls: wall.pos = (wall.pos[0] - self.k * dt, wall.pos[1]) # Remove wall from the list after it leaves screen self.walls = [i for i in self.walls if i.pos[0] >= -50] #add new wall when wall pass 0.48 of the window if self.walls[-1].pos[0] <= 0.48 * Window.size[0]: self.add_random_wall() self.score += 1 self.new_score() self.gameover() def new_score(self): self.score_label.text = "Score: " + str(self.score) self.score_label.refresh() self.score_instruction.texture = self.score_label.texture self.score_instruction.size = self.score_label.texture.size def get_high_score(self): if self.high_score < self.score: self.high_score = self.score else: return self.high_score def gameover(self): #when bird within the width of wall if self.current_bottom_wall.pos[0] <= ( self.birdy_windowpos[0] + 25) and (self.birdy_windowpos[0] + 25) <= self.current_bottom_wall.pos[0] + 50: #i bird hit the bottom wall if (self.current_bottom_wall.pos[1] + self.current_bottom_wall.size[1]) > ( self.birdy_windowpos[1] + 8): self.get_high_score() self.label = Label(text="Game Over\n" + 'Score:' + str(self.score) + '\n' + 'High Score:' + str(self.high_score), halign='center', valign='center', font_size=60) self.add_widget(self.label) self.label.size_hint = (0.5, 0.2) self.label.pos_hint = {'x': 0.25, 'y': 0.5} self.canvas.remove(self.score_instruction) Clock.unschedule(self.birdy_update) Clock.unschedule(self.wall_update) # if bird hit top wall elif self.current_top_wall.pos[1] < (self.birdy_windowpos[1] + 60): self.get_high_score() self.label = Label(text="Game Over\n" + 'Score:' + str(self.score) + '\n' + 'High Score:' + str(self.high_score), halign='center', valign='center', font_size=60) self.add_widget(self.label) self.label.size_hint = (0.5, 0.2) self.label.pos_hint = {'x': 0.25, 'y': 0.5} self.canvas.remove(self.score_instruction) Clock.unschedule(self.birdy_update) Clock.unschedule(self.wall_update) # if bird out of zone elif self.birdy_windowpos[1] + 10 <= 0: self.get_high_score() self.label = Label(text="Game Over\n" + 'Score:' + str(self.score) + '\n' + 'High Score:' + str(self.high_score), halign='center', valign='center', font_size=60) self.add_widget(self.label) self.label.size_hint = (0.5, 0.2) self.label.pos_hint = {'x': 0.25, 'y': 0.5} self.canvas.remove(self.score_instruction) Clock.unschedule(self.birdy_update) Clock.unschedule(self.wall_update) elif self.birdy_windowpos[1] + 50 >= Window.size[1]: self.get_high_score() self.label = Label(text="Game Over\n" + 'Score:' + str(self.score) + '\n' + 'High Score:' + str(self.high_score), halign='center', valign='center', font_size=60) self.add_widget(self.label) self.label.size_hint = (0.5, 0.2) self.label.pos_hint = {'x': 0.25, 'y': 0.5} self.canvas.remove(self.score_instruction) Clock.unschedule(self.birdy_update) Clock.unschedule(self.wall_update) def reset(self): self.clear_widgets() for wall in self.walls: del wall del self.current_bottom_wall del self.current_top_wall self.canvas.clear() Clock.unschedule(self.birdy_update) Clock.unschedule(self.wall_update) self.birdy = Bird() self.add_widget(self.birdy) self.birdy.size_hint = (50 / Window.size[0], 50 / Window.size[1]) self.birdy.pos_hint = {'x': 0.5, 'y': 0.5} self.birdy_windowpos = [ self.birdy.pos_hint['x'] * Window.size[0], self.birdy.pos_hint['y'] * Window.size[1] ] self.resetbtn = ResetBtn() self.add_widget(self.resetbtn) self.resetbtn.size_hint = (0.15, 0.06) self.resetbtn.pos_hint = {'x': 0.8, 'y': 0.90} self.walls = [] self.current_bottom_wall = None self.current_top_wall = None self.add_random_wall() self.score = 0 self.score_label = CoreLabel(text="Score:" + str(self.score), font_size=30, color=(1, 0.7, 0, 0.8)) self.score_label.refresh() with self.canvas: self.score_instruction = Rectangle( texture=self.score_label.texture, pos=(20, Window.size[1] - 50), size=self.score_label.texture.size) self.birdy_update = Clock.schedule_interval(self.birdy.update, 0.03) self.wall_update = Clock.schedule_interval(self.update, 0)
class GameWidget(Widget): def __init__(self, **kwargs): super().__init__(**kwargs) self._keyboard = Window.request_keyboard(self._on_keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_key_down) self._keyboard.bind(on_key_up=self._on_key_up) self._goldLabel = CoreLabel(text="Gold: " + str(money), font_size=15) self._goldLabel.refresh() self._gold = money self._tHealthLabel = CoreLabel(text="Health: 100", font_size=20) self._tHealthLabel.refresh() self._tHealth = 100 self._pHealth = 10 self.register_event_type( "on_frame") # This is from the super thing that we are inheriting with self.canvas.before: Rectangle(source=bg_img, pos=(0, 0), size=(Window.width, Window.height)) self._gold_instruction = Rectangle( texture=self._goldLabel.texture, pos=(0, Window.height - 100), size=self._goldLabel.texture.size) self._tHealth_instruction = Rectangle( texture=self._tHealthLabel.texture, pos=(Window.width / 2 - (130 / 2) + 10, 260), size=self._tHealthLabel.texture.size) with self.canvas.after: Rectangle(source="images/Shop.png", pos=(0, Window.height - 75), size=(100, 50)) btn1 = Button(text="Shop", pos=(0, Window.height - 90), background_color=(0, 0, 0, 0)) btn1.bind(on_press=show_popup) self.add_widget(btn1) btn_save = Button(text="Save", pos=((Window.width - self.size[0]), Window.height - self.size[1])) btn_save.bind(on_press=save) self.add_widget(btn_save) self.keysPressed = set() self._entities = set() Clock.schedule_interval(self._on_frame, 0) self.sound = SoundLoader.load("Music\Ominous Music.mp3") self.sound.play() Clock.schedule_interval(self.spawn_enemies, 2) self.last_time_a = 0 self.last_time_w = 0 Clock.schedule_interval(self.check_time, 0.1) def check_time(self, dt): global original_a global original_w global pause if pause == 1: if time.time() - self.last_time_a >= 1: if assassin_lives == 1 and original_a: self.add_entity(AssassinLT( (((Window.width / 2) - 200), 0))) self.last_time_a = time.time() if time.time() - self.last_time_w >= 3: if wizard_lives == 1: self.add_entity(fireball(((Window.width / 2) + 190, 5))) self.last_time_w = time.time() def spawn_enemies(self, dt): global pause if pause == 1: for i in range(2): random_spd = random.randint(25, 50) self.add_entity(EnemyLT((Window.width, 0), random_spd)) self.add_entity(EnemyRT((0, 0), random_spd)) def _on_frame(self, dt): self.dispatch("on_frame", dt) def on_frame(self, dt): pass @property def gold(self): # Score getter return self._gold @gold.setter def gold(self, value): # Score setter self._gold = value self._goldLabel.text = "Gold: " + str(value) self._goldLabel.refresh() self._gold_instruction.texture = self._goldLabel.texture self._gold_instruction.size = self._goldLabel.size @property def tHealth(self): # Score getter return self._tHealth @tHealth.setter def tHealth(self, value): # Score setter self._tHealth = value self._tHealthLabel.text = "Health: " + str(value) self._tHealthLabel.refresh() self._tHealth_instruction.texture = self._tHealthLabel.texture self._tHealth_instruction.size = self._tHealthLabel.size def set_wizard(self): rect1 = Rectangle(pos=(((Window.width / 2) + 150), 0), size=(50, 50), source='images/wizard frames/tile023.png') self.add_entity(WizardRT((((Window.width / 2) + 150), 0))) self.canvas.add(rect1) def set_assassin(self): rect2 = Rectangle(pos=(((Window.width / 2) - 200), 0), size=(50, 50), source='images/Bad guy frames/tile015.png') self.add_entity(AssassinLT((((Window.width / 2) - 200), 0))) self.canvas.add(rect2) def buy(self): global money global weapon global person global weap_rt global weap_lt global weap_size global durability if weapon == 1 and self._gold >= 10: global durability weapon = 0 game.gold -= 10 money -= 10 durability = 2 weap_rt = 'images/swordB_RT.png' weap_lt = 'images/swordB_LT.png' weap_size[0] = 30 weap_size[1] = 30 if person == 1 and self._gold >= 100: person = 0 game.gold -= 100 money -= 100 #rect1 = Rectangle(pos=(((Window.width / 2) + 150), 0), size=(50, 50), source='images/wizard frames/tile023.png') self.add_entity(WizardRT((((Window.width / 2) + 150), 0))) #self.canvas.add(rect1) if person == 2 and self._gold >= 100: person = 0 game.gold -= 100 money -= 100 rect2 = Rectangle(pos=(((Window.width / 2) - 200), 0), size=(50, 50), source='images/Bad guy frames/tile015.png') self.add_entity(AssassinLT((((Window.width / 2) - 200), 0))) self.canvas.add(rect2) def add_entity(self, entity): self._entities.add(entity) self.canvas.add(entity._instruction) def remove_entity(self, entity): if entity in self._entities: self._entities.remove(entity) self.canvas.remove(entity._instruction) def collides( self, e1, e2, value ): # Gets two tuples of rectangles position and returns a boolean if they collide. r1x = e1.pos[0] + value r1y = e1.pos[1] r2x = e2.pos[0] r2y = e2.pos[1] r1w = e1.size[0] + value r1h = e1.size[1] r2w = e2.size[0] r2h = e2.size[1] if ( r1x < r2x + r2w and r1x + r1w > r2x and r1y < r2y + r2h and r1y + r1h > r2y ): # The bottom left has the position then the height adds to the value to see if the bottom left of the second picture is collding. return True else: return False def colliding_entities(self, entity, dir): result = set() for e in self._entities: if self.collides( e, entity, dir ) and e != entity: # e == entry checks if the entity is colliding with itself. result.add(e) return result def _on_keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_key_down) self._keyboard.unbind(on_key_up=self._on_key_up) self.keyboard = None def _on_key_down(self, keyboard, keycode, text, modifiers): self.keysPressed.add(keycode[1]) def _on_key_up(self, keyboard, keycode): text = keycode[1] if text in self.keysPressed: self.keysPressed.remove(text)
class CombatScreen(Screen): """The screen that the user flies around shooting enemies.""" player = ObjectProperty(None) hostile = ObjectProperty(None) shiptype = StringProperty(None) updater = None #lives = NumericProperty(None) new_round = True objects = [] shells = [] asteroids = ListProperty() explosions = ListProperty() hostile_odd_move = True random_select_action = None def __init__(self, **kwargs): super().__init__(**kwargs) self.keyboard = Window.request_keyboard(self.on_keyboard_closed, self) self.keyboard.bind(on_key_down=self.on_key_down) self.keyboard.bind(on_key_up=self.on_key_up) self.score = 0 self.score_label = CoreLabel(text=str("Score: " + str(self.score))) self.score_label.refresh() self.level = 1 # Create a set of pressed keys for the given moment self.keysPressed = set() def on_pre_enter(self): """Perform tasks to ready the scene right before it is switched to.""" Logger.info('Application: Changed to the Combat screen.') Logger.info('Application: ' 'The ship chosen for combat is the ' '"{}" type.'.format(self.player.type)) Logger.info('Application: Stats: {}.'.format(self.player.stats)) self.start_soundtrack() # Set the event interval of every frame self.updater = Clock.schedule_interval(self.update, 1.0 / 60.0) # Populate round/level objects and collidable lists self.collidables = [] self.spaceships = [] # Sets the combat stage/hostiles based on players level self.set_level_hostiles() for asteroid in self.asteroids: self.collidables.append(asteroid) for ship in self.spaceships: self.collidables.append(ship) def on_pre_leave(self): """Perform clean up right before the scene is switched from.""" Logger.info('Application: Leaving the Combat screen.') self.updater.cancel() # Clear the event interval. self.stop_soundtrack() def on_keyboard_closed(self): """Act on the keyboard closing.""" self.keyboard.unbind(on_key_down=self.on_key_down) self.keyboard.unbind(on_key_up=self.on_key_up) self.keyboard = None def on_key_down(self, keyboard, keycode, text, modifiers): """Act on a key being pressed down.""" Logger.debug('KeyDown Event: Keycode[1] is "{}"'.format(keycode[1])) self.keysPressed.add(keycode[1]) def on_key_up(self, keyboard, keycode): """Act on a key being released up.""" Logger.debug('KeyUp Event: Keycode[1] is "{}"'.format(keycode[1])) self.keysPressed.remove(keycode[1]) def set_level_hostiles(self): if self.level == 1: self.init_players() self.init_hostiles(4) for i in range(4): self.generate_asteroid() elif self.level == 2: self.init_players() self.init_hostiles(4) for i in range(6): self.generate_asteroid() elif self.level == 3: self.init_players() self.init_hostiles(4) for i in range(9): self.generate_asteroid() def accelerate_hero(self, unit, physics=physics): """Calculate the acceleration changes based on the key pressed.""" minspeed = 0 rotation = 0 speed = self.player.speed topspeed = self.player.stat('speed') # Acceleration and turning are configs that modify movement overall. acceleration = physics.get('acceleration', 0.25) turning = physics.get('turning', 25) # Make rotation dependent on speed. angle_delta = turning * unit * topspeed # Make acceleration dependent on speed. speed_delta = acceleration * unit * topspeed if "w" in self.keysPressed: if speed < topspeed: speed = min(topspeed, speed + speed_delta) if "s" in self.keysPressed: if speed > minspeed: speed = max(minspeed, speed - speed_delta) if "a" in self.keysPressed: rotation += angle_delta if "d" in self.keysPressed: rotation -= angle_delta if "spacebar" in self.keysPressed: self.player.fire() self.player.angle += rotation self.player.speed = speed def accelerate_hostile(self, unit, physics=physics): """Calculate the acceleration changes based on the key pressed.""" minspeed = 0 rotation = 0 speed = self.hostile.speed topspeed = self.hostile.stat('speed') # Acceleration and turning are configs that modify movement overall. acceleration = physics.get('acceleration', 0.25) turning = physics.get('turning', 25) # Make rotation dependent on speed. angle_delta = turning * unit * topspeed # Make acceleration dependent on speed. speed_delta = acceleration * unit * topspeed if self.hostile.destroyed == False: random_select_action = randint(1, 100) if random_select_action < 20: rotation += angle_delta elif random_select_action < 40: rotation -= angle_delta elif random_select_action < 80: if speed < topspeed: speed = min(topspeed, speed + speed_delta) elif random_select_action < 90: if speed > minspeed: speed = max(minspeed, speed - speed_delta) if random_select_action == 20: self.hostile.fire() self.hostile.angle += rotation self.hostile.speed = speed def update(self, dt): """Step the scene forward.""" # First, step time forward. self.player.lastfired += dt self.hostile.lastfired += dt self.accelerate_hero(dt) if self.hostile in self.collidables: self.accelerate_hostile(dt) # Next, move the objects around the screen self.player.move(windowsize=Window.size) self.hostile.move(windowsize=Window.size) for asteroid in self.asteroids: asteroid.move(windowsize=Window.size) for shell in self.player.shells: shell.move(windowsize=Window.size) if shell.offscreen: self.player.shells.remove(shell) self.remove_widget(shell) for shell in self.hostile.shells: shell.move(windowsize=Window.size) if shell.offscreen: self.hostile.shells.remove(shell) self.remove_widget(shell) # Finally, check for any collisions self.detect_collisions(dt) def new_remove_widget(self, widget_object, dt): # removes widget from the GameView FloatLayout self.ids.GameView.remove_widget(widget_object) def detect_collisions(self, dt): # Creates list of current active shots/shells all_shells = [] for shell in self.player.shells: all_shells.append(shell) for shell in self.hostile.shells: all_shells.append(shell) # loops through all non-shell objects looking for collisions for object in self.collidables: if object.destroyed == True: pass else: for other_object in self.collidables: if other_object.destroyed: pass else: # ignore self to self matches if object != other_object: if object.collide_widget(other_object): Logger.info('Collision Detection: ' '{} and {} collided.'.format( object, other_object)) # Checks if players died if self.player == object or other_object == self.player: self.explosion(object, other_object, dt) # self.my_popup() else: # if non-player collision self.explosion(object, other_object, dt) # Loops through current active shells checking for collisions for shell in all_shells: if object.collide_widget(shell): # BugFix: Ignores any item on collide list marked as destroyed if object.destroyed == True: pass # ignores self friendly fire for player shells elif object == self.player and shell.origin == "player": pass # ignores self friendly fire for hostile shells elif object == self.hostile and shell.origin == "hostile": pass # Triggers round end notification if player collides elif object == self.player or other_object == self.player: self.explosion(object, other_object, dt) self.player_killed_popup() # Adds points if player shoots something elif shell.origin == "player": self.explosion(object, other_object, dt) self.score += 1 self.score_label.text = str("Score: " + str(self.score)) self.score_label.refresh() # Removes object that collides with shells else: self.explosion(object, other_object, dt) def explosion(self, obj1, obj2, dt): print("Explosion between %s and %s" % (obj1, obj2)) print("----------------Collidable List on Impact: ", self.collidables) Logger.info('Explode: "{}" and "{}" have collided: '.format( obj1, obj2)) try: self.collidables.remove(obj1) except: pass try: self.collidables.remove(obj2) except: pass print("+++++++++++++++Collidable List AFTER Impact", self.collidables) try: obj1.destroyed = True except: pass try: obj2.destroyed = True except: pass SoundManager.play_sfx(obj1.states['exploded']['sfx']) SoundManager.play_sfx(obj2.states['exploded']['sfx']) try: SoundManager.remove_sfx(obj1.states['exploded']['sfx'], obj1) except: pass try: SoundManager.remove_sfx(obj2.states['exploded']['sfx'], obj2) except: pass obj1.skin = obj1.states['exploded']['skin'] obj2.skin = obj2.states['exploded']['skin'] Clock.schedule_once(partial(self.new_remove_widget, obj1), .3) Clock.schedule_once(partial(self.new_remove_widget, obj2), .3) def player_killed_popup(self): """ The popup that appears upon player death """ # creates/formats popup content content = BoxLayout(orientation='vertical') image = Image(source="deadscreen.png", size_hint=(1, 1)) btn1 = Button(text='Exit', size_hint=(1, .2)) content.add_widget(image) content.add_widget(btn1) # creates popup from content popup = Popup(title='You Crashed', title_align="center", content=content, size_hint=(.6, .6)) # binds button to pop-up window close btn1.bind(on_press=popup.dismiss) # Opens popup popup.open() def generate_asteroid(self): positions = [] while len(positions) < 10: location = (randint(1, Window.width), randint(1, Window.height)) if abs(self.player.pos[0] - location[0]) < 100: pass elif abs(self.player.pos[1] - location[1]) < 100: pass else: positions.append(location) position = choice(positions) asteroid = AsteroidObstacle() asteroid.randomize_trajectory() asteroid.pos = position SoundManager.add_sfx(asteroid.states['exploded']['sfx'], asteroid) self.ids.GameView.add_widget(asteroid) # self.add_widget(asteroid) self.asteroids.append(asteroid) return asteroid def init_players(self): """Prepare the player ships.""" self.spaceships.append(self.player) SoundManager.add_sfx(self.player.states['exploded']['sfx'], self.player) def init_hostiles(self, number): """Prepare the level's hostiles.""" for i in range(number): self.spaceships.append(self.hostile) SoundManager.add_sfx(self.hostile.states['exploded']['sfx'], self.hostile) def start_soundtrack(self): """Choose and play music for the combat scene.""" sources = screens['Combat']['music'] self.source = choice(sources) Logger.info('Application: Chose "{}" as the combat music.'.format( self.source)) try: SoundManager.music[self.source] except KeyError: SoundManager.add_music(self.source, self) SoundManager.play_music(self.source) def stop_soundtrack(self): """Stop the combat scene music.""" SoundManager.remove_music(self.source, self)
def modify_text(self, label, new_text): text_label = CoreLabel(text=new_text, font_size=20) text_label.refresh() label.texture = text_label.texture
class Actions(GameSetup): def __init__(self, **kwargs): super().__init__(**kwargs) self.sound = SoundLoader.load('start.mp3') self.sound.volume = 0.1 self.sound.play() Clock.schedule_interval(self._player1_, 0) Clock.schedule_interval(self._player2_, 0) self._player1score_label = CoreLabel(text="Player 1 score: 0", font_size=40) self._player1score_label.refresh() self._player1score = 0 self._player2score_label = CoreLabel(text="Player 2 score: 0", font_size=40) self._player2score_label.refresh() self._player2score = 0 with self.canvas: Color(1, 0, .3) self._player1score_instruction = Rectangle( texture=self._player1score_label.texture, pos=(100, 750), size=self._player1score_label.texture.size) Color(0, 1, .6) self._player2score_instruction = Rectangle( texture=self._player2score_label.texture, pos=(1100, 750), size=self._player2score_label.texture.size) @property def player1_score(self): return self._player1score @player1_score.setter def player1_score(self, value): self._player1score = value self._player1score_label.text = f"Player 1 score: {self._player1score}" self._player1score_label.refresh() self._player1score_instruction.texture = self._player1score_label.texture self._player1score_instruction.size = self._player1score_label.texture.size @property def player2_score(self): return self._player2score @player2_score.setter def player2_score(self, value): self._player2score = value self._player2score_label.text = f"Player 2 score: {self._player2score}" self._player2score_label.refresh() self._player2score_instruction.texture = self._player2score_label.texture self._player2score_instruction.size = self._player2score_label.texture.size def _player1_(self, dt): """ :param dt:delta-time, time since last frame :return: player position """ player1xsize = self.player1.size[0] player1ysize = self.player1.size[1] player1xpos = self.player1.pos[0] player1ypos = self.player1.pos[1] step_size = 100 * dt if 'w' in self.keysPressed: player1ypos += step_size if 's' in self.keysPressed: player1ypos -= step_size if 'a' in self.keysPressed: player1xpos -= step_size if 'd' in self.keysPressed: player1xpos += step_size if 'a' in self.keysPressed and 'spacebar' in self.keysPressed: player1xpos -= step_size * 5 if 'w' in self.keysPressed and 'spacebar' in self.keysPressed: player1ypos += step_size * 5 if 's' in self.keysPressed and 'spacebar' in self.keysPressed: player1ypos -= step_size * 5 if 'd' in self.keysPressed and 'spacebar' in self.keysPressed: player1xpos += step_size * 5 self.player1.pos = (player1xpos, player1ypos) if player1xpos <= -.5 * player1xsize or player1xpos >= Window.width - 0.5 * player1xsize or \ player1ypos <= -.5 * player1ysize or player1ypos >= Window.height - 0.5 * player1ysize: popup = Popup(content=Label(text='Player 1 get back in the box!'), size_hint=(None, None), size=(300, 300), auto_dismiss=False) popup.open() popup.dismiss() self.player1_score -= 2 return self.player1.pos def _player2_(self, dt): """ :param dt:delta-time, time since last frame :return: enemy position """ player2xsize = self.player2.size[0] player2ysize = self.player2.size[1] player2xpos = self.player2.pos[0] player2ypos = self.player2.pos[1] step_size = 1000 * dt if 'up' in self.keysPressed: player2ypos += step_size if 'down' in self.keysPressed: player2ypos -= step_size if 'left' in self.keysPressed: player2xpos -= step_size if 'right' in self.keysPressed: player2xpos += step_size self.player2.pos = (player2xpos, player2ypos) if player2xpos <= -.5 * player2xsize or player2xpos >= Window.width - 0.5 * player2xsize or \ player2ypos <= -.5 * player2ysize or player2ypos >= Window.height - 0.5 * player2ysize: popup = Popup(content=Label(text='Player 2 get back in the box!'), size_hint=(None, None), size=(300, 300), auto_dismiss=False) popup.open() popup.dismiss() self.player2_score -= 4 if self.catch((self.player1.pos, self.player1.size), (self.player2.pos, self.player2.size)): self.player1_score += 1.5 self.player2_score -= 1 else: self.player2_score += 0.5 return self.player2.pos
class GameWidget(Widget): drop, lose = (False, False) tower = [Block(230, 0)] next_block = Block(230, 520) score = 0 speed = 1.0 def __init__(self, **kwargs): Widget.__init__(self, **kwargs) # create keyboard self.keyboard = Window.request_keyboard(self.keyboard_closed, self) self.keyboard.bind(on_key_down=self.on_keyboard_down) # custom events self.register_event_type('on_land') self.bind(on_land=self.check_landing) # canvas core labels self.lose_label = CoreLabel(text='', font_size=40) self.lose_label.refresh() self.lose_instruction = Rectangle(texture=self.lose_label.texture, pos=(85, 430), size=self.lose_label.texture.size) self.aim_label = CoreLabel(text='', font_size=20) self.aim_label.refresh() self.aim_instruction = Rectangle(texture=self.aim_label.texture, pos=(415, 300), size=self.aim_label.texture.size) self.score_label = CoreLabel(text='Score: 0', font_size=20) self.score_label.refresh() self.score_instruction = Rectangle(texture=self.score_label.texture, pos=(400, 530), size=self.score_label.texture.size) self.speed_label = CoreLabel(text='Speed: 1.0', font_size=20) self.speed_label.refresh() self.speed_instruction = Rectangle(texture=self.speed_label.texture, pos=(400, 485), size=self.speed_label.texture.size) self.canvas.add(self.lose_instruction) self.canvas.add(self.score_instruction) self.canvas.add(self.aim_instruction) self.canvas.add(self.speed_instruction) # graphics line_instruction = InstructionGroup() line_instruction.add(Color(1, 1, 1, 1)) line_instruction.add(Line(points=[0, 518, 500, 518], width=2)) self.canvas.add(line_instruction) self.canvas.add(self.next_block.instruction) # run these functions continuously Clock.schedule_interval(self.move_tower, 0.02) Clock.schedule_interval(self.move_block, 0.04) Clock.schedule_interval(self.drop_block, 0) Clock.schedule_interval(self.check_tower, 0) def move_tower(self, dt): ''' Oscillates the towers based on the step size from move_towerSM. ''' step_size = move_towerSM.step() for towerblock in self.tower: self.canvas.remove(towerblock.instruction) towerblock.x += step_size towerblock.shape.pos = (towerblock.x, towerblock.y) towerblock.instruction.add(towerblock.shape) self.canvas.add(towerblock.instruction) def move_block(self, dt): ''' Oscillates the building block based on the step size from move_blockSM. ''' if self.drop == False: step_size = move_blockSM.step() self.canvas.remove(self.next_block.instruction) self.next_block.x += step_size self.next_block.shape.pos = (self.next_block.x, self.next_block.y) self.next_block.instruction.add(self.next_block.shape) self.canvas.add(self.next_block.instruction) def check_tower(self, dt): ''' Removes the bottommost block if tower is more than 4 blocks tall. ''' if len(self.tower) == 5: self.canvas.remove(self.tower[0].instruction) self.tower.pop(0) # shift remaining blocks down for towerblock in self.tower: towerblock.y -= towerblock.size[1] def drop_block(self, dt): ''' Drops the building block was the SPACEBAR is pressed. ''' if self.drop == False: return current_y = self.next_block.y top_towerblock = len(self.tower) - 1 top_towerblock_y = self.tower[top_towerblock].y height = self.tower[top_towerblock].size[1] if current_y > top_towerblock_y + height: # change y coordinate and redraw self.canvas.remove(self.next_block.instruction) self.next_block.y -= 450 * dt self.next_block.shape.pos = (self.next_block.x, self.next_block.y) self.next_block.instruction.add(self.next_block.shape) self.canvas.add(self.next_block.instruction) if current_y <= top_towerblock_y + height: # stop dropping self.next_block.y = top_towerblock_y + height self.drop = False self.dispatch('on_land', dt) def check_landing(self, value, dt): ''' Checks the accuracy of the landing. Update score, speed and labels accordingly. ''' top_block = len(self.tower) - 1 top_x = self.tower[top_block].x top_y = self.tower[top_block].y width = self.tower[top_block].size[0] height = self.tower[top_block].size[1] # failed landing if self.next_block.x < top_x - width or self.next_block.x > top_x + width: self.lose = True self.update_labels('lose') # successful landing else: self.score += 1 # bad landing if self.next_block.x < top_x - 0.5 * width or self.next_block.x > top_x + 0.5 * width: self.update_labels('Bad..') if move_towerSM.coeff <= 14: move_towerSM.coeff *= 1.2 move_blockSM.coeff *= 1.2 self.speed += 0.2 # good landing elif self.next_block.x < top_x - 0.1 * width or self.next_block.x > top_x + 0.1 * width: self.update_labels('Good') if move_towerSM.coeff <= 14: move_towerSM.coeff *= 1.1 move_blockSM.coeff *= 1.1 self.speed += 0.1 # great landing else: self.update_labels('Great!') if move_towerSM.coeff > 2: self.speed -= 0.1 move_towerSM.coeff *= 0.9 move_blockSM.coeff *= 0.9 # append next_block to self.tower self.tower.append(self.next_block) # update labels, draw new building block self.update_speed() self.update_score() self.draw_new_block() def update_labels(self, result): ''' Updates aim and lose label. ''' if result == 'lose': self.aim_label.text = '' self.lose_label.text = "OH NO! YOU LOST!" self.lose_label.refresh() self.lose_instruction.texture = self.lose_label.texture self.lose_instruction.size = self.lose_label.texture.size elif result == 'restart': self.aim_label.text = '' self.lose_label.text = '' self.lose_label.refresh() self.lose_instruction.texture = self.lose_label.texture self.lose_instruction.size = self.lose_label.texture.size else: self.aim_label.text = result self.aim_label.refresh() self.aim_instruction.texture = self.aim_label.texture self.aim_instruction.size = self.aim_label.texture.size def update_speed(self): ''' Updates speed label. ''' self.speed_label.text = "Speed: " + str(round(self.speed, 1)) self.speed_label.refresh() self.speed_instruction.texture = self.speed_label.texture self.speed_instruction.size = self.speed_label.texture.size def update_score(self): ''' Updates score label. ''' self.score_label.text = "Score: " + str(self.score) self.score_label.refresh() self.score_instruction.texture = self.score_label.texture self.score_instruction.size = self.score_label.texture.size def draw_new_block(self): ''' Creates a new Block object at the starting position. ''' move_blockSM.start() self.next_block = Block(230, 520) self.canvas.add(self.next_block.instruction) def restart(self): ''' Reset tower and building blocks, SM, class variables and labels. ''' for towerblock in self.tower: self.canvas.remove(towerblock.instruction) self.tower = [Block(230, 0)] self.canvas.remove(self.next_block.instruction) self.next_block = Block(230, 520) move_blockSM.start() move_towerSM.start() move_blockSM.coeff = 4 move_towerSM.coeff = 2 # reset labels self.score = 0 self.speed = 1.0 self.update_score() self.update_speed() self.update_labels('restart') self.drop, self.lose = (False, False) def on_land(self, dt): ''' Default handler for the custom event 'on_land'. ''' pass def keyboard_closed(self): pass def on_keyboard_down(self, keyboard, keycode, text, modifiers): ''' Listens for SPACE BAR key down to trigger self.drop_block(). ''' if self.manager.current == 'play': if keycode[1] == 'spacebar' and self.lose == False: self.drop = True
def createTickets(self, parts, font_color, border_color): # Шрифт LabelBase.register(name='CG', fn_regular=paths['font']) with self.canvas: Color(0, 0, 0, 1) #black # Базовые размеры w = 595 h = 842 # Отступ margin = 28 marginY = 369 # Промежуток middleX = 9 middleY = 65 # Размеры билета ticketX = 567 ticketY = 369 # Размеры ячейки cell = 128 # Фон Color(1, 1, 1, 1) #white self.canvas.add(Rectangle(size=[w, h], pos=[0, 0])) # Изображение imageX = 111 imageY = 45 # Билеты tickets = [None] * int(len(parts) / 8) for i in range(len(tickets)): tickets[i] = [None] * 8 num = 0 for i in range(len(parts)): if (num / 8 == 1): num = 0 tickets[int(i / 8)][num] = parts[i] num += 1 # trigger запускает отрисовку второго билета на листе trigger = 0 for i in range(len(tickets)): Color(0, 0, 0, 1) #black self.canvas.add( Line(rectangle=(0, marginY * trigger, w, ticketY), width=1)) for num in range(len(tickets[i])): # Ряд в билете j = 1 j += int(num / 4) # Формирование содержимого ячейки name = CoreLabel(font_name='CG', text=str(tickets[i][num]), font_size=45) name.refresh() name = name.texture Color(rgba=border_color) self.canvas.add( Line(rectangle=(margin + (cell + middleX) * (num - (j - 1) * 4), margin + (cell + middleY) * (j - 1) + marginY * trigger, cell, cell), width=3)) Color(rgba=font_color) self.canvas.add( Rectangle(size=name.size, pos=(margin + (cell + middleX) * (num - (j - 1) * 4) + cell / 2 - name.size[0] / 2, margin + (cell + middleY) * (j - 1) + cell / 2 - name.size[1] / 2 + marginY * trigger), texture=name)) # Добавление логотипов на билет self.canvas.add( Rectangle(source=paths['logo'], size=(imageX, imageY), pos=(ticketX / 3 - imageX / 2, margin + cell + middleY / 2 - imageY / 2 + marginY * trigger))) self.canvas.add( Rectangle(source=paths['logo'], size=(imageX, imageY), pos=((ticketX / 3) * 2 - imageX / 2, margin + cell + middleY / 2 - imageY / 2 + marginY * trigger))) trigger = 1
def gen_texture(text: str, font_size: int): num_label = CoreLabel(text=text, font_size=font_size) num_label.refresh() return num_label.texture
class GameWidget(Widget): space_texture = ObjectProperty(None) def __init__(self, **kwargs): super().__init__(**kwargs) # Request reference to keyboard self._keyboard = Window.request_keyboard(self._on_keyboard_close, self) self._keyboard.bind(on_key_down=self._on_key_down) self._keyboard.bind(on_key_up=self._on_key_up) self._score_label = CoreLabel(text="Score: 0", font_size=20) self._score_label.refresh() self._score = 0 self.register_event_type("on_frame") # Inherited from super class # Create textures self.space_texture = Image(source="assets/background.png").texture self.space_texture.wrap = "repeat" self.space_texture.uvsize = (Window.height / self.space_texture.height, -1) with self.canvas: Rectangle(texture=self.space_texture, pos=(0, 0), size=(Window.width, Window.height)) self._score_instruction = Rectangle( texture=self._score_label.texture, pos=(10, Window.height - 50), size=self._score_label.texture.size) self._keys_pressed = set() self._entities = set() # Spawn enemies Clock.schedule_interval(self.spawn_enemies, 1) # Execute move every frame Clock.schedule_interval(self._on_frame, 0) def spawn_enemies(self, dt): x = random.randint(0, Window.width - 50) y = Window.height speed = random.randint(100, 200) self.add_entity(Enemy((x, y), speed)) def _on_frame(self, dt): self.dispatch("on_frame", dt) def on_frame(self, dt): pass @property def score(self): return self._score @score.setter def score(self, value): self._score = value self._score_label.text = "Score: " + str(value) self._score_label.refresh() self._score_instruction.texture = self._score_label.texture self._score_instruction.size = self._score_label.texture.size def add_entity(self, entity): self._entities.add(entity) self.canvas.add(entity._instruction) def remove_entity(self, entity): if entity in self._entities: self._entities.remove(entity) self.canvas.remove(entity._instruction) # Takes two entities as input and returns true if they are colliding def collides(self, e1, e2): r1_x = e1.pos[0] r1_y = e1.pos[1] r1_h = e1.size[0] r1_w = e1.size[1] r2_x = e2.pos[0] r2_y = e2.pos[1] r2_h = e2.size[0] r2_w = e2.size[1] if (r1_x < r2_x + r2_w and r1_x + r1_w > r2_x and r1_y < r2_y + r2_h and r1_y + r1_h > r2_y): return True else: return False # Returns a set of entities that the given entity collides with def colliding_entities(self, entity): result = set() for e in self._entities: if self.collides(e, entity) and e != entity: result.add(e) return result def reset(self): for e in game._entities.copy(): e.stop_callbacks() game.remove_entity(e) game.score = 0 game.player = Player() game.add_entity(game.player) # Unbind from keyboard def _on_keyboard_close(self): self._keyboard.unbind(on_key_down=self._on_key_down) self._keyboard.unbind(on_key_up=self._on_key_up) self._keyboard = None def _on_key_down(self, keyboard, keycode, text, modifiers): self._keys_pressed.add(keycode[1]) def _on_key_up(self, keyboard, keycode): text = keycode[1] if text in self._keys_pressed: self._keys_pressed.remove(text)