Exemplo n.º 1
0
 def move_to_heard(self):
     dino_1 = Dinosaur('T-rex', 40)
     dino_2 = Dinosaur('Raptor', 25)
     dino_3 = Dinosaur('Pterodactyl', 35)
     self.dinos.append(dino_1)
     self.dinos.append(dino_2)
     self.dinos.append(dino_3)
Exemplo n.º 2
0
 def create_herd(self):
     Dinosaur_1 = Dinosaur()
     Dinosaur_2 = Dinosaur()
     Dinosaur_3 = Dinosaur()
     self.herd_of_robots.append(Dinosaur_1)
     self.herd_of_robots.append(Dinosaur_2)
     self.herd_of_robots.append(Dinosaur_3)
Exemplo n.º 3
0
    def create_herd(self):
        dino1 = Dinosaur("Stegosaurus", 8)
        dino2 = Dinosaur("Raptor", 15)
        dino3 = Dinosaur("T-Rex", 50)

        self.dinosaurs.append(dino1)
        self.dinosaurs.append(dino2)
        self.dinosaurs.append(dino3)
Exemplo n.º 4
0
 def create_herd(self):
     self.dinosaur_herd = []
     dino1 = Dinosaur("Rex", "T-Rex", 120, 75, 300)
     dino2 = Dinosaur("Tony", "Triceratops", 75, 50, 275)
     dino3 = Dinosaur("Ed", "Raptor", 100, 100, 200)
     self.dinosaur_herd.append(dino1)
     self.dinosaur_herd.append(dino2)
     self.dinosaur_herd.append(dino3)
     for dino in self.dinosaur_herd:
         print(dino.name + " the " + dino.dinosaur_type)
     print(self.dinosaur_herd)
     return self.dinosaur_herd
Exemplo n.º 5
0
 def creat_herd(self):
     dino1 = Dinosaur()
     dino1.health = 100
     dino1.energy = 100
     dino2 = Dinosaur()
     dino2.health = 100
     dino2.energy = 100
     dino3 = Dinosaur()
     dino3.health = 100
     dino3.energy = 100
     self.dinosaurs.append(dino1)
     self.dinosaurs.append(dino2)
     self.dinosaurs.append(dino3)
Exemplo n.º 6
0
    def _create_fleet(self):
        """Create the cars"""
        # Create an alien and find the number of aliens in a rrow.
        dinosaur = Dinosaur(self)
        dinosaur_height = dinosaur.rect.height
        available_space_y = self.settings.screen_height - (2 * dinosaur_height)
        number_dinosaurs_y = available_space_y // (2 * dinosaur_height)

        # Create the first row of dino saurs
        for dinosaur_number in range(number_dinosaurs_y):
            dinosaur = Dinosaur(self)
            dinosaur.y = dinosaur_height + 2 * dinosaur_height * dinosaur_number
            dinosaur.rect.y = dinosaur.y

            self.dinosaurs.add(dinosaur)
Exemplo n.º 7
0
    def __init__(self, screen):
        """ 初始化 """
        self._screen = screen  # 屏幕画面
        self._gameState = GameState.start  # 游戏状态 0:开始画面; 1:游戏中; 2:游戏结束
        self._frameCount = 0  # 每个游戏状态的帧数计数
        self._score = Score(self)  # 分数系统

        # 游戏元素
        self._startScene = StartScene()
        self._gameoverScene = GameoverScene(self)
        self._dinosaur = Dinosaur(self)
        self._cactusGroup = pygame.sprite.RenderPlain()
        self._birdGroup = pygame.sprite.RenderPlain()
        self._terrian = Terrian(self)
        self._cloudGroup = pygame.sprite.RenderPlain()
        self._moon = Moon(self)
        self._starGroup = pygame.sprite.RenderPlain()

        # 控制难度的变量
        self._lastEnemyFrameCount = 0  # 上一次出现敌人的帧数计数
        self._curEnemeyProbability = Settings.enemyInitProbability  # x,当前每帧敌人出现的概率为1/x
        self._curEnemyMinFrameInterval = Settings.enemyInitMinFrameInterval  # 当前敌人最小帧数间隔
        self._curTerrianSpeed = Settings.terrianInitSpeed  # 当前地形移动速度

        # 控制环境的变量
        self._lastCloudFrameCount = Settings.cloudFrameInterval  # 上一次出现云的帧数计数
        self._isDay = True  # 是否白天
        self._dayNightFrame = Settings.dayNightChangeFrame  # 自从白天/黑夜开始的帧数,初始值不为0,因为开始无需昼夜交替
