Example #1
0
    def main(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit(0)
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit(0)

            self.delta += self.clock.tick() / 1000
            while self.delta > 1 / self.tps_max:
                self.tick()
                self.delta -= 1 / self.tps_max

            ### Collisions detector
            if self.collisions_detector(self.player.x, self.player.y,
                                        self.enemy.e_skin_rect.x,
                                        self.enemy.e_skin_rect.y, 32,
                                        32) == True:
                self.player.points += 1
                self.difficulty_counter += 1
                self.x = random.randint(1, self.WIDTH - 32)
                self.enemy = Enemy(self, self.x)
            ###
            # Score counter

            # End of map enemy action
            if self.enemy.e_skin_rect.y > self.HEIGHT:
                self.x = random.randint(1, self.WIDTH - 32)
                self.enemy = Enemy(self, self.x)
                self.player.hp -= 1

            # Break loop statement
            if self.player.is_alive() == False:
                self.point_buff = self.player.points
                self.player.default_valuse()
                self.difficulty = 5
                self.game_over_screen()

            # Change difficulty
            if self.difficulty_counter == 5:
                self.difficulty += 1.5
                self.difficulty_counter = 0

            # Painting
            self.draw()
            pygame.display.update()
Example #2
0
    def start(self):
        pygame.key.set_repeat(20)
        while True:
            for player in self.players:
                player.get_action()

                if player.tank.state == player.tank.STATE_DESTROYED:
                    self.players.remove(player)
                    for enemy in self.enemies:
                        enemy.kill()

                    self.text_format_draw('Game OVER', YELLOW, WIDTH / 2,
                                          HEIGHT / 8 + 250, self.font, -1, -2)
                    self.show_menu()

                if self.mode == 'Multi Player' and player.ptype == 'local':
                    if player.action != 'IDLE':
                        self.network.send_action(player)

            self.update_screen()
            self.timer.tick(FPS)

            if self.mode == 'Multi Player':
                continue

            for enemy in self.enemies:
                enemy.get_action(self.players)

            if len(self.enemies) == 0:
                # self.no_enemies += 1
                for _ in range(self.no_enemies):
                    Enemy(self.enemies)
Example #3
0
 def drop_enemies(self,screen_width):
     delay = random.random()
     if len(self.enemy_list) < self.max_enemies and delay < self.delay:
         x_pos = random.randint(0,screen_width)
         y_pos = 0
         enemy = Enemy(x_pos,y_pos)
         enemy_list.append(enemy)
Example #4
0
    def __init__(self, master=None):
        super().__init__(master)

        self.player = Player("Player")
        self.player.assignEnemy(Enemy("Slime", 5, 5, 10))

        self.pack()
        self.create_widgets()
Example #5
0
 def test_init_magic(self):
     magic = Magic(title="recover", category="big")
     self.assertEqual(magic.title, "recover")
     self.assertEqual(magic.category, "big")
     enemy = Enemy(name="yangshuai", weight=100, hp=50, mp=100)
     magic.effect(enemy)
     self.assertEqual(enemy.hp, 100)
     self.assertEqual(enemy.mp, 80)
Example #6
0
 def drop_enemies(self, screen_width):
     delay = random.random()
     if len(self.enemy_list
            ) < self.max_enemies and delay < self.delay:  # spawn with delay
         random_x = random.randint(0, screen_width)
         y_pos = 0
         enemy = Enemy(random_x, y_pos)
         self.enemy_list.append(enemy)
Example #7
0
    def __init__(self):
        pygame.init()

        # Constans
        self.WIDTH = 640
        self.HEIGHT = 480
        self.resolution = (self.WIDTH, self.HEIGHT)
        self.tps_max = 60.0
        self.delta = 0.0
        self.bg = pygame.image.load('pictures\\background.png')

        # Window setup
        self.screen = pygame.display.set_mode(self.resolution)
        pygame.display.set_caption('Catch a Bottle!')
        self.screen.blit(self.bg, (0, 0))

        # Clock setup
        self.clock = pygame.time.Clock()

        # Sounds setup
        self.catch_sound = pygame.mixer.Sound('sounds\catch.wav')
        self.game_over_sound = pygame.mixer.Sound('sounds\gameover.wav')

        # Game objects
        self.x = random.randint(1, self.WIDTH - 32)
        self.difficulty = 5
        self.difficulty_counter = 0
        self.point_buff = 0

        self.player = Player(self)
        self.player.set_image('character.png')
        self.enemy = Enemy(self, self.x)

        # Colors
        self.black = (0, 0, 0)
        self.white = (255, 255, 255)

        self.start_screen()
Example #8
0
    def start(self):

        self.background = pygame.Surface((self.WIDTH, self.HEIGHT))
        self.background = self.background.convert()
        self.background.fill(BLACK)
        self.font = pygame.font.SysFont(None, 28)
        self.FONT = pygame.font.SysFont(None, 60)

        self.screen.blit(self.background, (0, 0))

        pygame.display.flip()
        
        #Create shelters
        for i in range(50,800,200):
            self.create_shelters(i, 400)

        #Create enemies
        enemy_x = 100
        enemy_y = 50
        for i in range(5):
            for j in range(10):
                self.enemies.append(Enemy(enemy_x, enemy_y))
                enemy_x += 30
            enemy_x = 100
            enemy_y += 30


        while True:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
            
            keys = pygame.key.get_pressed()
            if keys[pygame.K_LEFT]:
                self.playerShip.moveLeft()
            if keys[pygame.K_RIGHT]:
                self.playerShip.moveRight()
            if keys[pygame.K_SPACE] and self.lazer.kd == 0:
                self.lazer.x = self.playerShip.x + (self.playerShip.width//2)
                self.lazer.y = self.playerShip.y
                self.lazer.color = (0, 255, 0)
                self.lazer.kd = 1

            self.update()

            self.draw()
Example #9
0
def main():
    gameState = True
    while gameState:
        if (app.player.isAlive == False):
            print("Game Over")
            gameState = False
        else:
            app.label_stats.configure(app.label_stats_enemy,
                                      text="{} : LVL {} - HP : {}".format(
                                          app.player.name, app.player.lvl,
                                          app.player.hp))

        if (app.player.enemy):
            app.label_stats_enemy.configure(
                app.label_stats_enemy,
                text="\nName : {}\n\nHP : {}".format(app.player.enemy.name,
                                                     app.player.enemy.hp))
        else:
            app.player.assignEnemy(Enemy("Slime", 5, 5, 10))
Example #10
0
 def handle_events(self):
     for event in pg.event.get():
         if event.type == pg.QUIT:
             self.game_state = GameState.ENDED
         #Shoots a Bullet in Direction of Mouse Click
         if event.type == pg.MOUSEBUTTONDOWN:
             x, y = pg.mouse.get_pos()
             x = (x / 10)
             y = (y / 10)
             x_player = self.player.get_x()
             y_player = self.player.get_y()
             b = Bullet(x, y, x_player, y_player, cg.SPEED)
             bullets.append(b)
         #Random Chance to Create Enemy Somewhere on Map
         if random.randint(0, 50) == 15:
             x = random.randint(0, (cg.SCREEN_WIDTH / 10))
             y = random.randint(0, (cg.SCREEN_HEIGHT / 10))
             x_player = self.player.get_x()
             y_player = self.player.get_y()
             e = Enemy(x, y, x_player, y_player, 2)
             enemies.append(e)
     self.player.move()
def main():
    """ Main Program """
    pygame.init()

    # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)
    bounds = screen.get_rect()
    pygame.display.set_caption("Super Alien Assault!")

    # Load the sound mixer:
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    # This is supposed to help stop sound lag

    # Create the player
    player = Player(bounds.center, bounds)
    player_grp = GroupSingle(player)

    # Create an enemy
    enemies = pygame.sprite.Group()

    # Create all the levels
    lindex = random.randrange(3, 9)

    level_list = []
    level_list.append(levels.Level_01(player))
    level_list.append(levels.Level_02(player))
    level_list.append(levels.Level_03(player))
    for i in range(lindex):
        level_list.append(levels.Level_01(player))
        level_list.append(levels.Level_02(player))
        level_list.append(levels.Level_03(player))

    # Initialize variables
    score = 0
    spawn_counter = 0
    tween_diff = 1

    # Select the font to use
    font = pygame.font.SysFont("calibri", 48)

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    # List of each block
    block_list = pygame.sprite.Group()

    # Set current level for player and inital x,y position
    player.level = current_level
    player.rect.x = 340
    player.rect.y = 200

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # Play "Hot Nights" by Beardmont / Three Chain Links
    # Available under Creative Commons attribution license from:
    # https://soundcloud.com/beardmont
    pygame.mixer.music.load('HotNights.ogg')
    pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
    pygame.mixer.music.play()

    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            elif event.type == pygame.constants.USEREVENT:
                # This event is triggered when the song stops playing.
                #
                # Next, play "Happiest Days" by Beardmont / Three Chain Links
                # Available under Creative Commons attribution license from:
                # https://soundcloud.com/beardmont
                pygame.mixer.music.load('HappiestDays.ogg')
                pygame.mixer.music.play()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True
                if event.key == pygame.K_q:
                    done = True
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()
                if event.key == pygame.K_SPACE:
                    player.shoot()
                if event.key == pygame.K_r and not player.alive():
                    main()

            elif event.type == pygame.KEYUP:

                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()

        # Update items in the level
        current_level.update()
        player_grp.update()
        player.bullets.update()
        player.bulletcasings.update()
        enemies.update()

        # Messing around with easing the enemy spawn counter
        # They should gradually trickle in at first and then build
        # to a flood of enemies then recede kind of like a tide
        spawn_counter += (101 - spawn_counter) * .1
        if spawn_counter >= 100:
            n = random.randrange(3)
            for i in range(n):
                x = random.randint(900, 1000)
                y = random.randint(100, 520)
                enemy = Enemy((x, y))
                enemies.add(enemy)
            spawn_counter = 0

        # Collision between player and enemies results in player death
        groupcollide(player_grp, enemies, True, False)

        # Add 1 point to score for every enemy the player kills
        for enemy in groupcollide(enemies, player.bullets, True, True):
            if player.alive():
                score += 1

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.x >= 310:
            diff = player.rect.x - 310
            # add some tweening/easing for momentum
            tween_diff += (diff - tween_diff) * .1
            player.rect.x = 310
            current_level.shift_world(int(-tween_diff))
            # also adjust enemies and bulletcasings by the world shift
            for enemy in enemies:
                enemy.rect.x += (int(-tween_diff))
            for bulletcasing in player.bulletcasings:
                bulletcasing.rect.x += (int(-tween_diff))

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.x <= 290:
            diff = 290 - player.rect.x
            # add some tweening/easing for momentum
            tween_diff += (diff - tween_diff) * .1
            player.rect.x = 290
            current_level.shift_world(int(tween_diff))
            # also adjust enemies and bulletcasings by the world shift
            for enemy in enemies:
                enemy.rect.x += (int(tween_diff))
            for bulletcasing in player.bulletcasings:
                bulletcasing.rect.x += (int(tween_diff))

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list) - 1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                player.level = current_level

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        player_grp.draw(screen)
        player.bullets.draw(screen)
        player.bulletcasings.draw(screen)
        enemies.draw(screen)

        # Blit the current score
        score_text = font.render("Score: %08d" % score, True, constants.PEACH)
        screen.blit(score_text, (5, 5))

        # If player dies, blit the respawn menu
        if not player.alive():
            gameover = font.render("Press R to Respawn or ESC to Quit", True,
                                   constants.PEACH)
            rect = gameover.get_rect()
            rect.center = screen.get_rect().center
            screen.blit(gameover, rect)

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        # Limit to 60 frames per second
        clock.tick(60)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
Example #12
0
 def test_ini_gongji(self):
     hero = Hero(name='lilei', hp=100, weight=100, att=100)
     enemy = Enemy(name='elong', hp=1000, weight=20, att=150, def_2=50)
     hero.attack(enemy)
     self.assertEqual(enemy.hp, 750)
Example #13
0
 def test_ini_attack(self):
     hero = Hero(name='casper', hp=100)
     enemy = Enemy(name='sp', hp=100, weight=100)
     hero.attack(enemy)
     self.assertEqual(enemy.hp, 100)
Example #14
0
 def test_init_enemy(self):
     enemy = Enemy(name='goblin1', hp=100, weight=70)
     self.assertEqual(enemy.name, 'goblin1')
     self.assertEqual(enemy.hp, 100)
     self.assertEqual(enemy.weight, 70)
import time
from screen import Screen
from player import Hero, Enemy
from obstacle import Firebeam, Coin, Magnet
from initialisations import initialiseFirebeams, initialiseCoins, initialiseMagnets
from input import Get, input_to

total_time = 100
refresh_time = 0.05
screen = Screen(1000)
mandalorian = Hero(screen, screen.getScreenwidth() / 4, screen.getScreenheight() - 1, refresh_time)
firebeams = initialiseFirebeams(screen)
coins = initialiseCoins(screen)
magnets = initialiseMagnets(screen)
boss = Enemy(screen, screen.getGamewidth() - 2, screen.getScreenheight() - 1)
bullets = []
get = Get()
input_taken = 0
start_time = time.time()
previous_time = start_time
while True:
	current_time = time.time()
	time_remaining = total_time - time.time() + start_time
	if time_remaining < 0:
		mandalorian.gameOver(mandalorian)
	if current_time - previous_time >= refresh_time:
		print( "\033[0;0H" )
		screen.printScreen(mandalorian, time_remaining)
		previous_time = time.time()
		input_taken = 0
	input = input_to(get, refresh_time)
Example #16
0
class Game(object):
    def __init__(self):
        pygame.init()

        # Constans
        self.WIDTH = 640
        self.HEIGHT = 480
        self.resolution = (self.WIDTH, self.HEIGHT)
        self.tps_max = 60.0
        self.delta = 0.0
        self.bg = pygame.image.load('pictures\\background.png')

        # Window setup
        self.screen = pygame.display.set_mode(self.resolution)
        pygame.display.set_caption('Catch a Bottle!')
        self.screen.blit(self.bg, (0, 0))

        # Clock setup
        self.clock = pygame.time.Clock()

        # Sounds setup
        self.catch_sound = pygame.mixer.Sound('sounds\catch.wav')
        self.game_over_sound = pygame.mixer.Sound('sounds\gameover.wav')

        # Game objects
        self.x = random.randint(1, self.WIDTH - 32)
        self.difficulty = 5
        self.difficulty_counter = 0
        self.point_buff = 0

        self.player = Player(self)
        self.player.set_image('character.png')
        self.enemy = Enemy(self, self.x)

        # Colors
        self.black = (0, 0, 0)
        self.white = (255, 255, 255)

        self.start_screen()

    # Main loop
    def main(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit(0)
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit(0)

            self.delta += self.clock.tick() / 1000
            while self.delta > 1 / self.tps_max:
                self.tick()
                self.delta -= 1 / self.tps_max

            ### Collisions detector
            if self.collisions_detector(self.player.x, self.player.y,
                                        self.enemy.e_skin_rect.x,
                                        self.enemy.e_skin_rect.y, 32,
                                        32) == True:
                self.player.points += 1
                self.difficulty_counter += 1
                self.x = random.randint(1, self.WIDTH - 32)
                self.enemy = Enemy(self, self.x)
            ###
            # Score counter

            # End of map enemy action
            if self.enemy.e_skin_rect.y > self.HEIGHT:
                self.x = random.randint(1, self.WIDTH - 32)
                self.enemy = Enemy(self, self.x)
                self.player.hp -= 1

            # Break loop statement
            if self.player.is_alive() == False:
                self.point_buff = self.player.points
                self.player.default_valuse()
                self.difficulty = 5
                self.game_over_screen()

            # Change difficulty
            if self.difficulty_counter == 5:
                self.difficulty += 1.5
                self.difficulty_counter = 0

            # Painting
            self.draw()
            pygame.display.update()

    def collisions_detector(self, ply_x, ply_y, obj_x, obj_y, obj_w, obj_h):
        if ply_y < obj_y + obj_h:
            if ply_x > obj_x and ply_x < obj_x + obj_w or ply_x + 42 > obj_x and ply_x + 42 < obj_x + obj_w:
                pygame.mixer.Sound.play(self.catch_sound)
                return True

    def quit_game(self):
        pygame.quit()
        quit()

    def tick(self):
        self.player.move()
        self.enemy.move(self.difficulty)

    def draw(self):
        self.screen.blit(self.bg, (0, 0))
        self.player.draw()
        self.enemy.draw()
        self.print_score(self.player.points)
        self.print_lives(self.player.hp)

    ### Scenes
    def start_screen(self):
        while True:
            for self.event in pygame.event.get():
                if self.event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

            # Load and set imaga as background
            start_background = pygame.image.load('pictures\\menu.png')
            self.screen.blit(start_background, (0, 0))

            # START button
            self.button(100, self.HEIGHT / 2, 'start_button.png',
                        'start_button_ac.png', self.main)
            # EXIT button
            self.button(self.WIDTH - 200, self.HEIGHT / 2, 'end_button.png',
                        'end_button_ac.png', self.quit_game)

            pygame.display.update()

    def game_over_screen(self):
        pygame.mixer.music.stop()
        pygame.mixer.Sound.play(self.game_over_sound)

        while True:
            for self.event in pygame.event.get():
                if self.event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

            # Load and set imaga as background
            start_background = pygame.image.load('pictures\\game_over.png')
            self.screen.blit(start_background, (0, 0))

            # RESET button
            self.button(self.WIDTH / 2 - 50, self.HEIGHT / 2 + 10,
                        'reset_button.png', 'reset_button_ac.png',
                        self.start_screen)

            font = pygame.font.SysFont(None, 30)
            text = font.render(
                'Your finale score is ' + str(self.point_buff) + ' bottles!',
                True, (0, 255, 0))
            self.screen.blit(text, (80, self.HEIGHT / 2 + 80))

            pygame.display.update()

    ###

    # Buttons drawing and events loop
    def button(self, x, y, image, active_img, action=None):
        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()

        if (x + 100) > mouse[0] > x and (y + 50) > mouse[1] > y:
            skin = pygame.image.load('pictures\\' + active_img)

            if click[0] == 1 and action != None:
                action()
        else:
            skin = pygame.image.load('pictures\\' + image)

        self.screen.blit(skin, (x, y))

    def print_score(self, count):
        font = pygame.font.SysFont(None, 30)
        text = font.render('You caught ' + str(count) + ' bottles!', True,
                           self.white)

        self.screen.blit(text, (0, 0))

    def print_lives(self, count):
        font = pygame.font.SysFont(None, 30)
        text = font.render('Lives: ' + str(count), True, self.white)

        self.screen.blit(text, (0, 31))
Example #17
0
    def show_menu(self):
        pygame.key.set_repeat(0)
        self.no_enemies = 2
        selected = 1
        self.draw_menu(selected)
        game_sound.menu_music()
        self.level.load_level()

        self.active_menu = 'Main menu'
        self.start_game = False

        self.players = []

        while True:
            no_entries = {
                'Main menu': 4,
                'Multi-player menu': 2,
                'Show connected clients': 3,
                'List available servers': len(self.available_servers)
            }

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.network.allowconnection = False
                    self.network.server_flag = False
                    self.network.listen = False
                    pygame.quit()

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        self.active_menu = 'Main menu'
                        self.network.reset()

                    if event.key == pygame.K_m:
                        game_sound.mute_toggle()

                    if event.key == pygame.K_UP and selected > 1:
                        selected -= 1

                    elif event.key == pygame.K_DOWN and selected < no_entries[
                            self.active_menu]:
                        selected += 1

                    if event.key == pygame.K_RETURN:
                        # print(selected)
                        if self.active_menu == 'Main menu':
                            if selected == 1:
                                self.mode = 'Single Player'
                                self.start_game = True
                                # reverting back to set-repeat 10

                            elif selected == 2:
                                self.mode = 'Multi Player'
                                self.active_menu = 'Multi-player menu'
                                selected = 1

                            elif selected == 4:
                                pygame.quit()

                        elif self.active_menu == 'Multi-player menu':
                            # print(selected)
                            if selected == 1:
                                self.network.start_broadcast()
                                self.active_menu = 'Show connected clients'

                            elif selected == 2:
                                selected = 1
                                self.network.start_listen_server()
                                self.network.start_server()
                                self.active_menu = 'List available servers'

                        elif self.active_menu == 'List available servers':
                            p1 = Player('Player 2', 100)
                            self.add_player(p1)
                            self.network.join_server(p1, selected - 1)
                            # self.network.start_server()

                        elif self.active_menu == 'Show connected clients':
                            p1 = Player('Warrior', 100)
                            self.add_player(p1)
                            self.network.send_connected_player_info()

            # print('pass')
            if self.start_game:
                if self.mode == 'Single Player':
                    p1 = Player('Warrior', 100)
                    self.add_player(p1)
                    Enemy(self.enemies)
                    # Enemy(self.enemies)

                pygame.mixer.music.fadeout(2000)
                print('Game started')
                self.start()

            self.timer.tick(FPS)
            self.draw_menu(selected)