def __init__(self, name, classType="Player", image="", attackSound="", specialSound=""): super(Player, self).__init__(image=games.load_image(image), x=150, y=350, dx=0, dy=0) self.name = name.title() self.status = "Alive" self.health = randint(20, 45) self.money = 0 self.type = classType # Sounds self.attackSound = games.load_sound(attackSound) self.specialSound = games.load_sound(specialSound) self.deathSound = games.load_sound("sounds/death.wav") self.alive = True self.moving = False self.attacking = False self.attackDelay = 0 # Sprite to show damage was inflicted self.damageSprite = games.Sprite(image=games.load_image("sprites/damage.png"), x=self.x, y=self.y) self.damageSpriteCounter = -1 # label for health info self.lblHP = games.Text(value="HP: " + str(self.health), size=30, x=self.x, y=self.top - 20, color=color.white) games.screen.add(self.lblHP)
def __init__(self, name="", image="", attackSound="", specialSound="", xPos=450, yPos=250, dX=0, dY=1): # Initialize Sprite super(Monster, self).__init__(image=games.load_image(image), x=xPos, y=yPos, dx=dX, dy=dY) # General Variables self.name = name.title() self.health = randint(20, 53) self.money = dice.roll(20) # Roll d20 for amount of coins owned self.alive = True self.moving = False # Attack Variables self.attacking = False self.attackDelay = 0 self.attackBonus = 0 self.defenseBonus = 10 # Sounds self.attackSound = games.load_sound(attackSound) self.specialSound = games.load_sound(specialSound) self.deathSound = games.load_sound("sounds/dragon_death.wav") # Sprite to show damage was inflicted self.damageSprite = games.Sprite(image=games.load_image("sprites/damage.png"), x=self.x, y=self.y) self.damageSpriteCounter = -1 # Sprite to show health info above head self.healthLabel = games.Text(value="HP: " + str(self.health), size=30, x=self.x, y=self.top - 20, color=color.white) games.screen.add(self.healthLabel)
class Goal(games.Sprite): # левые ворота, фиксирует касание и считает очки goal_image = games.load_image("goal1.jpg", transparent=False) wav_goal = games.load_sound("pingpong_goal.wav") wav_loss = games.load_sound("pingpong_loss.wav") def __init__(self, y=games.screen.height / 2, speed=2, odds_change=200): # Инициализирует объект Out super(Goal, self).__init__(image=Goal.goal_image, y=y, left=0, dy=speed) self.score = games.Text(value=0, size=42, color=YELLOW, top=10, left=games.screen.width / 2 + 30) self.odds_change = odds_change games.screen.add(self.score) def update(self): # меняет направление на краях и хаотично if self.top <= 0 or self.bottom >= games.screen.height: self.dy = -self.dy elif random.randrange(self.odds_change) == 100: self.dy = -self.dy self.touch() # проверка касания к мячу def touch(self): # Проверяет касание к мячу # если касается, уничтожает мяч и создает новый for ball in self.overlapping_sprites: Goal.wav_goal.play() self.add_score() ball.goal() ball.message() ball.destroy() new_ball = Ball() games.screen.add(new_ball) def add_score(self): # Добавляет очки, игра до 11 self.score.value += 1 self.score.left = games.screen.width / 2 + 30 if self.score.value == 11: self.end_game() def end_game(self): """ Завершает игру. """ Goal.wav_loss.play() end_message = games.Message(value="Ігру закінчено. Ви перемогли", size=60, color=color.red, x=games.screen.width / 2, y=games.screen.height / 3, lifetime=5 * games.screen.fps, after_death=games.screen.quit) games.screen.add(end_message)
class Out(games.Sprite): # the edge of the table, invisible, fixes the touch and counts the glasses # край стола, невидимый, фиксирует касание и считает очки out_image = games.load_image("line_bok.jpg", transparent=True) wav_goal = games.load_sound("pingpong_goal.wav") wav_loss = games.load_sound("pingpong_loss.wav") def __init__(self): # Initializes the Out object # Инициализирует объект Out super(Out, self).__init__(image=Out.out_image, y=games.screen.height / 2, right=games.screen.width - 1) self.score = games.Text(value=0, size=42, color=YELLOW, top=10, right=games.screen.width / 2 - 30) games.screen.add(self.score) def update(self): self.touch() # Checks the touch to the ball | проверка касания к мячу def touch(self): # Checks the touch to the ball # if applicable, destroys the ball and creates a new one # Проверяет касание к мячу # если касается, уничтожает мяч и создает новый for ball in self.overlapping_sprites: Out.wav_goal.play() self.add_score() ball.goal() ball.message() # ball.destroy() new_ball = Ball() games.screen.add(new_ball) def add_score(self): # Adds points if 11 eyes are scored - the end of the game # Добавляет очки, если набрано 11 очей - конец игры self.score.value += 1 self.score.right = games.screen.width / 2 - 30 if self.score.value == 11: self.end_game() def end_game(self): """ Finishes the game. """ """ Завершает игру. """ Out.wav_loss.play() end_message = games.Message(value="The game is over. You have lost", size=60, color=color.red, x=games.screen.width / 2, y=games.screen.height / 3, lifetime=5 * games.screen.fps, after_death=games.screen.quit) games.screen.add(end_message)
class Ball(games.Sprite): """ Ball """ """ Мячик """ ball_image = games.load_image("ball.png") wav_ping = games.load_sound("pingpong1.wav") wav_pingpong = games.load_sound("pingpong3.wav") def __init__(self): # Initializes a Ball object # Инициализирует объект Ball super(Ball, self).__init__(image=Ball.ball_image, x=games.screen.width / 4, y=random.randrange(30, games.screen.height - 30), dx=2, dy=2) self.message() def message(self): ball_message = games.Message(value="Innings", size=50, color=color.green, right=games.screen.width / 2 - 25, y=games.screen.height / 6, lifetime=3 * games.screen.fps) games.screen.add(ball_message) def update(self): if self.left < 0 or self.right > games.screen.width: Ball.wav_ping.play() # single sound | звук одиночный self.dx = -self.dx if self.bottom > games.screen.height or self.top < 0: Ball.wav_ping.play() # single sound | звук одиночный self.dy = -self.dy def goal(self): # change the direction of the ball without changing the speed # менять направление мяча без смены скорости self.destroy() def recoil(self): # changes direction and speed # меняет направление и скорость Ball.wav_pingpong.play() # звук от ракетки self.dx = -(self.dx + 1) def correct(self): # corrects the direction and speed # корректирует направление и скорость if self.dx < 0: # if it moves to the left | если движется влево self.dy = -(self.dy) if self.dx < -2: self.dx = -2 # speed limit | ограничение скорости
class Out(games.Sprite): # край стола, невидимый, фиксирует касание и считает очки out_image = games.load_image("line_bok.jpg", transparent=True) wav_goal = games.load_sound("pingpong_goal.wav") wav_loss = games.load_sound("pingpong_loss.wav") def __init__(self): # Инициализирует объект Out super(Out, self).__init__(image=Out.out_image, y=games.screen.height / 2, right=games.screen.width - 1) self.score = games.Text(value=0, size=42, color=YELLOW, top=10, right=games.screen.width / 2 - 30) games.screen.add(self.score) def update(self): self.touch() # проверка касания к мячу def touch(self): # Проверяет касание к мячу # если касается, уничтожает мяч и создает новый for ball in self.overlapping_sprites: Out.wav_goal.play() self.add_score() ball.goal() ball.message() ball.destroy() new_ball = Ball() games.screen.add(new_ball) def add_score(self): # Добавляет очки, игра до 11 self.score.value += 1 self.score.right = games.screen.width / 2 - 30 if self.score.value == 11: self.end_game() def end_game(self): """ Завершает игру. """ Out.wav_loss.play() end_message = games.Message(value="Ігру закінчено. Ви програли", size=60, color=color.red, x=games.screen.width / 2, y=games.screen.height / 3, lifetime=5 * games.screen.fps, after_death=games.screen.quit) games.screen.add(end_message)
class Ball(games.Sprite): """ Мячик """ ball_image = games.load_image("ball.png") wav_ping = games.load_sound("pingpong1.wav") wav_pingpong = games.load_sound("pingpong3.wav") def __init__(self): # Инициализирует объект Ball super(Ball, self).__init__(image=Ball.ball_image, x=games.screen.width / 4, y=random.randrange(30, games.screen.height - 30), dx=2, dy=2) self.message() def message(self): ball_message = games.Message(value="Подача", size=50, color=color.green, right=games.screen.width / 2 - 25, y=games.screen.height / 6, lifetime=3 * games.screen.fps) games.screen.add(ball_message) def update(self): if self.left < 0 or self.right > games.screen.width: Ball.wav_ping.play() # звук одиночный self.dx = -self.dx if self.bottom > games.screen.height or self.top < 0: Ball.wav_ping.play() # звук одиночный self.dy = -self.dy def goal(self): # менять направление мяча без смены скорости self.dx = -self.dx def recoil(self): # меняет направление и скорость Ball.wav_pingpong.play() # звук от ракетки self.dx = -(self.dx + 1) def correct(self): # корректирует направление и скорость if self.dx < 0: # движется влево self.dy = -(self.dy) if self.dx < -2: self.dx = -2 # ограничение скорости
class Missile(Collider): image = games.load_image('missile.bmp') sound = games.load_sound('missile.wav') BUFFER = 40 VELOCITY_FACTOR = 7 LIFETIME = 50 def __init__(self, ship_x, ship_y, ship_angle, ship_dx, ship_dy): Missile.sound.play() angle = ship_angle * math.pi / 180 buffer_x = Missile.BUFFER * math.sin(angle) buffer_y = Missile.BUFFER * -math.cos(angle) x = ship_x + buffer_x y = ship_y + buffer_y dx = ship_dx + Missile.VELOCITY_FACTOR * math.sin(angle) dy = ship_dy + Missile.VELOCITY_FACTOR * -math.cos(angle) super(Missile, self).__init__(image=Missile.image, x=x, y=y, dx=dx, dy=dy) self.lifetime = Missile.LIFETIME def update(self): super(Missile, self).update() self.lifetime -= 1 if self.lifetime == 0: self.destroy() if self.overlapping_sprites: for sprite in self.overlapping_sprites: sprite.die() self.die()
class Ship(games.Sprite): """ The Player's Ship """ image = games.load_image("ship.jpg") ROTATION_STEP = 3 VELOCITY_STEP = .03 sound = games.load_sound("thrust.wav") def update(self): """ Rotate based on keys pressed """ if games.keyboard.is_pressed(games.K_LEFT): self.angle -= Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_RIGHT): self.angle += Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_UP): Ship.sound.play() angle = self.angle * math.pi / 180 # radians self.dx += Ship.VELOCITY_STEP * math.sin(angle) self.dy += Ship.VELOCITY_STEP * -math.cos(angle) if self.top > games.screen.height: self.bottom = 0 if self.bottom < 0: self.top = games.screen.height if self.left > games.screen.width: self.right = 0 if self.right < 0: self.left = games.screen.width
def main(): #Set screen background screen_background = games.load_image('stars background.png', transparent=False) games.screen.background = screen_background #Play sound ## red_alert = games.load_sound('Red_alert.wav') ## red_alert.play() #Play Music music = games.load_sound('Robolympics.wav') music.play(-1) ## pygame.mixer.music.load('Robolympics.mp3') ## pygame.mixer.music.play(-1) #Create spaceship spawn() #Create the score score = Score() games.screen.add(score) #Create cursor sprite controlled by mouse cursor = Cursor() games.screen.add(cursor) games.mouse.is_visible = False #Starts mainloop games.screen.mainloop()
class Explosion(games.Animation): sound = games.load_sound("eksplozja.wav") images_big = [ "expl1.bmp", "expl2.bmp", "expl3.bmp", "expl4.bmp", "expl5.bmp", "expl6.bmp", "expl7.bmp", "expl8.bmp", "expl9.bmp" ] images_small = ["expl1.bmp", "expl2.bmp"] def __init__(self, x, y, nr): if nr == 'big': super(Explosion, self).__init__(images=Explosion.images_big, x=x, y=y, repeat_interval=6, n_repeats=1, is_collideable=False) elif nr == 'small': super(Explosion, self).__init__(images=Explosion.images_small, x=x, y=y, repeat_interval=6, n_repeats=1, is_collideable=False) Explosion.sound.play()
class Missile(games.Sprite): """ A missile launched by the player's ship. """ image = games.load_image("missile.bmp") sound = games.load_sound("missile.wav") BUFFER = 40 VELOCITY_FACTOR = 7 LIFETIME = 40 def __init__(self, ship_x, ship_y, ship_angle): """ Initialize missile sprite. """ Missile.sound.play() # convert to radians angle = ship_angle * math.pi / 180 # calculate missile's starting position buffer_x = Missile.BUFFER * math.sin(angle) buffer_y = Missile.BUFFER * -math.cos(angle) x = ship_x + buffer_x y = ship_y + buffer_y # calculate missile's velocity components dx = Missile.VELOCITY_FACTOR * math.sin(angle) dy = Missile.VELOCITY_FACTOR * -math.cos(angle) # create the missile super(Missile, self).__init__(image = Missile.image, x = x, y = y, dx = dx, dy = dy) self.lifetime = Missile.LIFETIME def update(self): """ Move the missile. """ # if lifetime is up, destroy the missile self.lifetime -= 1 if self.lifetime == 0: self.destroy() # wrap the missile around screen if self.top > games.screen.height: self.bottom = 0 if self.bottom < 0: self.top = games.screen.height if self.left > games.screen.width: self.right = 0 if self.right < 0: self.left = games.screen.width # check if missile overlaps any other object if self.overlapping_sprites: for sprite in self.overlapping_sprites: sprite.die() self.die() def die(self): """ Destroy the missile. """ self.destroy()
def __init__(self): self.sound = games.load_sound('level.wav') self.player1_score = games.Text(value=0, size=40, color=color.white, x=10, top=5, is_collideable=False) games.screen.add(self.player1_score) self.player2_score = games.Text(value=0, size=40, color=color.red, x=games.screen.width - 10, top=5, is_collideable=False) games.screen.add(self.player2_score) self.player1 = Player1(x=games.screen.width / 2 - 100, y=games.screen.height / 2) games.screen.add(self.player1) self.player2 = Player2(x=games.screen.width / 2 + 100, y=games.screen.height / 2) games.screen.add(self.player2) self.ball = Ball(game=self, x=games.screen.width / 2, y=games.screen.height / 2) games.screen.add(self.ball)
class Pocisk(games.Sprite): sound = games.load_sound("pocisk.wav") image = games.load_image("pocisk.bmp") def __init__(self, statek_x, statek_y, dy): Pocisk.sound.play() super(Pocisk, self).__init__(image=Pocisk.image, x=statek_x, y=statek_y, dy=dy) def update(self): # sprawdź, czy pocisk zachodzi na jakiś inny obiekt if self.overlapping_sprites: for sprite in self.overlapping_sprites: sprite.die() self.die() def die(self, expl='Yes'): if expl == 'Yes': new_explosion = Explosion(x=self.x, y=self.y, nr='small') games.screen.add(new_explosion) self.destroy() elif expl == 'No': self.destroy()
class Missile(Collider): # Класс ракет """Rocket, which may shoot space ship player""" image = games.load_image('missile.bmp') # Загрузка изображения ракет sound = games.load_sound('missile.wav') # Загружаем звук BUFFER = 40 # растояние в пикселях появления ракеты VELOCITY_FACTOR = 7 # скорость движения ракеты LIFETIME = 40 # время в кадрах жизни ракеты def __init__(self, ship_x, ship_y, ship_angle): # Передаются параметры от корабля """Init sprite with image missile""" Missile.sound.play() # проигрывается звук запуска ракет angle = ship_angle * math.pi / 180 # Высчитывается угол сопоставимый с отметкой на корабле buffer_x = Missile.BUFFER * math.sin(angle) # Высчитывается точка появления ракеты по абциссе в 40 писселях от корабля buffer_y = Missile.BUFFER * -math.cos(angle) # Высчитывается точка появления ракеты по ординате в 40 писселях от корабля x = ship_x + buffer_x # Высчитывается точка появления ракеты по абциссе в 40 писселях от корабля y = ship_y + buffer_y # Высчитывается точка появления ракеты по ординате в 40 писселях от корабля dx = Missile.VELOCITY_FACTOR * math.sin(angle) # Задается скорость ракеты по абцисе dy = Missile.VELOCITY_FACTOR * -math.cos(angle) # Задается скорость ракеты по ординате super().__init__(Missile.image, x = x, y = y, # Хер поймешь зачем такие сложные высчеты, надо разбираться в начальной математике dx = dx, dy = dy) # self.lifetime = Missile.LIFETIME # def update(self): """Moves rocket""" super().update() # Наследование от Collider ( 1 - переход при попадание на край экрана # 2 - проверка на столкновения с другими объектами (астероидами) self.lifetime -= 1 # при каждом кадре жизнь выстрела становится меньше на 1 if self.lifetime == 0: # Если она равна 1: self.destroy() # выстрел уничтожается
def __init__(self): """ Initialize Game object. """ # set level self.level = 0 # load sound for level advance self.sound = games.load_sound("level.wav") # create score self.score = games.Text(value = 0, size = 30, color = color.white, top = 5, right = games.screen.width - 10, is_collideable = False) games.screen.add(self.score) # create player's ship self.ship = Ship(game = self, x = games.screen.width/2, y = games.screen.height/2) games.screen.add(self.ship) #CHANGE powerups self.powerup = PowerUp(game = self, x = random.choice([1,-1]), y = random.choice([1,-1]))
def __init__(self): """ Initialize Game object. """ # set level self.level = 0 # load sound for level advance self.sound = games.load_sound("level.wav") # create score self.score = games.Text(value = 0, size = 30, color = color.white, top = 5, right = games.screen.width - 10, is_collideable = False) games.screen.add(self.score) ## # create player's ship self.platform = Platform(game = self, x = games.screen.width/2, y = games.screen.height) games.screen.add(self.platform) # Create the ball self.ball = Ball(game = self, x = games.screen. width/2, y = games.screen.height, dx = 2, dy = 2) games.screen.add(self.ball)
class Missile(Collider): """Ракеты коробля""" image = games.load_image("missile.bmp") sound = games.load_sound("missile.wav") BUFFER = 40 VELOCITY_FACTOR = 7 LIFETIME = 40 def __init__(self, ship_x, ship_y, ship_angle): """Инициализация ракеты""" Missile.sound.play() angle = ship_angle * math.pi / 180 buffer_x = Missile.BUFFER * math.sin(angle) buffer_y = Missile.BUFFER * -math.cos(angle) x = ship_x + buffer_x y = ship_y + buffer_y dx = Missile.VELOCITY_FACTOR * math.sin(angle) dy = Missile.VELOCITY_FACTOR * -math.cos(angle) super(Missile, self).__init__(image=Missile.image, x=x, y=y, dx=dx, dy=dy) self.lifetime = Missile.LIFETIME def update(self): """ Перемещает ракету""" super(Missile, self).update() self.lifetime -= 1 if self.lifetime == 0: self.destroy()
class Ship(Collider): """ The Player's Ship """ image = games.load_image("ship.png") ROTATION_STEP = 3 VELOCITY_STEP = .03 MISSILE_DELAY = 25 sound = games.load_sound("thrust.wav") def __init__(self, x, y): """ Initialise the ship """ super(Ship, self).__init__(image=Ship.image, x=x, y=y) self.missile_wait = 0 def update(self): """ Rotate based on keys pressed """ # Inputs if games.keyboard.is_pressed(games.K_LEFT): self.angle -= Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_RIGHT): self.angle += Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_UP): Ship.sound.play() angle = self.angle * math.pi / 180 # radians self.dx += Ship.VELOCITY_STEP * math.sin(angle) self.dy += Ship.VELOCITY_STEP * -math.cos(angle) # Firing missiles is more complex if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0: new_missile = Missile(self.x, self.y, self.angle) games.screen.add(new_missile) self.missile_wait = Ship.MISSILE_DELAY super(Ship, self).update() if self.missile_wait > 0: self.missile_wait -= 1
def __init__(self): """ Initialize Game object.""" # set level self.level = 0 #load sound for level advance self.sound = games.load_sound("../Res/level.wav") #create score self.score = games.Text(value = 0, size = 30, color = color.white, top = 5, right = games.screen.width - 10, is_collideable = False) games.screen.add(self.score) self.livesboard = games.Text(value = str(self.lives)+" left", size = 30, color = color.white, top = 5, left = 25, is_collideable = False) games.screen.add(self.livesboard) #create a player's ship self.new_ship()
class Book(games.Sprite): sound_end = games.load_sound('music/end.wav') def __init__(self, img, student, x=900, y=400): super(Book, self).__init__(image=img, x=x, y=y, dx=-5) self.student = student def update(self): if self.left < 0: self.destroy() self.student.score.value += 1 self.angle += 2 def collision(self): self.destroy() def end_game(self): Book.sound_end.play() end_message = games.Message(value='YOU LOOOOOSE!!', size=90, color=color.dark_red, x=games.screen.width / 2, y=games.screen.height / 2, lifetime=2 * games.screen.fps, after_death=games.screen.quit) games.screen.add(end_message)
class Ship(Collider): """ The Player's Ship """ image = games.load_image("ship.png") ROTATION_STEP = 3 VELOCITY_STEP = .03 MAX_VELOCITY = 3 MISSILE_DELAY = 25 sound = games.load_sound("thrust.wav") def __init__(self, game, x, y): """ Initialise the ship """ super(Ship, self).__init__(image=Ship.image, x=x, y=y) self.missile_wait = 0 self.game = game self.health = 5 self.invulnerability_time = 0 self.health_message = games.Text(value="Health:" + str(self.health), size=30, color=color.white, left=10, top=5, is_collideable=False) games.screen.add(self.health_message) def update(self): """ Rotate based on keys pressed """ # Rotation control if games.keyboard.is_pressed(games.K_LEFT): self.angle -= Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_RIGHT): self.angle += Ship.ROTATION_STEP # Velocity control if games.keyboard.is_pressed(games.K_UP): Ship.sound.play() angle = self.angle * math.pi / 180 # radians self.dx += Ship.VELOCITY_STEP * math.sin(angle) self.dy += Ship.VELOCITY_STEP * -math.cos(angle) self.dx = min(max(self.dx, -Ship.MAX_VELOCITY), Ship.MAX_VELOCITY) self.dy = min(max(self.dy, -Ship.MAX_VELOCITY), Ship.MAX_VELOCITY) # Firing missiles is more complex if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0: new_missile = Missile(self.x, self.y, self.angle) games.screen.add(new_missile) self.missile_wait = Ship.MISSILE_DELAY self.health_message.value = "Health:" + str(self.health) super(Ship, self).update() if self.missile_wait > 0: self.missile_wait -= 1 def die(self): """ Destroys the ship and ends the game """ super(Ship, self).die() self.game.end()
def __init__(self): """ Cursor Initializer """ super(Cursor, self).__init__(image=games.load_image("Sprites/cursor.png"), x=games.mouse.x, y=games.mouse.y) self.mouseClicked = False self.mouseCounter = 0 # Load gunshot sound self.gunShotSound = games.load_sound("Sounds/shot.wav")
def __init__(self): super(Bird, self).__init__(images=Bird.images, x=300, y=300, dy=7, n_repeats=0, repeat_interval=8) self.score = games.Text(value=0, size=100, color=color.red, top=5, right=games.screen.width - 10) games.screen.add(self.score) #various sounds that come on at various points when interaction occurs self.chirp = games.load_sound("Bird.Chirp.mp3") self.crash = games.load_sound("swisher.mp3") self.ding = games.load_sound("coin.mp3") self.time = 2 self.message = None
class Ship(Collider): """ Statek kosmiczny gracza. """ image = games.load_image("statek.bmp") sound = games.load_sound("przyspieszenie.wav") ROTATION_STEP = 3 VELOCITY_STEP = .03 VELOCITY_MAX = 3 MISSILE_DELAY = 25 def __init__(self, game, x, y): """ Inicjalizuj duszka statku. """ super(Ship, self).__init__(image = Ship.image, x = x, y = y) self.game = game self.missile_wait = 0 def update(self): """ Obracaj statek, przyśpieszaj i wystrzeliwuj pociski, zależnie od naciśniętych klawiszy. """ super(Ship, self).update() # obróć statek zależnie od naciśniętych klawiszy strzałek (w prawo lub w lewo) if games.keyboard.is_pressed(games.K_LEFT): self.angle -= Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_RIGHT): self.angle += Ship.ROTATION_STEP # zastosuj siłę ciągu przy naciśniętym klawiszu strzałki w górę if games.keyboard.is_pressed(games.K_UP): Ship.sound.play() # zmień składowe prędkości w zależności od kąta położenia statku angle = self.angle * math.pi / 180 # zamień na radiany self.dx += Ship.VELOCITY_STEP * math.sin(angle) self.dy += Ship.VELOCITY_STEP * -math.cos(angle) # ogranicz prędkość w każdym kierunku self.dx = min(max(self.dx, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX) self.dy = min(max(self.dy, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX) # jeśli czekasz, aż statek będzie mógł wystrzelić następny pocisk, # zmniejsz czas oczekiwania if self.missile_wait > 0: self.missile_wait -= 1 # wystrzel pocisk, jeśli klawisz spacji jest naciśnięty i skończył się # czas oczekiwania if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0: new_missile = Missile(self.x, self.y, self.angle) games.screen.add(new_missile) self.missile_wait = Ship.MISSILE_DELAY def die(self): """ Zniszcz statek i zakończ grę. """ self.game.end() super(Ship, self).die()
def _init__(self): """Initialize Game object. """ # set level self.level = 0 #load sound for level advance self.sound = games.load_sound("level.wav") for player in number_of_players: self.ship = Ship(game = self, x = games.screen.width/2, y = games.screen.height/2) games.screen.add(self.ship)
class Ship(Collider): """ The player's ship. """ image = games.load_image("ship.bmp") sound = games.load_sound("thrust.wav") ROTATION_STEP = 5 VELOCITY_STEP = .03 VELOCITY_MAX = 3 MISSILE_DELAY = 20 def __init__(self, game, x, y): """ Initialize ship sprite. """ super(Ship, self).__init__(image = Ship.image, x = x, y = y) self.game = game self.missile_wait = 0 def update(self): """ Rotate, thrust and fire missiles based on keys pressed. """ super(Ship, self).update() # Move based on left and right arrow keys if games.keyboard.is_pressed(games.K_LEFT): self.x -= 1 if games.keyboard.is_pressed(games.K_RIGHT): self.x += 1 if self.left > games.screen.width: self.right = 0 if self.right < 0: self.left = games.screen.width # change velocity components based on ship's angle angle = self.angle * math.pi / 180 # convert to radians self.dx += Ship.VELOCITY_STEP * math.sin(angle) self.dy += Ship.VELOCITY_STEP * -math.cos(angle) # cap velocity in each direction self.dx = min(max(self.dx, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX) self.dy = min(max(self.dy, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX) # if waiting until the ship can fire next, decrease wait if self.missile_wait > 0: self.missile_wait -= 1 # fire missile if spacebar pressed and missile wait is over if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0: new_missile = Missile(self.x, self.y, self.angle) games.screen.add(new_missile) self.missile_wait = Ship.MISSILE_DELAY def die(self): """ Destroy ship and end the game. """ self.game.end() super(Ship, self).die()
def main(): # background wall_image = games.load_image("field_background.bmp", transparent=False) games.screen.background = wall_image # when game starts, play sound yahoo_sound = games.load_sound("yahoo.wav") yahoo_sound.play() # begin message start_message = games.Message(value="Kill 20 ducks!", size=90, color=color.blue, x=games.screen.width / 2, y=games.screen.height / 2, lifetime=games.screen.fps) games.screen.add(start_message) directions_spacebar = games.Message(value="Spacebar to shoot!", size=25, color=color.green, is_collideable=False, x=games.screen.width / 4, y=games.screen.height - 20, lifetime=500) games.screen.add(directions_spacebar) directions_turning = games.Message(value="Turn with <- and -> arrow keys!", size=25, color=color.green, is_collideable=False, x=games.screen.width - 225, y=games.screen.height - 20, lifetime=500) games.screen.add(directions_turning) # create 4 ducks for i in range(2): x = random.randrange(games.screen.width) y = random.randrange(400) size = random.choice( [Duck.Duck1, Duck.Duck2, Duck.Duck3, Duck.Shadow_duck]) new_duck = Duck(x=x, y=y, size=size) games.screen.add(new_duck) # add the gun the_gun = Gun(x=games.screen.width / 2, y=games.screen.height) games.screen.add(the_gun) games.mouse.is_visible = False games.screen.event_grab = True games.screen.mainloop()
class Spaceship(Collider): # The player's spaceship. image = games.load_image("SpaceShip.png") sound = games.load_sound("thrust.wav") ROTATION_STEP = 3 VELOCITY_STEP = .03 VELOCITY_MAX = 3 MISSILE_DELAY = 25 def __init__(self, game, x, y): # Initialise the spaceship sprite. super(Spaceship, self).__init__(image=Spaceship.image, x=x, y=y) self.game = game self.missile_wait = 0 def update(self): # Rotate spaceship using left and right arrows. super(Spaceship, self).update() if games.keyboard.is_pressed(games.K_LEFT): self.angle -= Spaceship.ROTATION_STEP if games.keyboard.is_pressed(games.K_RIGHT): self.angle += Spaceship.ROTATION_STEP # Apply thrust based on the up-arrow key. if games.keyboard.is_pressed(games.K_UP): Spaceship.sound.play() # Change the velocity based on the spaceship's angle. angle = self.angle * math.pi / 180 # Convert to radians. self.dx += Spaceship.VELOCITY_STEP * math.sin(angle) self.dy += Spaceship.VELOCITY_STEP * -math.cos(angle) # Cap velocity in each direction. self.dx = min(max(self.dx, -Spaceship.VELOCITY_MAX), Spaceship.VELOCITY_MAX) self.dy = min(max(self.dy, -Spaceship.VELOCITY_MAX), Spaceship.VELOCITY_MAX) # If waiting until the ship can fire next, decrease wait. if self.missile_wait > 0: self.missile_wait -= 1 # Fire a missile if spacebar pressed and missile wait is over. if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0: new_missile = Missile(self.x, self.y, self.angle) games.screen.add(new_missile) self.missile_wait = Spaceship.MISSILE_DELAY def die(self): # Destroy the spaceship and end the game. self.game.end() super(Spaceship, self).die()
class Ship(Collider): """ Корабль игрока """ image = games.load_image("ship.bmp") sound = games.load_sound("thrust.wav") ROTATION_STEP = 3 VELOCITY_STEP = .03 VELOCITY_MAX = 3 MISSILE_DELAY = 25 def __init__(self, game, x, y): """ Инициализирует спрайт с изображением космического корабля """ super(Ship, self).__init__(image=Ship.image, x=x, y=y) self.game = game self.missile_wait = 0 def update(self): """ поворот и запуск ракеты на основе нажатых клавиш. """ super(Ship, self).update() # вращает корабль при нажатии клавиш со стрелками if games.keyboard.is_pressed(games.K_LEFT): self.angle -= Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_RIGHT): self.angle += Ship.ROTATION_STEP # движение в перед if games.keyboard.is_pressed(games.K_UP): Ship.sound.play() # изменение горизонтальной и вертикальной скорости корабля с учетом угла поворота angle = self.angle * math.pi / 180 # преобразование в радианы self.dx += Ship.VELOCITY_STEP * math.sin(angle) self.dy += Ship.VELOCITY_STEP * -math.cos(angle) # ограничение горизонтальной и вертикальной скорости self.dx = min(max(self.dx, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX) self.dy = min(max(self.dy, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX) # если запуск следующей ракеты пока еще не разрешен, вычесть 1 из длины оставшегося интервала ожидания if self.missile_wait > 0: self.missile_wait -= 1 # если нажат Пробел и интервал ожидания истек. выпустить ракету if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0: new_missile = Missile(self.x, self.y, self.angle) games.screen.add(new_missile) self.missile_wait = Ship.MISSILE_DELAY def die(self): """ Разрушает корабль и завершает игру""" self.game.end() super(Ship, self).die()
class Ship(games.Sprite): """ Корабль игрока """ image = games.load_image("ship.bmp") sound = games.load_sound("thrust.wav") ROTATION_STEP = 3 VELOCITY_STEP = .03 MISSILE_DELAY = 25 def __init__(self, x, y): """ Инициализирует спрайт с изображением космического корабля. """ super(Ship, self).__init__(image=Ship.image, x=x, y=y) self.missile_wait = 0 def update(self): """ вращение и движение """ # Вращает корабль при нажатии клавиш со стрелками if games.keyboard.is_pressed(games.K_LEFT): self.angle -= Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_RIGHT): self.angle += Ship.ROTATION_STEP # движение в перед if games.keyboard.is_pressed(games.K_UP): Ship.sound.play() # изменение горизонтальной и вертикальной скорости корабля с учетом угла поворота angle = self.angle * math.pi / 180 # преобразование в радианы self.dx += Ship.VELOCITY_STEP * math.sin(angle) self.dy += Ship.VELOCITY_STEP * -math.cos(angle) # Заставляет корабль обогнуть экран. if self.top > games.screen.height: self.bottom = 0 if self.bottom < 0: self.top = games.screen.height if self.left > games.screen.width: self.right = 0 if self.right < 0: self.left = games.screen.width # если запуск следующей ракеты пока еще не разрешен, вычесть 1 из длины оставшегося интервала ожидания if self.missile_wait > 0: self.missile_wait -= 1 # если нажат Пробел и интервал ожидания истек, выпустить ракету if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0: new_missile = Missile(self.x, self.y, self.angle) games.screen.add(new_missile) self.missile_wait = Ship.MISSILE_DELAY
def main(): # background wall_image = games.load_image("field_background.bmp", transparent = False) games.screen.background = wall_image # when game starts, play sound yahoo_sound = games.load_sound("yahoo.wav") yahoo_sound.play() # begin message start_message = games.Message(value = "Kill 20 ducks!", size = 90, color = color.blue, x = games.screen.width/2, y = games.screen.height/2, lifetime = games.screen.fps) games.screen.add(start_message) directions_spacebar = games.Message(value = "Spacebar to shoot!", size = 25, color = color.green, is_collideable = False, x = games.screen.width/4, y = games.screen.height - 20, lifetime = 500) games.screen.add(directions_spacebar) directions_turning = games.Message(value = "Turn with <- and -> arrow keys!", size = 25, color = color.green, is_collideable = False, x = games.screen.width - 225, y = games.screen.height - 20, lifetime = 500) games.screen.add(directions_turning) # create 4 ducks for i in range(2): x = random.randrange(games.screen.width) y = random.randrange(400) size = random.choice([Duck.Duck1, Duck.Duck2, Duck.Duck3, Duck.Shadow_duck]) new_duck = Duck(x = x, y = y, size = size) games.screen.add(new_duck) # add the gun the_gun = Gun(x = games.screen.width/2, y = games.screen.height) games.screen.add(the_gun) games.mouse.is_visible = False games.screen.event_grab = True games.screen.mainloop()
class Ship(Collider): # При создании объекта Ship """Player ship""" image = games.load_image('ship.bmp') # Загружаем изображение корабля ROTATION_STEP = 5 # Угол отклонения корабля VELOCITY_STEP = .025 # шаг увеличения скорости sound = games.load_sound('thrust.wav') # Загрузка звука рева двигателя MISSILE_DELAY = 25 # Задержка выпуска ракеты VELOCITY_MAX = 2 # Максимальная скорость корабля def __init__(self, game, x, y): # Корабль респится строго посередине """Init sprite with image space ship""" super().__init__(Ship.image, x=x, y=y) # Загрузка данных self.missile_wait = 0 # Задержка ожидания ракеты self.game = game # Передаем ссылку на экз класса Game def update(self): """Whirl ship by pressing buttons with arrow""" super().update() # Проверка на границы, на столкновения if games.keyboard.is_pressed(games.K_LEFT): # Угол наклона self.angle -= Ship.ROTATION_STEP # -3 if games.keyboard.is_pressed(games.K_RIGHT): # Угол наклона self.angle += Ship.ROTATION_STEP # +3 if games.keyboard.is_pressed( games.K_UP): # При нажатие вверха увеличивается скорость Ship.sound.play() # Проигрывается звук двигателя angle = self.angle * math.pi / 180 # Высчитывается угол self.dx += Ship.VELOCITY_STEP * math.sin( angle) # Прибавка скорости по абциссе self.dy += Ship.VELOCITY_STEP * -math.cos( angle) # Прибавка скорости по ординате if games.keyboard.is_pressed( games.K_SPACE ) and self.missile_wait == 0: # Если нажат пробел и задержка ракет равна 0 new_missile = Missile( self.x, self.y, self.angle ) # Создается новая ракета, в нее передаются параметры абциссы, ординаты и угла games.screen.add(new_missile) # спрайт выводится на экран self.missile_wait = Ship.MISSILE_DELAY # обновляется время ожидания новой ракет, выставляется в 25 кадров if self.missile_wait > 0: # если задержка больше 0 self.missile_wait -= 1 # из задержки вычитается 1 self.dx = min( max(self.dx, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX ) #Мин(Макс(тек.скорость абциссы, отр. макс скорость), макс.скорость) # Ограничение движения, максимальная скорость 3 self.dy = min( max(self.dy, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX ) #Мин(Макс(тек.скорость ординаты, отр. макс скорость), макс.скорость) # Ограничение движения, максимальная скорость 3 def die(self): # Вызывает спрайт с концом игры, взрывает корабль self.game.end() super().die()
class Missile(games.Sprite): """ A missile what gets shot """ image = games.load_image("missile.bmp") sound = games.load_sound("missile.wav") BUFFER = 40 VELOCITY_FACTOR = 7 LIFETIME = 40 def __init__(self, ship_x, ship_y, ship_angle): """ Initialise the ship missile """ Missile.sound.play() angle = ship_angle * math.pi / 180 # Where missile starts buffer_x = Missile.BUFFER * math.sin(angle) buffer_y = Missile.BUFFER * -math.cos(angle) x = ship_x + buffer_x y = ship_y + buffer_y # velocity dx = Missile.VELOCITY_FACTOR * math.sin(angle) dy = Missile.VELOCITY_FACTOR * -math.cos(angle) # Create super(Missile, self).__init__(image=Missile.image, x=x, y=y, dx=dx, dy=dy) self.lifetime = Missile.LIFETIME def update(self): """ Move then destroy missile""" # Lifetime self.lifetime -= 1 if self.lifetime == 0: self.destroy() # wrap if self.top > games.screen.height: self.bottom = 0 if self.bottom < 0: self.top = games.screen.height if self.left > games.screen.width: self.right = 0 if self.right < 0: self.left = games.screen.width
class Ship(Collider): """ Создание корабля """ image = games.load_image("ship.bmp") sound = games.load_sound("thrust.wav") ROTATION_STEP = 3 VELOCITY_STEP = .03 VELOCITY_MAX = 3 MISSILE_DELAY = 25 def __init__(self, game, x, y): """ Спрайт корабля """ super(Ship, self).__init__(image=Ship.image, x=x, y=y) self.game = game self.missile_wait = 0 def update(self): """ Перемещение корабля """ super(Ship, self).update() # повороты if games.keyboard.is_pressed(games.K_LEFT): self.angle -= Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_RIGHT): self.angle += Ship.ROTATION_STEP # звук двигателей корабля при нажатии на стрелку вверх if games.keyboard.is_pressed(games.K_UP): Ship.sound.play() # Изменение угла спрайта и угла пушки при повороте корабля angle = self.angle * math.pi / 180 # переводим в радианы... self.dx += Ship.VELOCITY_STEP * math.sin(angle) self.dy += Ship.VELOCITY_STEP * -math.cos(angle) # рассчет траектории перемещения self.dx = min(max(self.dx, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX) self.dy = min(max(self.dy, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX) # Задержка выстрела if self.missile_wait > 0: self.missile_wait -= 1 # выстрел на пробел if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0: new_missile = Missile(self.x, self.y, self.angle) games.screen.add(new_missile) self.missile_wait = Ship.MISSILE_DELAY def die(self): """ Очередная СМЭРТЬ """ self.game.end() super(Ship, self).die()
class Ship(games.Sprite): """ The player's ship. """ image = games.load_image("ship.bmp") sound = games.load_sound("thrust.wav") ROTATION_STEP = 3 VELOCITY_STEP = .03 MISSILE_DELAY = 25 def __init__(self, x, y): """ Initialize ship sprite. """ super(Ship, self).__init__(image=Ship.image, x=x, y=y) self.missile_wait = 0 def update(self): """ Rotate and thrust based on keys pressed. """ # rotate based on left and right arrow keys if games.keyboard.is_pressed(games.K_LEFT): self.angle -= Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_RIGHT): self.angle += Ship.ROTATION_STEP # apply thrust based on up arrow key if games.keyboard.is_pressed(games.K_UP): Ship.sound.play() # change velocity components based on ship's angle angle = self.angle * math.pi / 180 # convert to radians self.dx += Ship.VELOCITY_STEP * math.sin(angle) self.dy += Ship.VELOCITY_STEP * -math.cos(angle) # wrap the ship around screen if self.top > games.screen.height: self.bottom = 0 if self.bottom < 0: self.top = games.screen.height if self.left > games.screen.width: self.right = 0 if self.right < 0: self.left = games.screen.width # if waiting until the ship can fire next, decrease wait if self.missile_wait > 0: self.missile_wait -= 1 # fire missile if spacebar pressed and missile wait is over if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0: new_missile = Missile(self.x, self.y, self.angle) games.screen.add(new_missile) self.missile_wait = Ship.MISSILE_DELAY
class Missile(games.Sprite): """ Ракета, которую может выпустить космический корабль игрока. """ image = games.load_image("missile.bmp") sound = games.load_sound("missile.wav") BUFFER = 40 VELOCITY_FACTOR = 7 LIFETIME = 40 def __init__(self, ship_x, ship_y, ship_angle): """ Инициализирует спрайт с изображением ракеты """ Missile.sound.play() # преобразование в радианы angle = ship_angle * math.pi / 180 # вычисление начальной позиции ракеты buffer_x = Missile.BUFFER * math.sin(angle) buffer_y = Missile.BUFFER * -math.cos(angle) x = ship_x + buffer_x y = ship_y + buffer_y # вычисление горизонтальной и вертикальной скорости ракеты dx = Missile.VELOCITY_FACTOR * math.sin(angle) dy = Missile.VELOCITY_FACTOR * -math.cos(angle) # создание ракеты super(Missile, self).__init__(image=Missile.image, x=x, y=y, dx=dx, dy=dy) self.lifetime = Missile.LIFETIME def update(self): """ Перемещает ракету. """ # еспи "срок годности" ракеты истек, она уничтожается self.lifetime -= 1 if self.lifetime == 0: self.destroy() # ракета будет огибать экран if self.top > games.screen.height: self.bottom = 0 if self.bottom < 0: self.top = games.screen.height if self.left > games.screen.width: self.right = 0 if self.right < 0: self.left = games.screen.width
def __init__(self): super(Clock, self).__init__(image=Game.image, x=0, y=0) # Timer Display self.timer = games.Text(value="1:00", size=50, x=300, y=435, color=color.white) games.screen.add(self.timer) self.clockCount = 0 self.seconds = 60 # Sound For Last 10 Seconds self.sound = games.load_sound("Sounds/beep.wav") self.started = False
def die(self): """ Destroy self and then quack """ duck_quack = games.load_sound("quack.wav") duck_quack.play() self.destroy() # add a new duck ## this is cool because they are spontaneously spawning from the grass with ## the death of a comrade x = random.randrange(games.screen.width) y = random.randrange(400) size = random.choice([Duck.Duck1, Duck.Duck2, Duck.Duck3, Duck.Shadow_duck]) new_duck = Duck(x = x, y = y, size = size) games.screen.add(new_duck)
def __init__(self, name, minHP=20, maxHP=53, image="", attackSound="", specialSound="", x=450, y=250, dx=0, dy=1): super(Monster, self).__init__(image=games.load_image(image, transparent=True), x=x, y=y, dx=dx, dy=dy) self.name = name.title() self.status = "Alive" self.health = randint(minHP, maxHP) self.alive = True self.moving = False self.attacking = False self.attackDelay = 0 # Sounds self.attackSound = games.load_sound(attackSound) self.specialSound = games.load_sound(specialSound) self.deathSound = games.load_sound("sounds/dragon_death.wav") # Red slash mark to indicated damage self.damageSprite = games.Sprite(games.load_image("sprites/damage.png"), x=self.x, y=self.y) self.damageSpriteCounter = -1 # Health label self.lblHP = games.Text(value="HP: " + str(self.health), size=30, x=self.x, y=self.top - 20, color=color.white) games.screen.add(self.lblHP)
def __init__(self): """ Initialize Game object. """ # set level, score , ship sound and add it to the screen. Then make ship self.level = 0 self.sound = games.load_sound("level.wav") self.score = games.Text(value = 0, size = 30, color = color.white, top = 5, right = games.screen.width - 10, is_collideable = False) games.screen.add(self.score) self.ship = Ship(game = self, x = games.screen.width/2, y = games.screen.height/2) games.screen.add(self.ship)
def __init__(self): """Выбор начального уровня""" #выбор начального игрового уровня self.level=0 #загрузка звука следующего уровня self.sound=games.load_sound("level.wav") #создание обьекта текущего счета self.score=games.Text(value=0, size=60, color=color.white, top=5, right=games.screen.width-10, is_collideable=False) games.screen.add(self.score) # создание корабля,которым управляет игрок self.ship=Ship(game=self, x=games.screen.width/2, y=games.screen.height/2) games.screen.add(self.ship)
def __init__(self): self.sound = games.load_sound("level.wav") self.invaders = [] self.level = 1 self.score = games.Text(value = 0, size = 30, color = color.white, top = 5, right = games.screen.width - 10, is_collideable = False) games.screen.add(self.score) self.level1() self.ship = Ship(game = self, x = games.screen.width/2, y = games.screen.height - 25, invaders = self.invaders) games.screen.add(self.ship)
def __init__(self): """ Initialize Game object. """ # set level self.level = 0 # load sound for level advance self.sound = games.load_sound("level.wav") # create score self.score = games.Text( value=0, size=30, color=color.white, top=5, right=games.screen.width - 10, is_collideable=False ) games.screen.add(self.score) self.lives = games.Text(value=5, size=30, color=color.white, top=5, left=10, is_collideable=False) games.screen.add(self.lives) # create player's ship self.ship = Ship(game=self, x=games.screen.width / 2, y=games.screen.height / 2) games.screen.add(self.ship)
def game_over(self): """ Game ends, kill objects, prevent clicking, redirect to menu""" games.music.stop() self.lives = - 1 # show message for 15 seconds self.message = "Game Over" end_message = games.Message(value = self.message, size = 90, color = color.white, x = games.screen.width/2, y = games.screen.height/2, lifetime = 15 * games.screen.fps, after_death = restart, is_collideable = False) games.screen.add(end_message) # load and play sound if not self.muted: gameOverSound = games.load_sound("sounds/gameover.wav") gameOverSound.play()
def __init__(self): """Initialize Game""" #set level self.level = 0 #load level advance sound self.sound = games.load_sound("level.wav") #create score self.score = games.Text(value = 0, size = 30, color = color.white, top = 5, right = games.screen.width -10, is_collideable = False) games.screen.add(self.score) #where's my ship self.ship = Ship(game = self, x = games.screen.width/2, y = games.screen.height/2) games.screen.add(self.ship)
def play(self): """ Start Game """ # destroy menu self.playBtn.destroy() self.instructionsBtn.destroy() self.main_menu.destroy() # muted? self.muted = 0 # load sounds self.coinSound = games.load_sound("sounds/coin.wav") self.purchaseSound = games.load_sound("sounds/ChaChing.wav") self.errorSound = games.load_sound("sounds/button.wav") self.burgerSound = games.load_sound("sounds/plop.wav") self.burgerSound.set_volume(0.7) # load & play music games.music.load("sounds/TropicalMusic.wav") pygame.mixer.music.set_volume(0.7) games.music.play(-1) # set money self.money = 50 # set lives self.lives = 4 # set number of pets self.numPets = 0 # burger size self.burgerSize = 1 # create live icons self.live1 = LiveIcon(game = self) games.screen.add(self.live1) self.live2 = LiveIcon(game = self, x = 80) games.screen.add(self.live2) self.live3 = LiveIcon(game = self, x = 125) games.screen.add(self.live3) self.live4 = LiveIcon(game = self, x = 170) games.screen.add(self.live4) # create quit btn quitBtn = QuitBtn(game = self) games.screen.add(quitBtn) # mute button muteBtn = MuteBtn(game = self) games.screen.add(muteBtn) # create top coin (to represent score) tCoin = TopCoin() games.screen.add(tCoin) # create money display self.moneyDisplay = games.Text(value = self.money, size = 40, color = color.white, top = 20, right = games.screen.width - 70, is_collideable = False) games.screen.add(self.moneyDisplay) # create bert btn bertBtn = BertBtn(game = self) games.screen.add(bertBtn) # create kasha btn kashaBtn = KashaBtn(game = self) games.screen.add(kashaBtn) # create pentalope btn pentalopeBtn = PentalopeBtn(game = self) games.screen.add(pentalopeBtn) # create garlyn btn garlynBtn = GarlynBtn(game = self) games.screen.add(garlynBtn) # create burger btn burgerBtn = BurgerBtn(game = self) games.screen.add(burgerBtn) # create first pet pet1 = Bert(game = self) games.screen.add(pet1) # create second pet (start in random place away from edges) pet2 = Bert(game = self, x = random.randint(200,games.screen.width - 150), y = random.randint(200,games.screen.height - 150)) games.screen.add(pet2) # create player self.the_player = Player(game = self) games.screen.add(self.the_player) games.mouse.is_visible = False
board.loadBack('level1.map') board.setBoard('level1.units') images = [] units = [] act = 0 inactive = 1 screen_w = pygame.display.Info().current_w screen_h = pygame.display.Info().current_h CONST_TILE_SIZE = 60 CONST_SIDE_PANELS = 150 games.init(screen_width = (board.getWidth() * CONST_TILE_SIZE + CONST_SIDE_PANELS * 2), screen_height = (board.getHeight() * CONST_TILE_SIZE), fps = 50) print(os.getcwd()) explosion = games.load_sound('sounds/Flashbang-Kibblesbob-899170896.wav') #games.init(screen_width = (board.getLength() * 60), screen_height = (1500), fps = 50) mouse = games.Mouse() class HighlightBox(games.Sprite): def __init__(self, x, y): """ Draw a rounded rect onto a surface and use that surface as the image for a sprite. The surface is 80% transparent, so it seems like the unit is highlighted. RoundedRect equations from http://pygame.org/project-AAfilledRoundedRect-2349-.html """ radius = 0.4 surf = pygame.Surface((CONST_TILE_SIZE,CONST_TILE_SIZE), pygame.SRCALPHA, 32)
def update(self): choice = randint(0,1) if self.delay > 0: self.delay -= 1 if games.keyboard.is_pressed(games.K_a) and self.both_alive and self.delay == 0: self.enemyHP = self.enemy.health self.user.attack(self.enemy) self.delay = self.DELAY damage = self.enemyHP - self.enemy.health self.loss(damage, self.enemy.enemyX, self.enemy.enemyY) self.attacked = True self.commentary(self.user.action, self.delay) self.enemy.shake = True self.attackSound = games.load_sound(self.user.sound) self.attackSound.play() if games.keyboard.is_pressed(games.K_s) and self.both_alive and self.delay == 0: self.enemyHP = self.enemy.health self.user.special(self.enemy) self.delay = self.DELAY damage = self.enemyHP - self.enemy.health self.loss(damage, self.enemy.enemyX, self.enemy.enemyY) self.attacked = True self.commentary(self.user.action, self.delay) self.enemy.shake = True self.attackSound = games.load_sound(self.user.sound) self.attackSound.play() if self.both_alive and self.attacked: if self.delay == 0: self.userHP = self.user.health if choice == 0: self.enemy.attack(self.user) else: self.enemy.special(self.user) damage = self.userHP - self.user.health self.loss(damage, self.user.x, self.user.y) attackSound = games.load_sound(self.enemy.sound) attackSound.play() self.attacked = False self.delay = self.DELAY try: action2 = self.enemy.action2 except: action2 = "" self.commentary(self.enemy.action, self.delay, action2) self.shake = True if self.shake: self.count -= 1 if self.count >= 0: if self.left: self.x += 10 if self.x == self.XPOS - 100: self.left = True else: self.x -= 10 if self.x == self.XPOS + 100: self.left = False else: self.shake = False self.count = 10 if games.keyboard.is_pressed(games.K_F1): self.txt = games.Message(value = "a = attack " +"s = special " +"F1 = help " +"ESC = exit", size = 25, color = color.white, x = games.screen.width/2, y = games.screen.height -20, lifetime = 250) games.screen.add(self.txt) if games.keyboard.is_pressed(games.K_ESCAPE): self.quit() if self.user.alive: self.userHealth.value = "health: " + str(self.user.health) else: self.userHealth.value = "Dead" self.end_game("You lost") if self.enemy.alive: self.enemyHealth.value = "health: " + str(self.enemy.health) else: self.enemyHealth.value = "Dead" self.end_game("You Won!")
#Sound and Music #Demos playing sound and music files from livewires import games games.init(screen_width = 640, screen_height = 480, fps = 50) #load a sound file missile_sound = games.load_sound("../Res/missile.wav") #load a music file games.music.load("../Res/theme.mid") choice = None while choice != "0": print( """ Sound and Music 0 - Quit 1 - Play missile sound 2 - Loop missile sound 3 - Stop missile sound 4 - Play theme music 5 - Loop theme music 6 - Stop theme music """ )
def __init__(self, game, x, y): super(Goal, self).__init__(image = Goal.image, x = x, y = y) self.game = game self.sound = games.load_sound("resources\\goal.wav")
def __init__(self, game, x, y): super(Player, self).__init__(image = Player.image, x = x, y = y) self.game = game self.sound = games.load_sound("resources\\death.wav")
# Sound and Music # Demonstrates playing sound and music files from livewires import games games.init(screen_width = 640, screen_height = 480, fps = 50) # load a sound file missile_sound = games.load_sound("missile.wav") # load musec file games.music.load("theme.mid") choice = None while choice != "0": print( """ Sound a Music 0 - Quit 1 - Play missile sound 2 - Loop missile sound 3 - Stop missile soun 4 - Play theme music 5 - Loop theme music 6 - Stop theme music """) choice = str(input("Choice: ")) print("You choose", choice)
__author__ = 'Vitaha' from livewires import games, color #screen initiation games.init(screen_width = 640, screen_height = 640, fps = 50) sound = games.load_sound('ping_pong_8bit_plop.wav') class Rocket(games.Sprite): """ping-pong rocket""" image = games.load_image('rocket.bmp') score = 0 #score number when need to change difficulty cycle = 20 def __init__(self, ball): """rocket constructor""" super(Rocket, self).__init__(image = Rocket.image, x = games.mouse.x, bottom = games.screen.height) #game score initiation self.score = games.Text(value = Rocket.score, size = 25, color = color.black, top = 5, right = games.screen.width - 10) games.screen.add(self.score) self.ball = ball def update(self):