Exemplo n.º 8
0
    def __init__(self):
        pygame.display.set_caption('Dinosaur Game')
        self.clock = pygame.time.Clock()
        self.height = 400
        self.width = 700
        self.screen_res = [self.width, self.height]
        self.screen = pygame.display.set_mode(self.screen_res,
                                              pygame.HWSURFACE, 32)
        self.white = [222, 222, 222]
        self.black = [0, 0, 0]
        self.screen.fill(self.white)
        self.font = pygame.font.SysFont("Calibri", 16)
        self.ground_y = 250
        self.end = False
        self.obj_speed = 2.5
        self.dinosaur = Dinosaur(self)
        self.cactus_group = pygame.sprite.Group()
        self.collide = False
        self.object_period = 5
        self.current_obj = None
        self.score = 0
        self.add_speed = 5
        self.current_cloud = None

        while not self.end:
            self.loop()
Exemplo n.º 9
0
def run_game():
    tick = 0
    while 1923014810498219048120948:
        if game_settings.game_active:
            game_func.check_events(screen, game_settings, squares, characters,
                                   bullets)
            # screen.fill(game_settings.bg_color);
            tick += 1
            if tick % 30 == 0 or tick == 1:
                dinosaurs.add(Dinosaur(screen, game_settings))

            dinosaur_got_shot = groupcollide(dinosaurs, bullets, False, False)
            character_got_hit = groupcollide(dinosaurs, characters, False,
                                             True)
            for dinosaur in dinosaur_got_shot:
                # print dinosaur;
                if dinosaur.yard_row == dinosaur_got_shot[dinosaur][
                        0].yard_row:
                    bullets.remove(dinosaur_got_shot[dinosaur][0])
                    dinosaur.hit(1)
                    if (dinosaur.health <= 0):
                        dinosaurs.remove(dinosaur)
                        # os.system("say ow")
                        game_settings.dinosaur_in_row[dinosaur.yard_row] -= 1

        game_func.update_screen(screen, game_settings, background, dinosaurs,
                                squares, characters, bullets, tick)
        pygame.display.flip()
Exemplo n.º 10
0
 def __init__(self):
     self.dinosaur = Dinosaur(win, 500 - 100, 450)
     self.bg_colour = win.fill((255, 255, 255))
     self.cactuses = [Cactus(win, 1000), Cactus(win, 1000)]
     self.bg = pygame.image.load("imgs/floor.png")
     self.timer = time.time()
     self.score = -1
Exemplo n.º 11
0
    def __init__(self):
        dinosaur_1 = Dinosaur()
        dinosaur_1.type = 'Indominus-Rex'
        dinosaur_1.health = 100
        dinosaur_1.energy = 100
        dinosaur_1.attack_power = 10

        dinosaur_2 = Dinosaur()
        dinosaur_2.type = 'Triceratops'
        dinosaur_2.health = 100
        dinosaur_2.energy = 100
        dinosaur_2.attack_power = 15

        dinosaur_3 = Dinosaur()
        dinosaur_3.type = 'T-Rex'
        dinosaur_3.health = 150
        dinosaur_3.energy = 150
        dinosaur_3.attack_power = 25
Exemplo n.º 12
0
 def init_game(self):
     # 游戏结束
     self.over = False
     # 创建滚动地图对象
     self.bg = RollBackground()
     # 创建恐龙对象
     self.dinosaur = Dinosaur()
     # 创建障碍物组合
     self.obstacles = ObstacleGroup()
Exemplo n.º 13
0
 def create_herd_custom_amount(self, amount):
     self.dinosaurs = []
     i = 1
     while i <= amount:
         self.dinosaurs.append(
             Dinosaur(f'Dinosaur {i}', random.randint(15, 30)))
         if 20 < self.dinosaurs[i - 1].attack_power <= 25:
             self.dinosaurs[i - 1].energy_drain = -15
         elif self.dinosaurs[i - 1].attack_power > 25:
             self.dinosaurs[i - 1].energy_drain = -20
         i += 1
Exemplo n.º 14
0
 def create_herd(self):
     i = 0
     while i < 3:
         print(f"If Dinosaur {i+1} is a T-Rex press 1:")
         print(f"If Dinosaur {i+1} is a Triceratops press 2:")
         print(f"If Dinosaur {i+1} is a Stegosaurus press 3:")
         selector = {"1": "T-Rex", "2": "Triceratops", "3": "Stegosaurus"}
         self.dinos.append(
             Dinosaur(selector[input()],
                      input(f"What is Dinosaur {i+1}'s Attack Power?")))
         i += 1
Exemplo n.º 15
0
    def create_herd(self):
        dinosaur1 = Dinosaur()
        dinosaur1.type = 'raptor'
        dinosaur1.health = 20
        dinosaur1.energy = 10
        dinosaur1.attack_power = 5

        dinosaur2 = Dinosaur()
        dinosaur2.type = 'pterosaur'
        dinosaur2.health = 20
        dinosaur2.energy = 10
        dinosaur2.attack_power = 5

        dinosaur3 = Dinosaur()
        dinosaur3.type = 'triceratops'
        dinosaur3.health = 30
        dinosaur3.energy = 5
        dinosaur3.attack_power = 10

        dinos = [dinosaur1, dinosaur2, dinosaur3]
        return dinos
Exemplo n.º 16
0
 def reset_game(self):
     self.score = 0
     self.cont_enemies_x_level = 0
     self.over = False
     self.level = 0
     self.last_timestamp = time.time()
     self.enemies_list.empty()
     sprites_list_temp = pygame.sprite.Group()
     sprites_list_temp.add(enemy for enemy in self.sprites_list if enemy.__module__ != 'enemy' and enemy.__module__ != 'dinosaur')
     self.sprites_list = sprites_list_temp
     self.dino = Dinosaur()
     self.dino.walls = self.walls_list
     self.sprites_list.add(self.dino)
Exemplo n.º 17
0
    def __init__(self):
        """Initilize the game, and create game resources"""
        pygame.init()

        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Snap Strats")
        self.dinosaur = Dinosaur(self)
        self.car = Car(self)
        self.dinosaurs = pygame.sprite.Group()

        self._create_fleet()
Exemplo n.º 18
0
def handler(event, context):
    """
    The function to create a new dinosaur and store it into DynamoDB
    """
    dinosaur_dict = event.get('dinosaur', None)
    if not dinosaur_dict:
        print('No dinosaur provided.')
        return
    if not all(keys in dinosaur_dict for keys in
               ['name', 'diet', 'period', 'weight', 'armor', 'hybrid']):
        print('Missing dinosaur values.')
        return

    # Get dinosaur information from event
    dino_name = dinosaur_dict.get('name')
    dino_diet = dinosaur_dict.get('diet')
    dino_period = dinosaur_dict.get('period')
    dino_weight = dinosaur_dict.get('weight')
    dino_armor = dinosaur_dict.get('armor')
    dino_hybrid = dinosaur_dict.get('hybrid')

    # Create new dinosaur object
    new_dinosaur = Dinosaur(name=dino_name,
                            diet=dino_diet,
                            period=dino_period,
                            weight=dino_weight,
                            armor=dino_armor,
                            hybrid=dino_hybrid)

    # Store new dinosaur object in DynamoDB
    print(new_dinosaur.__dict__)
    response = dinosaurs_table.put_item(
        Item={
            'name': new_dinosaur.name,
            'diet': new_dinosaur.diet,
            'period': new_dinosaur.period,
            'attack': new_dinosaur.attack,
            'defense': new_dinosaur.defense,
            'life': new_dinosaur.life,
            'info': {
                'weight': new_dinosaur.weight,
                'armor': new_dinosaur.armor,
                'nature': new_dinosaur.nature,
                'hybrid': new_dinosaur.hybrid
            }
        })

    print('PutItem succeeded:')
    print(json.dumps(response, indent=2))
Exemplo n.º 19
0
def run_game():
    pygame.init()
    dino_settings = Settings()
    screen = pygame.display.set_mode((dino_settings.screen_width, dino_settings.screen_height))
    pygame.display.set_caption("dino")
    score = float(0)
    while True:
        ground = Ground(dino_settings, screen)
        dinosaur = Dinosaur(dino_settings, screen)
        clouds = Group()
        birds = Group()
        cactus = Group()
        gf.create_clouds(dino_settings, screen, clouds)
        gf.create_birds(dino_settings, screen, birds)
        gf.create_cactus(dino_settings, screen, cactus)
        sb = Scoreboard(dino_settings, screen)
        while not dinosaur.dead:
            gf.check_events(dinosaur)
            ground.update()
            dinosaur.update()
            score += 3
            dino_settings.score = int(score)
            sb.prep_score()
            gf.update_clouds(dino_settings, screen, clouds)
            gf.update_birds(dino_settings, screen, birds, dinosaur)
            gf.update_cactus(dino_settings, screen, cactus, dinosaur)
            gf.update_screen(dino_settings, screen, ground, clouds, dinosaur, cactus, birds, sb)
        while dinosaur.dead:
            exit_game = False
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_x, mouse_y = pygame.mouse.get_pos()
                    if button.rect.collidepoint(mouse_x, mouse_y):
                        exit_game = True
            if exit_game:
                if dino_settings.score > dino_settings.high_score:
                    dino_settings.high_score = dino_settings.score
                    sb.prep_high_score()
                dino_settings.score = 0
                score = 0
                break
            
            button = Button(dino_settings, screen)
            button.blitme()
            pygame.display.flip()
Exemplo n.º 20
0
 def __init__(self):
     self.score = 0
     self.cont_enemies_x_level = 0
     self.level = 0
     self.over = False
     self.pause = False
     self.messages = []
     self.sprites_list = pygame.sprite.Group()
     self.walls_list = pygame.sprite.Group()
     self.enemies_list = pygame.sprite.Group()
     self.define_borders()
     self.grown = Grown()
     self.sprites_list.add(self.grown.objects_list)
     self.dino = Dinosaur()
     self.dino.walls = self.walls_list
     self.sprites_list.add(self.dino)
     self.last_timestamp = time.time()
     self.next_level_timestamp = time.time()
    def eval_genomes(self, genomes, config):
        # Terminate if the user closed the window
        if self.has_exit:
            exit()

        # Increment the generation number
        self.generation += 1
        self.number_of_dinosaurs = len(genomes)

        # Set up the list of genomes
        self.neural_nets = []
        self.dinosaurs = []
        self.genomes = []

        # Set up the genomes
        for _, genome in genomes:
            genome.fitness = 0  # Start with fitness level of 0
            self.neural_nets.append(neat.nn.FeedForwardNetwork.create(genome, config))
            self.dinosaurs.append(Dinosaur(self.dinosaur_run_animation, 65, 45, batch=self.main_batch))
            self.genomes.append(genome)
        
        # Run the game
        pyglet.app.run()
Exemplo n.º 22
0
 def create_herd(self, team_size):
     dinosaur_list = ["T-Rex", "Raptor", "Triceratops"]
     dinosaurs = []
     # Loop to create robot fleet
     i = 0
     while i < team_size:
         x = random.randrange(0, 2)
         dino_type = dinosaur_list[x]
         dinosaur = Dinosaur(dino_type)
         dinosaurs.append(dinosaur)
         if dino_type == "T-Rex":
             dinosaur.health = random.randrange(80, 110, 10)
             dinosaur.attack_power = random.randrange(20, 30)
         elif dino_type == "Triceratops":
             dinosaur.health = random.randrange(50, 80, 5)
             dinosaur.attack_power = random.randrange(10, 20)
             dinosaur.energy = 100
         elif dino_type == "Raptor":
             dinosaur.health = random.randrange(30, 50, 5)
             dinosaur.attack_power = random.randrange(10, 15)
             dinosaur.energy = 200
         i += 1
     self.dinosaurs = dinosaurs
     pass
Exemplo n.º 23
0
 def create_herd(self):
     dinosaur1 = Dinosaur('Tyrannosaurus Rex', 100)
     dinosaur2 = Dinosaur('Triceratops', 50)
     dinosaur3 = Dinosaur('Velociraptor', 25)
     temp_list = [dinosaur1, dinosaur2, dinosaur3]
     return temp_list
Exemplo n.º 24
0
import pygame

from settings import Settings
from landscape import Landscape
from dinosaur import Dinosaur

pygame.init()
canvas = pygame.display.set_mode(Settings.screen_size)

landscape = Landscape(canvas)
dinosaur = Dinosaur(canvas, landscape)

clock = pygame.time.Clock()

done = False
while not done:
    canvas.fill((0, 0, 0))
    landscape.draw()
    dinosaur.draw()
    pygame.display.flip()
    landscape.update()
    clock.tick(10)
Exemplo n.º 25
0
from dinosaur import Dinosaur

dinosaur_one = Dinosaur()
dinosaur_two = Dinosaur()
dinosaur_three = Dinosaur()

dinosaur_herd = [dinosaur_one, dinosaur_two, dinosaur_three]


class Herd:

    def dinosaur_herd_health(self):
        herd_health = dinosaur_one.dinosaur_health
        herd_health += dinosaur_two.dinosaur_health
        herd_health += dinosaur_three.dinosaur_health
        if herd_health == 0:
            print("all dinosaurs are dead, robots win!")
        elif herd_health != 0:
            print(herd_health)
    def __init__(self, enable_neat=False, *args, **kwargs):
        # Inherit the pyglet window
        super().__init__(*args, **kwargs)

        # Save the configuration that determines if the NEAT algorithm is used
        self.enable_neat = enable_neat

        # Generate the font style
        pyglet.font.add_file('data/fonts/press_start_2p.ttf')
        pyglet.font.load("Press Start 2P")

        # Save and draw the FPS
        self.frame_rate = 1/60
        self.fps_display = FPSDisplay(self)
        self.fps_display.label.x = self.width - 10
        self.fps_display.label.y = 10
        self.fps_display.label.anchor_x = "right"
        self.fps_display.label.font_name = "Press Start 2P"
        self.fps_display.label.font_size = 20
        self.fps_display.label.color = (192, 192, 192, 192)

        # Set the FPS
        pyglet.clock.schedule_interval(self.update, self.frame_rate)

        # Control the horizontal velocity of the obstacles
        self.obstacle_velx = -600

        # Create batches
        self.bg_batch = pyglet.graphics.Batch()
        self.main_batch = pyglet.graphics.Batch()
        if self.enable_neat:
            self.neat_batch = pyglet.graphics.Batch()
        else:
            self.game_over_batch = pyglet.graphics.Batch()

        # Preload the images into memory and save them
        game_sprites = self.preload_image("sprites.png")
        self.terrain_img = game_sprites.get_region(2, 0, 2402, 27)
        self.dinosaur_run_animation = Animation.from_image_sequence(
            ImageGrid(
                game_sprites.get_region(1854, 33, 176, 95),
                1,
                2,
                item_width=88,
                item_height=96
            ),
            0.3,
            loop=True
        )
        self.dinosaur_duck_animation = Animation.from_image_sequence(
            ImageGrid(
                game_sprites.get_region(2203, 33, 240, 61),
                1,
                2,
                item_width=118,
                item_height=62
            ),
            0.3,
            loop=True
        )
        self.dinosaur_jump_img = game_sprites.get_region(1678, 33, 88, 95)
        self.dinosaur_collision_img = game_sprites.get_region(2030, 33, 88, 95)
        self.cacti_imgs = (
            game_sprites.get_region(446, 58, 34, 70),  # Small cacti 1
            game_sprites.get_region(480, 58, 68, 70),  # Small cacti 2
            game_sprites.get_region(548, 58, 102, 70), # Small cacti 3
            game_sprites.get_region(652, 32, 50, 98),  # Large cacti 1
            game_sprites.get_region(702, 32, 100, 98), # Large cacti 2
            game_sprites.get_region(802, 30, 150, 98), # Large cacti 3

        )
        self.bird_animation = Animation.from_image_sequence(
            ImageGrid(
                game_sprites.get_region(260, 48, 184, 80),
                1, 2, item_width=92, item_height=80
            ),
            0.3,
            loop=True
        )
        self.cloud_img = game_sprites.get_region(165, 100, 95, 28)
        self.moon_phases = cycle((
            game_sprites.get_region(1234, 47, 40, 82),
            game_sprites.get_region(1194, 47, 40, 82),
            game_sprites.get_region(1154, 47, 40, 82),
            game_sprites.get_region(1074, 47, 80, 82),
            game_sprites.get_region(1034, 47, 40, 82),
            game_sprites.get_region(994, 47, 40, 82),
            game_sprites.get_region(954, 47, 40, 82)
        ))
        self.reset_button_img = game_sprites.get_region(2, 63, 72, 65)

        # Score and label
        self.score = 0
        self.score_label = pyglet.text.Label(
            f"{self.score:05}",
            font_name="Press Start 2P",
            font_size=20,
            x=self.width - 10,
            y=self.height - 10,
            anchor_x="right",
            anchor_y="top",
            batch=self.bg_batch
        )

        # Game over label (only if the user plays the game manually)
        if not self.enable_neat:
            self.game_over_label = pyglet.text.Label(
                "G A M E  O V E R",
                font_name="Press Start 2P",
                font_size=30,
                x=self.width / 2,
                y=self.height / 2 + 100,
                anchor_x="center",
                anchor_y="center",
                batch=self.game_over_batch
            )
        
        # Initialize the sprites
        self.terrain_1 = GameSprite(
            self.terrain_img,
            0,
            50,
            velx=self.obstacle_velx,
            batch=self.bg_batch
        )
        self.terrain_2 = GameSprite(
            self.terrain_img,
            2400,
            50,
            velx=self.obstacle_velx,
            batch=self.bg_batch
        )
        self.moon = GameSprite(next(self.moon_phases), 2920, 275, velx=-20, batch=self.main_batch)
        self.clouds = [] # Elements will be randomly generated as the game progresses
        self.obstacles = [] # Elements will be randomly generated as the game progresses
        
        # Reset button is only available when the user plays manually
        if not self.enable_neat:
            self.reset_button = GameSprite(
                self.reset_button_img,
                564,
                150,
                batch=self.game_over_batch
            )
        
        # Generate the user's dinosaur if the user plays manually
        if not self.enable_neat:
            self.dinosaur = Dinosaur(self.dinosaur_run_animation, 65, 45, batch=self.main_batch)

            # Set variables to track user inputs
            self.trigger_duck = False
            self.trigger_jump = False

            # Keep track of any user collisions
            self.user_collision = False

        # Add a delays to control when events happen
        self.next_score_increment = 0.1
        self.next_cloud_spawn = 3 * random() + 1
        self.next_obstacle_spawn = 2 * random() + 1
        self.next_velocity_increase = 1

        # Set up the NEAT algorithm if true. Otherwise, let the user play manually
        if self.enable_neat:
            # Locate the NEAT configuration file
            config_file = os.path.join(os.path.dirname(__file__), 'config-feedforward.txt')

            # Configure the NEAT algorithm
            config = neat.config.Config(
                neat.DefaultGenome,
                neat.DefaultReproduction,
                neat.DefaultSpeciesSet,
                neat.DefaultStagnation,
                config_file
            )

            # Generate the population
            population = neat.Population(config)

            # Add a reporter to show progress in the terminal
            population.add_reporter(neat.StdOutReporter(True))
            population.add_reporter(neat.StatisticsReporter())

            # Generation label
            self.generation = -1
            self.generation_label = pyglet.text.Label(
                f"GENERATION: {self.generation:02}",
                font_name="Press Start 2P",
                font_size=20,
                x=10,
                y=self.height - 10,
                anchor_x="left",
                anchor_y="top",
                batch=self.neat_batch
            )

            # Number of dinosaurs label
            self.number_of_dinosaurs = 0
            self.number_of_dinosaurs_label = pyglet.text.Label(
                f"DINOSAURS: {self.number_of_dinosaurs:03}",
                font_name="Press Start 2P",
                font_size=20,
                x=10,
                y=self.height - 40,
                anchor_x="left",
                anchor_y="top",
                batch=self.neat_batch
            )
            # Run the NEAT algorithm and find the best "player"
            winner = population.run(self.eval_genomes, 25)
        else:
            # Run the main loop and play the game manually
            pyglet.app.run()
Exemplo n.º 27
0
def handler(event, context):
    """
    The function to fight two random dinosaurs from DynamoDB
    """
    dinosaur_carnivore_list = dinosaurs_table.scan(
        FilterExpression=Attr('diet').eq('carnivore'),
        ProjectionExpression='#name',
        ExpressionAttributeNames={ '#name': 'name' }
    )['Items']

    dinosaur_herbivore_list = dinosaurs_table.scan(
        FilterExpression=Attr('diet').eq('herbivore'),
        ProjectionExpression='#name',
        ExpressionAttributeNames={ '#name': 'name' }
    )['Items']
    
    carnivore = random.choice(dinosaur_carnivore_list)
    herbivore = random.choice(dinosaur_herbivore_list)

    dino_data_1 = dinosaurs_table.query(
        KeyConditionExpression=Key('name').eq(carnivore['name'])
    )['Items'][0]

    dino_data_2 = dinosaurs_table.query(
        KeyConditionExpression=Key('name').eq(herbivore['name'])
    )['Items'][0]

    dino_1 = Dinosaur(
        name=dino_data_1['name'],
        diet=dino_data_1['diet'],
        period=dino_data_1['period'],
        weight=dino_data_1['info']['weight'],
        armor=dino_data_1['info']['armor'],
        hybrid=dino_data_1['info']['hybrid'],
        nature=dino_data_1['info']['nature'], 
        attack=dino_data_1['attack'],
        defense=dino_data_1['defense'],
        life=dino_data_1['life']
    )

    dino_2 = Dinosaur(
        name=dino_data_2['name'],
        diet=dino_data_2['diet'],
        period=dino_data_2['period'],
        weight=dino_data_2['info']['weight'],
        armor=dino_data_2['info']['armor'],
        hybrid=dino_data_2['info']['hybrid'],
        nature=dino_data_2['info']['nature'], 
        attack=dino_data_2['attack'],
        defense=dino_data_2['defense'],
        life=dino_data_2['life']
    )

    battle_turns = 0
    print(f'A wild {dino_1.name} and {dino_2.name} encounter!')
    print('---------------------------------')
    print('THE HUNT HAS STARTED!')
    while (True):
        print('---------------------------------')
        print(f'Turn {battle_turns} status:')
        print(f'Dino 1: {dino_1.name}')
        print(f'Life  : {dino_1.life}')
        print(f'Dino 2: {dino_2.name}')
        print(f'Life  : {dino_2.life}')
        dino_2.update_life(dino_1.make_attack())
        if(dino_2.is_dead()):
           winner = dino_1
           loser = dino_2
           break
        dino_1.update_life(dino_2.make_attack())
        if(dino_1.is_dead()):
            winner = dino_2
            loser = dino_1
            break
        battle_turns += 1
    
    announce_winner(winner, loser)
Exemplo n.º 28
0
def battle_action():
    # NOTE: THIS REALLY SHOULD BE DONE USING A DATABASE OR AN ARRAY/LIST
    #       RATHER THAN SEPARATE INSTANCES OF  ROBOTS AND DINOSAURS.
    #       AN ARRAY/LIST WOULD BE MUCH MORE EFFICIENT
    # Assemble the robots
    print('\n================================')
    robot1 = Robot('Able', 50, 50, 'Phaser').robot_attr_list()
    robot2 = Robot('Baker', 50, 50, 'Phaser').robot_attr_list()
    robot3 = Robot('Sarge', 125, 100, '').robot_attr_list()

    robot_fleet = Fleet('Armageddon')
    robot_fleet.assign_member(robot3.name, robot3.attack_power, robot3.health)
    robot_fleet.assign_member(robot1.name, robot1.attack_power, robot1.health)
    robot_fleet.assign_member(robot2.name, robot2.attack_power, robot2.health)
    robot_fleet.fleet_status()

    # Assemble the dinosaurs
    print('\n================================')
    dinosaur1 = Dinosaur('Triceratops', 75, 30, 'Bash').dino_attr_list()
    dinosaur2 = Dinosaur('Velociraptor', 50, 100, 'Tail whip').dino_attr_list()
    dinosaur3 = Dinosaur('T-Rex', 100, 70, '').dino_attr_list()

    dinosaur_herd = Herd('R-r-raw-R!')
    dinosaur_herd.add_member(dinosaur3.dino_type, dinosaur3.attack_power, dinosaur3.health)
    dinosaur_herd.add_member(dinosaur1.dino_type, dinosaur1.attack_power, dinosaur1.health)
    dinosaur_herd.add_member(dinosaur2.dino_type, dinosaur2.attack_power, dinosaur2.health)
    dinosaur_herd.herd_status()

    # Create the battle field
    water_loo = Battlefield('Water Loo')
    water_loo.side1_name = robot_fleet.name
    water_loo.side2_name = dinosaur_herd.name
    water_loo.side1_points = robot_fleet.defense_points
    water_loo.side2_points = dinosaur_herd.defense_points

    # Now fight
    battle_ended = False
    counter = 0
    engagements = len(robot_fleet.members)
    water_loo.battle_status()
    print('\n\n ***** Battle commencing *****')
    detail_print = input('Do you wish to see the details? (y/n): ')
    while not battle_ended:
        side1_damage = 0
        side2_damage = 0
        damage1 = 0
        # battle strikes happen here...
        # Individual engagements (eg. 1 vs 1, 2 vs 2, 3 vs 3)
        if (robot1.health > 0 and robot1.power_level > 0) and (dinosaur1.health > 0 and dinosaur1.energy > 0):
            robot_attack_damage = make_an_attack(robot1.attack_power)
            dino_attack_damage = make_an_attack(dinosaur1.attack_power)
            dinosaur1.update_health(robot_attack_damage).update_energy(10)
            robot1.update_health(dino_attack_damage).update_power_level(10)
            if detail_print == 'y':
                print(f'Robot {robot1.name} hits {dinosaur1.dino_type} for {robot_attack_damage} damage '
                      f'and it has {dinosaur1.health} health '
                      f'and {dinosaur1.energy} energy left.')
                print(f'The {dinosaur1.dino_type} hits {robot1.name} for {dino_attack_damage} damage '
                      f'and it has {robot1.health} health '
                      f'and {robot1.power_level} power left.\n')
            side1_damage += dino_attack_damage
            side2_damage += robot_attack_damage
        else:
            # One member has been defeated, the other may or may not be left standing.
            engagements -= 1

        if (robot2.health > 0 and robot2.power_level > 0) and (dinosaur2.health > 0 and dinosaur2.energy > 0):
            robot_attack_damage = make_an_attack(robot2.attack_power)
            dino_attack_damage = make_an_attack(dinosaur2.attack_power)
            dinosaur2.update_health(robot_attack_damage).update_energy(10)
            robot2.update_health(dino_attack_damage).update_power_level(10)
            if detail_print == 'y':
                print(f'Robot {robot2.name} hits {dinosaur2.dino_type} for {robot_attack_damage} damage '
                      f'and it has {dinosaur2.health} health '
                      f'and {dinosaur2.energy} energy left.')
                print(f'The {dinosaur2.dino_type} hits {robot2.name} for {dino_attack_damage} damage '
                      f'and it has {robot2.health} health '
                      f'and {robot2.power_level} power left.\n')
            side1_damage += dino_attack_damage
            side2_damage += robot_attack_damage
        else:
            # One member has been defeated, the other may or may not be left standing.
            engagements -= 1

        if (robot3.health > 0 and robot3.power_level > 0) and (dinosaur3.health > 0 and dinosaur3.energy > 0):
            robot_attack_damage = make_an_attack(robot3.attack_power)
            dino_attack_damage = make_an_attack(dinosaur3.attack_power)
            dinosaur3.update_health(robot_attack_damage).update_energy(10)
            robot3.update_health(dino_attack_damage).update_power_level(10)
            if detail_print == 'y':
                print(f'Robot {robot3.name} hit the {dinosaur3.dino_type} for {robot_attack_damage} damage '
                      f'and it has {dinosaur3.health} health '
                      f'and {dinosaur3.energy} energy left.')
                print(f'The {dinosaur3.dino_type} hit robot {robot3.name} for {dino_attack_damage} damage '
                      f'and it has {robot3.health} health '
                      f'and {robot3.power_level} power left.\n')
            side1_damage += dino_attack_damage
            side2_damage += robot_attack_damage
        else:
            # One member has been defeated, the other may or may not be left standing.
            engagements -= 1

        water_loo.update_battle_status(side1_damage, side2_damage)
        if detail_print == 'y':
            water_loo.battle_status()
        counter += 1
        # Check to see if either side has been wiped out or at a tactical advantage
        battle_ended = water_loo.battle_results(counter, engagements, detail_print)
        # Tactical advantage equals all engagements are complete (0).
        if engagements == 0:
            battle_ended = True
        elif counter > 15:
            # The soldiers are too wimpy and their hearts are in not in the fight!
            print('Battle has stalemated. Troops are going home.')
            battle_ended = True
Exemplo n.º 29
0
 def create_herd(self):
     self.dinosaurs.append(Dinosaur('T-Rex', 30))
     self.dinosaurs.append(Dinosaur('Raptor', 15))
     self.dinosaurs.append(Dinosaur('Triceratops', 20))
Exemplo n.º 30
0
def main(genomes, config):
    global game_speed, x_pos_bg, y_pos_bg, points, obstacles, dinosaurs, ge, nets
    run = True
    clock = pygame.time.Clock()
    points = 0

    dinosaurs = []
    ge = []
    nets = []
    obstacles = []

    cloud = Cloud()
    game_speed = 40
    x_pos_bg = 0
    y_pos_bg = 380

    font = pygame.font.Font('freesansbold.ttf', 20)

    death_count = 0

    if AI_player:
        for genome_id, genome in genomes:
            dinosaurs.append(AI_Dino())
            ge.append(genome)
            net = neat.nn.FeedForwardNetwork.create(genome, config)
            nets.append(net)
            genome.fitness = 0
    else:
        dinosaurs.append(Dinosaur())

    def score():
        global points, game_speed
        points += 5
        if (points % 100 == 0) and (game_speed < 52):
            game_speed += 2

        text = font.render("Points: " + str(points), True, (0, 0, 0))
        textRect = text.get_rect()
        textRect.center = (1000, 40)
        SCREEN.blit(text, textRect)
        for g in ge:
            g.fitness += 2

    if AI_player:

        def statistics():
            global dinosaurs, game_speed, ge
            text_1 = font.render(f'Dinosaurs Alive:  {str(len(dinosaurs))}',
                                 True, (0, 0, 0))
            text_2 = font.render(f'Generation:  {pop.generation+1}', True,
                                 (0, 0, 0))
            text_3 = font.render(f'Game Speed:  {str(game_speed)}', True,
                                 (0, 0, 0))

            SCREEN.blit(text_1, (50, 450))
            SCREEN.blit(text_2, (50, 480))
            SCREEN.blit(text_3, (50, 510))

    def background():
        global x_pos_bg, y_pos_bg
        image_width = BG.get_width()
        SCREEN.blit(BG, (x_pos_bg, y_pos_bg))
        SCREEN.blit(BG, (image_width + x_pos_bg, y_pos_bg))
        if x_pos_bg <= -image_width:
            SCREEN.blit(BG, (image_width + x_pos_bg, y_pos_bg))
            x_pos_bg = 0
        x_pos_bg -= game_speed

    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                sys.exit()

        SCREEN.fill((255, 255, 255))

        if len(obstacles) == 0:
            rand_int = random.randint(0, 2)
            if rand_int == 0:
                obstacles.append(SmallCactus(SMALL_CACTUS))
            elif rand_int == 1:
                obstacles.append(LargeCactus(LARGE_CACTUS))
            elif rand_int == 2:
                obstacles.append(Bird(BIRD))

        if not AI_player:
            userInput = pygame.key.get_pressed()
            for dinosaur in dinosaurs:
                dinosaur.draw(SCREEN)
                dinosaur.update(userInput)
        else:
            for dinosaur in dinosaurs:
                dinosaur.draw(SCREEN)
                dinosaur.update()

        if AI_player:
            for obstacle in obstacles:
                obstacle.draw(SCREEN)
                obstacle.rect.x -= game_speed
                for i, dinosaur in enumerate(dinosaurs):
                    pygame.draw.line(
                        SCREEN, dinosaur.color,
                        (dinosaur.dino_rect.x + 54, dinosaur.dino_rect.y + 12),
                        obstacle.rect.center, 2)
                    if dinosaur.dino_rect.colliderect(obstacle.rect):
                        ge[i].fitness -= 1
                        remove(i)
                        # nets.pop(i)
                        # ge.pop(i)
        else:
            for obstacle in obstacles:
                obstacle.draw(SCREEN)
                obstacle.rect.x -= game_speed
                for i, dinosaur in enumerate(dinosaurs):
                    if dinosaur.dino_rect.colliderect(obstacle.rect):
                        dinosaurs.pop(i)

        for obstacle in obstacles:
            if obstacle.rect.x < -obstacle.rect.width:
                obstacles.pop()

        if AI_player:
            for i, dinosaur in enumerate(dinosaurs):
                output = nets[i].activate(
                    (dinosaur.dino_rect.y,
                     distance((dinosaur.dino_rect.x, dinosaur.dino_rect.y),
                              obstacle.rect.midtop), obstacle.type))
                if output[0] > 0.5 and dinosaur.dino_rect.y == dinosaur.Y_POS:
                    dinosaur.dino_jump = True
                    dinosaur.dino_run = False
                    dinosaur.dino_duck = False
                if output[1] > 0.5 and dinosaur.dino_rect.y == dinosaur.Y_POS:
                    dinosaur.dino_jump = False
                    dinosaur.dino_run = False
                    dinosaur.dino_duck = True

            if len(dinosaurs) == 0:
                if pop.generation > 5:
                    death_count += 1
                    menu(death_count)
                    run = False
                else:
                    break

        if len(dinosaurs) == 0 and not AI_player:
            game_speed = 0
            death_count += 1
            menu(death_count)
            run = False

        background()
        if AI_player:
            statistics()
        cloud.draw(SCREEN)
        cloud.update()
        score()
        clock.tick(30)
        pygame.display.update()