Ejemplo n.º 1
0
    def __init__(self):
        # Initialization
        libtcodpy.console_set_custom_font('src/arial10x10.png', libtcodpy.FONT_TYPE_GREYSCALE | libtcodpy.FONT_LAYOUT_TCOD)
        libtcodpy.console_init_root(settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT, 'ROGuelike TUTorial', False)
        libtcodpy.sys_set_fps(settings.LIMIT_FPS)
        self.con = libtcodpy.console_new(settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT)

        self.game_map = GameMap(self.con)
        player_x, player_y = self.game_map.get_staring_position()
        # game objects
        self.player = Player(
            'Player',
            self.con,
            player_x, player_y, '@',
            fighter=Fighter(hp=15, defense=5, power=5, death_function=player_death))

        npc_x, npc_y = self.game_map.get_ending_position()
        self.npc = Npc('Trader', self.con, npc_x, npc_y, '@')
        self.objects = [self.npc, self.player]

        self.npcs = [self.npc]
        for monster in self.game_map.place_monsters():
            self.objects.append(monster)

            if hasattr(monster, 'is_selfmoving') and monster.is_selfmoving:
                self.npcs.append(monster)

        self.game_state = 'playing'
        self.player_action = None
Ejemplo n.º 2
0
def init():
    units = []
    player = Player(MAP_SIZE)
    units.append(player)
    player.set_location((random.randint(0, 12) * 5, random.randint(0, 12) * 5))
    player.inital_location = player.location

    objective = Objective()
    units.append(objective)
    objective.set_location(player.location)

    while (player.location == objective.location):
        objective.set_location(
            (random.randint(0, 12) * 5, random.randint(0, 12) * 5))

    mine_count = 10
    mines = []
    for x in range(mine_count):
        temp_location = player.location
        while (temp_location == player.location) or (temp_location
                                                     == objective.location):
            temp_location = (random.randint(0, 12) * 5,
                             random.randint(0, 12) * 5)
        mines.append(Mine())
        units.append(mines[x])
        mines[x].set_location(temp_location)

    return units
Ejemplo n.º 3
0
def main():

    printer = Printer.Printer()
    printer.mainMenu()
    choice = 0
    choice = int(input("Please Enter Your Age:"))
    if choice < 19:
        printer.denyAccess()
        return

    else:
        print("Access Granted")
        turn = "player"
        player = Player.Player()
        ai = Player.Player()
        die = Die.Die()
        maxTotal = (choice)

    while True:
        if turn == "player":
            print("die rolling \../")
            if player.total == 0:
                for i in range(2):
                    die.roll()
                    player.addToTotal(die.value)
                print(player.total)
            else:
                printer.playerChoice()  #adding class to die roll
                pick = input("y/n\n")
                print("AI is rolling the dice")
                if pick == "y":
                    die.roll()
                    player.addToTotal(die.value)
                    printer.printRollValue(die.value, player.total)
                    if player.total > maxTotal:
                        print(
                            "Player has busted and lost, so sad ( >_< -_- >_< -_-)"
                        )
                        break
                else:
                    print("Your Total is : " + str(player.total))
                    turn = "AI"
        else:  # AI turn logic

            printer.dieRoll(die, ai)
            if ai.total >= player.total and ai.total <= maxTotal:
                print("AI Wins  >_< -_- >_< -_-")
                break
            elif ai.total > maxTotal:
                print("AI busted @-@ you got lucky =^_^= ")
                break
            else:
                pass
    print("Thanks for playing! Would You Like To Play Again")
    pick = input("y/n\n")
    if pick == "y":
        return main()
    else:
        return print("Have A Great Day !! See You Soon")
Ejemplo n.º 4
0
 def __init__(self, screen):
     super(RunPlay, self).__init__('Run Play')
     self.player = Player(coord=player_coord, speed=12, screen=screen)
     self.spawner = Spawner()
     self.game = game = Game(screen=screen, width=800, length=600)
     self.screen = screen
     self.time = time.time()
     self.score = 0
Ejemplo n.º 5
0
 def open(self):
     player = Player(ws_connection=self, uuid=uuid.uuid4())
     player.send_message(MyUID(player.uuid))
     mes = NewPlayerConnected(player)
     self.players.append(player)
     self.notify_players_except_self(mes)
     for p in self.players:
         p_mes = PlayerInfo(p)
         player.send_message(p_mes)
Ejemplo n.º 6
0
Archivo: db.py Proyecto: bogolt/dclord
	def getPlayer(self, id):
		if id in self.player.keys():
			return self.player[id] 
		
		self.cur.execute("select name,hw_x,hw_y,login from player where id=:id",(id,))
		r = self.cur.fetchone()
		if not r:
			return None
		p = Player(id, r[0], r[3])
		if r[1] and r[2]:
			p.hw = r[1],r[2]
		
		self.player[id] = p
		return p
Ejemplo n.º 7
0
    def run_game_loop(self):
        is_game_over = False

        x_dir = 1
        y_dir = 0

        snek = Player(100, 230)
        food = Food(400, 230)

        while not is_game_over:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    is_game_over = True
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP:
                        if y_dir != -1:
                            x_dir = 0
                            y_dir = 1
                    elif event.key == pygame.K_DOWN:
                        if y_dir != 1:
                            x_dir = 0
                            y_dir = -1
                    elif event.key == pygame.K_RIGHT:
                        if x_dir != -1:
                            x_dir = 1
                            y_dir = 0
                    elif event.key == pygame.K_LEFT:
                        if x_dir != 1:
                            x_dir = -1
                            y_dir = 0
                elif event.type == pygame.KEYUP:
                    pass

            self.game_screen.fill(GRAY_COLOR)

            snek.draw_snek(self.game_screen)
            snek.move(x_dir, y_dir)
            food.draw(self.game_screen)

            if snek.is_out_of_bounds(self.resolution):
                is_game_over = True
                pygame.display.update()
                clock.tick(self.TICK_RATE)

            if snek.is_eating_himself():
                is_game_over = True
                pygame.display.update()
                clock.tick(self.TICK_RATE)

            if snek.check_for_food(food):
                food.randomize()
                #self.TICK_RATE += 1

            pygame.display.update()
            clock.tick(self.TICK_RATE)
Ejemplo n.º 8
0
    def __init__(self, level):
        super(Game, self).__init__()
        self.level = Level.load_level(level)
        self.background = Sprite(source='img/background.PNG')
        self.size = self.background.size
        self.player = None
        self.boxes = []

        # Initiate the game by creating tiles
        Tile.make_tiles(self.size, self.level)

        # Add bg widget first to not cover other sprites
        self.add_widget(self.background)

        # Add proper widgets for every non-empty tile in the Tile.List
        for tile in Tile.List:
            if tile.type != 'empty':
                if Tile.get_tile(tile.number - Tile.V).walkable:
                    self.add_widget(Sprite(
                        source=Tile.image_files[tile.type],
                        pos=(tile.x, tile.y)), index=2)
                else:
                    self.add_widget(Sprite(
                        source=Tile.image_files[tile.type + '_edge'],
                        pos=(tile.x, tile.y - SPRITE_EDGE_OFFSET)))

        for tile in self.level.boxspawn:
            self.boxes.append(Box(tile, self))

        self.player = Player(self.level.playerspawn, self)

        self.fps_lab = Label(
            text='FPS: ' + str(Clock.get_rfps()),
            pos=(2, self.height - 110),
            font_name=APP_FONT,
            font_size=18,
            color=(240, 240, 240, 0.8))

        self.add_widget(self.fps_lab)

        self.add_widget(Label(
            text="Level {}".format(self.level.level),
            pos=(0, self.height - 80),
            font_name=APP_FONT,
            font_size=18,
            color=(240, 240, 240, 0.8)))

        # Schedule an interval for the game update function
        Clock.schedule_interval(self.update, 1.0/60.0)
Ejemplo n.º 9
0
    def __init__(self):
        super().__init__()

        # Load the screen for the current stage
        state = Config.state()
        entities = (Player(Colors.VIR),
                    Enemy(state['color'], state['shoot_delay']))
        self.screen_intro = ScreenIntro(entities, state['balls'])
        if Config.level == 4:
            self.screen_play = ScreenHardcore(entities, state['balls'],
                                              state['max_balls'],
                                              state['max_score'])
        else:
            self.screen_play = ScreenNormal(entities, state['balls'],
                                            state['max_balls'],
                                            state['max_score'])

        # Set the current screen
        self.current_screen = self.screen_intro

        # Pause sound
        self.snd_click = SoundManager.load_sound('snd_click.wav')

        # Play the background music
        SoundManager.load_music('bgm_stage1.ogg')
Ejemplo n.º 10
0
    def __init__(self, update=True):
        super().__init__()

        # Repeat cutscene
        if not update:
            Cutscene.current_cutscene -= 1
            ScreenDialog.current_dialog -= 1
            SoundManager.load_music('bgm_dialog.ogg')

        # Change level
        if Cutscene.current_cutscene in (4, 6, 8, 11, 14, 17):
            Config.level += 1

        # Background
        state = Config.state()
        self.background = ScreenBackground(
            (Player(Colors.VIR), Enemy(state['color'], state['shoot_delay'])))

        # Transition
        self.transition = False
        self.transition_delay = 50
        self.snd_transition = SoundManager.load_sound('snd_transition1.wav')

        # Set the current screen
        if Cutscene.current_cutscene in (1, 4, 8, 11, 14, 17):
            self.current_screen = ScreenNarrator()
        elif Cutscene.current_cutscene in (3, 6, 7, 10, 13, 16, 19):
            self.current_screen = ScreenDialog()
            SoundManager.load_music('bgm_dialog.ogg')
        else:
            self.current_screen = ScreenDialog()
Ejemplo n.º 11
0
 def __init__(self):
     self.score = 0
     self.graphic = []
     self.objects = []
     self.shifty = 0
     self.player = Player(20, 75, game=self)
     for i in range(0, 20):
         for j in range(1, 3):
             self.objects.append(Enemy(i * 10, j * 10, game=self))
     for i in range(0, 40):
         self.graphic.append([])
         for j in range(0, 80):
             if ((j) % 2 == 0 and i == self.shifty):
                 self.graphic[i].append("A")
             else:
                 self.graphic[i].append(" ")
Ejemplo n.º 12
0
def main():
    """
    Main function of the game
    """

    debug = False
    pygame.init()
    win = pygame.display.set_mode((500, 500))
    pygame.display.set_caption("First Game")

    player = Player(x=50, y=50, width=40, height=60, velocity=15)

    running = True

    while running:
        pygame.time.delay(100)

        for event in pygame.event.get():

            if debug:
                print(event)

            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:
                running = False

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            if player.x >= 0:
                player.x -= player.velocity
        if keys[pygame.K_RIGHT]:
            if player.x + player.width <= 500:
                player.x += player.velocity
        if keys[pygame.K_UP]:
            if player.y >= 0:
                player.y -= player.velocity
        if keys[pygame.K_DOWN]:
            if player.y + player.height <= 500:
                player.y += player.velocity

        win.fill((0, 0, 0))
        pygame.draw.rect(win, (255, 0, 0), player.get())
        pygame.display.update()

    pygame.quit()
Ejemplo n.º 13
0
Archivo: db.py Proyecto: bogolt/dclord
	def getPlayerByLogin(self, login):
		p = [p for _,p in self.player.iteritems() if p.login==login]
		if p:
			return p
		#look in db
		self.cur.execute("select id,name,hw_x,hw_y from player where login=:login",(login,))
		r = self.cur.fetchone()
		
		#or should we add empty user to the list ?
		if not r:
			log.error('player (login: %s) not found'%(login,))
			return None
		p = Player(r[0], r[1], login)
		if r[2] and r[3]:
			p.hw = to_pos(r[2],r[3])
		self.player[p.id] = p	
		return p		
Ejemplo n.º 14
0
 def parse_tournaments_per_month(cls, div, year, month):
     tournaments = []
     for row in filter(bool, div.findAll("tr")):
         try:
             start, end = row.findChild(
                 "td", {"class": "title-content"}).findChild(
                 "span", {"class": "tourney-dates"}).text.split("-")
             winners = {}
             print row.select(".tourney-details")
             for div in row.select(".tourney-details > div"):
                 if div.text.strip().strip("\t").strip("\n") == "SGL":
                     winners["single"] = Player(
                         name=div.findChild("a").text.strip().strip(
                             "\t").strip("\n"),
                         atp_url="%s/%s" % (
                             cls.URL, div.findChild("a").attrs["href"])
                     )
                 elif div.text.strip().strip("\t").strip("\n") == "DBL":
                     winners["double"] = (
                         Player(
                             name=a.text.strip().strip(
                                 "\t").strip("\n"),
                             atp_url="%s/%s" % (
                                 cls.URL, a.attrs["href"])
                         ) for a in div.findChildren("a")
                     )
             tournaments.append(Tournament(
                 name=row.findChild(
                     "td", {"class": "title-content"}).findChild("a").text,
                 year=year,
                 month=month,
                 atp_url="%s/%s" % (cls.URL, row.findChild(
                     "td", {"class": "title-content"}).findChild(
                     "a").attrs["href"]),
                 start=start.strip().strip("\t").strip("\n"),
                 end=end.strip().strip("\t").strip("\n"),
                 location=row.findChild(
                     "td", {"class": "title-content"}).findChild(
                     "span", {
                         "class": "tourney-location"
                     }).text.strip().strip("\t").strip("\n"),
                 winners=winners
             ))
         except (AttributeError, ValueError):
             continue
     return tournaments
Ejemplo n.º 15
0
    def __init__(self):
        self.tk = Tk()
        self.tk.title('Chrome')
        self.tk.resizable(0, 0)
        self.canvas = Canvas(self.tk,
                             width=800,
                             height=200,
                             bd=0,
                             highlightthickness=0)
        self.canvas.config(bg='black')
        self.canvas.pack()

        self.player = Player(self.canvas)
        self.floor = Floor(self.canvas)
        self.obstacles = []
        self.current_speed = 5
        self.frame_number = 0
Ejemplo n.º 16
0
 def __init__(self, log, player_count=2):
     self.log = log
     self.log.info('New session started.')
     self.community_cards = []
     self.deck = deque(self.ALL_CARDS)
     self.players = []
     for i in range(player_count):
         self.players.append(Player(position=i))
Ejemplo n.º 17
0
    def __init__(self, game, level_map=None):
        super(Ingame, self).__init__(game)

        self.p = Player(100, 700)
        self.map = level_map or TestMap()

        self.env = [obj for obj in self.map if obj and obj.obj_type == 'env']
        self.npc = [obj for obj in self.map if obj and obj.obj_type == 'npc']

        self.walls = self.env + self.npc
Ejemplo n.º 18
0
 def __init__(self, gamefile):
     """
     takes path to a xml-gamefile and extracts the world
     """
     self.gamefile = gamefile
     tree = conv.loadworld(gamefile)
     self.properties = conv.unpack_properties(tree)
     self.player = Player(tree.find('player'), self)
     self.rooms = {}
     for room in tree.findall('room'):
         self.rooms[room.get('id')] = Room(self, room)
     self.connections = {}
     for connection in tree.findall('connection'):
         self.connections[connection.get('id')] = Connection(connection)
         # -- WIP -- #            
     self.eventhandler = EventHandler(self)
     self.events = []
     for event in tree.find('events').findall('event'):
         self.events.append(event.get('id'))
         self.eventhandler.events[event.get('id')] = self.eventhandler.parser.parse_xml(event)
class InvadersWindow(pyglet.window.Window):
    """
    This class does all managing: it draws to the screen, and
    updates all the bits and pieces flying around the screen!

    Extends pyglet.window.Window, overwriting the on_draw method.
    """

    def __init__(self):
        """
        This sets everything up. Factoid: Init is short for 'initialise'.

        We call up to pyglets Window init to do the heavy lifting,
        specifying a width, height and caption (title).
        """
        # Create pyglet window - the caption is the window title
        pyglet.window.Window.__init__(
            self,
            caption="Invaders From Space!",
            width=640,
            height=480)
        from objects import Player
        self.player = Player()
        self.push_handlers(self.player.key_handler)

    def on_draw(self):
        """
        Overrides Window.on_draw.
        """
        # First off we wipe the slate clean.
        self.clear()
        self.player.draw()

    def update(self, elapsed_time):
        """
        Perform frame-rate indepent updates of game objects.
        """
        self.player.update(elapsed_time=elapsed_time)
        pass
Ejemplo n.º 20
0
def run_simulation(args):
    number_of_players = int(args[0])
    rounds = int(args[1])
    player_args = [int(i) for i in args[2:]]
    players = []
    for i in range(number_of_players):
        buying_strategy = player_args[i * 3]
        upgrading_strategy = player_args[i * 3 + 1]
        trading_strategy = player_args[i * 3 + 2]
        players.append(
            Player(i, buying_strategy, upgrading_strategy, trading_strategy))
    game = Game(players, rounds)
    game.run()
Ejemplo n.º 21
0
def create_players(world, settings):
    players = []
    for config in settings['players']:
        if config['active']:
            codes = []
            for key in config['controls']:
                code = convert_key(key)
                if code is None:
                    raise RuntimeError('Invalid Key: {}'.format(key))
                codes.append(code)
            player = Player(world, config['colour'], config['name'], [codes[0:2], codes[2:4]])
            world.add_object(player)
            players.append(player)
    return players
Ejemplo n.º 22
0
def create_world():
    global pacman, ghost, item_set, world_map, font_guide, font_life
    pacman = Player()
    ghost = [
        Enemy(35, 565, 1),
        Enemy(565, 35, 2),
        Enemy(565, 565, 3),
        Enemy(350, 390, 4)
    ]
    #   item_set = [item(100, 100, 0), item(200, 200, 0), item(300, 300, 0), item(400, 400, 0)
    #               ,item(100, 200, 4), item(200, 300, 5), item(300, 400, 6), item(400, 500, 7)]
    world_map = map()
    font_guide = load_font('resource/Pixel.ttf', 30)
    font_life = load_font('resource/CrackMan.ttf', 30)
Ejemplo n.º 23
0
    def __init__(self, save):
        # If save is NONE, __init__ is called for default values, otherwise data are loaded from file.
        self.player = Player(save)
        self.world = World(save)

        #Build GUI
        self.gui = GUIWindow(self.world.map)

        self.gui.after(int(1000 / 20), self.call)
        self.gui.bind('<Key>', self.keypress)
        self.gui.map.bind('<B1-Motion>', self.map_pan)
        self.gui.map.bind('<MouseWheel>', self.map_zoom)

        self.gui.run()
Ejemplo n.º 24
0
    async def get_me(self,
                     mode: Gamemode = Gamemode.std) -> Union[Player, bool]:
        if not self.token:
            await self.get_access_token()

        if self.token.expired:
            await self.get_access_token()

        url = f'https://osu.ppy.sh/api/v2/me/{mode.value}'
        json = await self.get(url, headers=self.token.headers)
        if not json:
            return

        return Player.from_api(json)
    def __init__(self, game_width, game_height, agent, user_agent):
        # set the game field
        self.game_width = game_width
        self.game_height = game_height
        self.field = {'width': game_width, 'height': game_height}
        self.redisClient = redis.Redis(host='127.0.0.1', port=6379, db=0)

        self.agent = agent
        self.user_agent = user_agent

        # generate the player instance
        self.player_agent = Player(random.randint(50, self.game_width - 50),
                                   random.randint(50, self.game_height - 50))
        self.player_user = Player(random.randint(50, self.game_width - 50),
                                  random.randint(50, self.game_height - 50))
        flag = True
        x = random.randint(50, self.game_width - 50)
        y = random.randint(50, self.game_height - 50)
        while (flag):
            flag = False
            x = random.randint(50, self.game_width - 50)
            y = random.randint(50, self.game_height - 50)
            position = {'x': x, 'y': y}
            if (util.distance(self.player_agent.position, position) <
                    self.player_user.radius + self.player_agent.radius):
                flag = True
        self.player_user.position['x'] = x
        self.player_user.position['y'] = y
        # initialize the map infomation
        self.map_info = {'stuffs': [], 'bullets': []}

        # initialize the basic infomation of the game
        self.score = 0
        self.timeout = False

        # initialize the agent action
        self.initialize(agent)
Ejemplo n.º 26
0
    def __init__(self,
                 resolution=(750, 750),
                 player_velocity=8,
                 enemy_velocity=2,
                 laser_velocity=7,
                 wave_length=5,
                 player_color='yellow'):
        self.window_width, self.window_height = resolution
        self.player_velocity = player_velocity
        self.enemy_velocity = enemy_velocity
        self.laser_velocity = laser_velocity
        self.wave_length = wave_length

        self.player = Player(300, 630, player_velocity, laser_velocity,
                             player_color)
        self.enemies = []
        self.lasers = []

        self.level = 0
        self.lives = 3
        self.max_lives = 3
        self.score = 0
        self.lost = False
        self.cooldown = 10
Ejemplo n.º 27
0
    async def get_profile(
            self,
            userid: int,
            mode: Gamemode = Gamemode.std) -> Union[Player, bool]:
        if not self.token:
            await self.get_access_token()

        if self.token.expired:
            await self.get_access_token()

        url = ('https://osu.ppy.sh/api/v2' f'/users/{userid}/{mode.value}')
        json = await self.get(url, headers=self.token.headers)
        if not json:
            return

        return Player.from_api(json)
    def __init__(self):
        """
        This sets everything up. Factoid: Init is short for 'initialise'.

        We call up to pyglets Window init to do the heavy lifting,
        specifying a width, height and caption (title).
        """
        # Create pyglet window - the caption is the window title
        pyglet.window.Window.__init__(
            self,
            caption="Invaders From Space!",
            width=640,
            height=480)
        from objects import Player
        self.player = Player()
        self.push_handlers(self.player.key_handler)
Ejemplo n.º 29
0
class RunPlay(State):
    def __init__(self, screen):
        super(RunPlay, self).__init__('Run Play')
        self.player = Player(coord=player_coord, speed=12, screen=screen)
        self.spawner = Spawner()
        self.game = game = Game(screen=screen, width=800, length=600)
        self.screen = screen
        self.time = time.time()
        self.score = 0
        # pygame.mixer.music.load("sound/bensound-punky.mp3")
        # pygame.mixer.music.play(-1)

    def execute(self, fsm):
        self.screen.blit(background, (0, 0))

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                self.player.read_key_down(event)

            if event.type == pygame.KEYUP:
                self.player.read_key_up(event)

            if event.type == pygame.QUIT:
                fsm.change_state(GameOff())

        self.player.update(self.score)

        # Spawn
        if time.time() - self.time >= spawn_time(self.score) and len(
                self.game.enemy_list) <= 32:
            self.time = time.time()
            for i in range(
                    1, 2 +
                    math.floor(breed(self.score) * len(self.game.enemy_list))):
                self.game.include_enemy(self.spawner.create_enemy(self.score))

        end = self.game.update_enemy()
        self.score = self.game.bullet_impact(self.player.bullet_shoot,
                                             self.score)

        score_frame = font.render("Score : " + str(self.score), True,
                                  font_color)
        self.screen.blit(score_frame, (textX, textY))

        if end:
            fsm.change_state(GameOver(self.screen))
            pass

        pygame.display.update()
Ejemplo n.º 30
0
    def __init__(self, victory=False):
        super().__init__()

        # Background
        state = Config.state()
        self.background = ScreenBackground(
            (Player(Colors.VIR), Enemy(state['color'], state['shoot_delay'])))

        # Screens
        self.screen_menu = ScreenMenu(self)
        self.screen_options = ScreenOptions(self)

        # Set the current screen
        self.current_screen = self.screen_menu

        # Play the background music
        if victory:
            SoundManager.load_music('bgm_victory.ogg')
        else:
            SoundManager.load_music('bgm_menu.ogg')
    def __init__(self):
        """
        This sets everything up. Factoid: Init is short for 'initialise'.

        We call up to pyglets Window init to do the heavy lifting, and we
        give it a caption for the window title.
        """
        # Create pyglet window - the caption is the window title
        self.window = pyglet.window.Window(
            caption="Invaders From Space!",
            width=640,
            height=480)

        # Game over label. We also use it as a flag for when
        # the game is finished.
        self.game_over_label = None

        #  Add the alien and laser lists
        self.aliens = []
        self.lasers = []

        # Start the game with three loads of aliens
        self.lurch_aliens_forward()
        self.lurch_aliens_forward()
        self.lurch_aliens_forward()

        # We add two timed functions here to control the flow of aliens
        pyglet.clock.schedule_interval(
            self.change_alien_direction,
            self.seconds_till_lurch)
        pyglet.clock.schedule_interval(
            self.lurch_aliens_forward,
            self.seconds_till_lurch)

        # Add the player and bullet tracker
        from objects import Player
        self.player = Player(window=self)
        self.bullets = []
        # And let the window know to send keyboard events to the Player's
        # key_handler object.
        self.window.push_handlers(self.player.key_handler)
    def __init__(self):
        """
        This sets everything up. Factoid: Init is short for 'initialise'.

        We call up to pyglets Window init to do the heavy lifting,
        specifying a width, height and caption (title).
        """
        # Create pyglet window - the caption is the window title
        pyglet.window.Window.__init__(
            self,
            caption="Invaders From Space!",
            width=640,
            height=480)

        # A list of bullets!
        self.bullets = []

        from objects import Player
        # Our fearless tank, with a reference to ourselves being passed in.
        self.player = Player(window=self)
        # We make sure that the keyboard events are sent to the key handler.
        self.push_handlers(self.player.key_handler)
Ejemplo n.º 33
0
def test_serializable(player):
    data = player.json

    assert data[
        "__TYPE__"] == "Player", "Json data should have the object's type"
    assert "uuid" in data, "Json data should have the object's uuid"
    assert data[
        "position"] == "0,0,0", "Json data should have the object's position"

    assert data[
        "name"] == "TestPlayer", "Json data should have the player's name"
    assert "user" in data, "Player should track which user it belongs to"
    assert data["resources"] == {"Food": 0, "Water": 0, "Fuel": 0}

    reinstantiated = Player.load(data)

    assert player.name == reinstantiated.name
    assert player.position == reinstantiated.position
    assert player.uuid == reinstantiated.uuid

    assert isinstance(
        reinstantiated,
        Player), "Player type information was lost during serialization"
Ejemplo n.º 34
0
    def __init__(self, window_class, window, fpsclock):
        self.window_class = window_class
        self.window = window
        self.clock = fpsclock
        self.groups = Groups()
        self.fps = False
        self.fpsmeter = None
        self.player = Player(window_class, (450, 450), 10, 10, (0, 0), self.groups)
        self.deathscreen_ticker = 255
        self.groups.addtogroup(self.player, self.groups.sprites)
        with open('levels/lvl_1.json', 'r') as data_file:
            data = json.loads(data_file.read(), parse_float=decimal.Decimal)


        for object in data["scene"]["objects"]:
            if data["scene"]["objects"][object]["type"] == 'wall':

                x = int(data["scene"]["objects"][object]["x"])
                y = int(data["scene"]["objects"][object]["y"])
                width = int(data["scene"]["objects"][object]["width"])
                height = int(data["scene"]["objects"][object]["height"])
                color = (
                    int(data["scene"]["objects"][object]["color"][0]),
                    int(data["scene"]["objects"][object]["color"][1]),
                    int(data["scene"]["objects"][object]["color"][2])
                )
                damp = float(data["scene"]["objects"][object]["dampening"])
                fric = float(data["scene"]["objects"][object]["friction"])
                soft = bool(data["scene"]["objects"][object]["soft"])
                emitter = bool(data["scene"]["objects"][object]["emitter"])
                wall = Wall(x, y, width, height, color, damp, fric, soft)
                self.groups.addtogroup(wall, self.groups.walls)
                if emitter:
                    self.groups.addtogroup(wall, self.groups.emitters)
            elif data["scene"]["objects"][object]["type"] == "text":
                text = data["scene"]["objects"][object]["text"]
                x = int(data["scene"]["objects"][object]["x"])
                y = int(data["scene"]["objects"][object]["y"])
                font = data["scene"]["objects"][object]["font"]
                size = int(data["scene"]["objects"][object]["size"])
                antialias = bool(data["scene"]["objects"][object]["antialias"])
                color = (
                    int(data["scene"]["objects"][object]["color"][0]),
                    int(data["scene"]["objects"][object]["color"][1]),
                    int(data["scene"]["objects"][object]["color"][2])
                )

                textobj = Text(self.window, x, y, size, font, text, antialias, color)
                self.groups.addtogroup(textobj, self.groups.text)

        for property in data["scene"]["properties"]:
            if property == "music":
                music = pygame.mixer.Sound(data["scene"]["properties"]["music"])
                music.play(-1, fade_ms=1000)
            elif property == "fps" and bool(data["scene"]["properties"]["fps"]):
                self.fps = True
                pos = (
                    int(data["scene"]["properties"]["fps_pos"][0]),
                    int(data["scene"]["properties"]["fps_pos"][1])
                )
                fpstext = str(self.clock.get_fps()) + " FPS"
                self.fpsmeter = Text(self.window, pos[0], pos[1], 20, None, fpstext, True, (255, 255, 255))
                self.groups.addtogroup(self.fpsmeter, self.groups.text)
class InvadersWindow(object):
    """This class does all managing: it draws to the screen, and
    runs the main game loop.

    Class variables:
    seconds_till_lurch -- the seconds between aliens lurching (default 5)
    aliens_per_row -- how many new aliens per row created (default 5)

    Instance Variables:
    game_over_label -- Initially None, set to a pyglet label by game_over
    aliens -- List of all Alien objects in the game.
    lasers -- List of all laser blasts in the game.
    player -- The Player object.
    bullets -- The list of bullets in the game.
    window -- The pyglet window

    Methods:
    on_draw -- Assigned to the window as a draw function
    update -- Calls the update functions for all game objects.
    change_alien_direction -- Makes all aliens swap strafe direction.
    lurch_aliens_forward -- Makes all aliens jump forward.
    spawn_alien_row -- Spawns a new row of aliens at the top of the screen.
    game_over -- Sets the game over text based on a boolean argument.
    """

    seconds_till_lurch = 5
    aliens_per_row = 5

    def __init__(self):
        """
        This sets everything up. Factoid: Init is short for 'initialise'.

        We call up to pyglets Window init to do the heavy lifting, and we
        give it a caption for the window title.
        """
        # Create pyglet window - the caption is the window title
        self.window = pyglet.window.Window(
            caption="Invaders From Space!",
            width=640,
            height=480)

        # Game over label. We also use it as a flag for when
        # the game is finished.
        self.game_over_label = None

        #  Add the alien and laser lists
        self.aliens = []
        self.lasers = []

        # Start the game with three loads of aliens
        self.lurch_aliens_forward()
        self.lurch_aliens_forward()
        self.lurch_aliens_forward()

        # We add two timed functions here to control the flow of aliens
        pyglet.clock.schedule_interval(
            self.change_alien_direction,
            self.seconds_till_lurch)
        pyglet.clock.schedule_interval(
            self.lurch_aliens_forward,
            self.seconds_till_lurch)

        # Add the player and bullet tracker
        from objects import Player
        self.player = Player(window=self)
        self.bullets = []
        # And let the window know to send keyboard events to the Player's
        # key_handler object.
        self.window.push_handlers(self.player.key_handler)

    def on_draw(self):
        """
        Overrides Window.on_draw, and draws all our sprites to the screen.

        Draw order is:
        1. Player
        2. Bullets
        3. Aliens
        4. Lasers

        Things drawn later go on top of things drawn earlier.
        """
        # First off we wipe the slate clean.
        self.window.clear()

        # Then we draw our tank
        self.player.draw()

        # Now we go through the bullets, aliens and lasers and draw them
        for drawable in chain(self.bullets, self.aliens, self.lasers):
            drawable.draw()

        # Lastly we draw the game over text on the screen if it has been set
        if self.game_over_label is not None:
            self.game_over_label.draw()

    def update(self, elapsed_time):
        """
        Perform frame-rate independent updates of game objects.

        This method just tells each game object to update themselves, Then it
        checks for collions, removes destroyed objects and tests for Player
        victory.

        Arguments:
        elapsed_time -- Time in seconds since the last update.
        """

        # First off we make sure the player gets updated.
        self.player.update(elapsed_time=elapsed_time)

        # Update all the bullets...
        for bullet in self.bullets:
            bullet.update(elapsed_time=elapsed_time)
            # .. and now check for collisions
            for alien in self.aliens:
                if bullet.has_hit(alien):
                    bullet.destroy()
                    alien.explode()

        # Update all the lasers...
        for laser in self.lasers:
            laser.update(elapsed_time=elapsed_time)
            # and check for collisions there too!
            if laser.has_hit(self.player):
                laser.destroy()
                self.player.explode()
                self.game_over(you_won=False)

        # Remove bullets that have gone off the screen or have
        # been marked as 'destroyed'. This kind of line here is
        # a 'list comprehension'. They are really nifty.
        self.bullets = [
            b for b in self.bullets if b.sprite.y < self.window.height
            and not b.destroyed]

        # Remove the aliens that are destroyed, like above, with
        # another list comprehension
        self.aliens = [a for a in self.aliens if not a.destroyed]

        # Remove lasers that have gone off the screen.
        self.lasers = [
            l for l in self.lasers if l.sprite.y > 0
            and not l.destroyed]

        # Make the aliens fire! Maybe. It's a bit random.
        for alien in self.aliens:
            alien.fire()

        # Do the end game victory check
        if len(self.aliens) == 0:
            self.game_over(you_won=True)

    def change_alien_direction(self, elapsed_time=None):
        """
        Make aliens strafe in a different direction.

        Simply sets each aliens head_right variable to the opposite
        value.

        Arguments:
        elapsed_time -- Ignored. Required by pyglet clock.
        """
        for alien in self.aliens:
            alien.head_right = not alien.head_right

    def lurch_aliens_forward(self, elapsed_time=None):
        """
        Make aliens lurch forward.

        Simply calls each aliens lurch function, checking for the
        return value of false that means the Alien has won. If it
        finds it, it calls game_over.

        After each lurch, it spawns a new row of aliens.

        Arguments:
        elapsed_time -- Ignored, required by pyglet's clock.
        """
        if self.game_over_label is None:
            for alien in self.aliens:
                if not alien.lurch():
                    # lurch() returns false if the alien has reached you!
                    # This is a nice way of checking that.
                    self.game_over(you_won=False)

            # After all the aliens have moved forward, we add a new row in
            self.spawn_alien_row()

    def spawn_alien_row(
            self,
            elapsed_time=None,
            number_of_aliens=None):
        """
        Make a row of aliens at the top of the screen.

        Does some rather hacky spacing calculations to determine
        Alien x coordinates.

        Arguments:
        elapsed_time -- Ignored, required by pyglet's clock.
        number_of_aliens -- How many aliens do we want?
        """
        from objects import Alien
        # Check if we should use the default number of aliens
        if not number_of_aliens:
            number_of_aliens = self.aliens_per_row

        # This maths figures out how much space we need to leave for
        # the aliens to strafe across the whole screen.
        number_of_strafes = self.seconds_till_lurch / Alien.strafe_delay
        strafe_distance = number_of_strafes * Alien.strafe_step
        rightmost_start = self.window.width - strafe_distance

        # Now we figure out if we can fit the number of aliens requested
        # into that space. If we can't, we try with one less, then two less...
        spacing = None

        while not spacing:
            space_per_alien = rightmost_start / number_of_aliens
            if space_per_alien < Alien.image.width:
                # Won't fit! Try one less!
                number_of_aliens -= 1
            else:
                # Great! Let's make these aliens!
                spacing = space_per_alien

        # Add some new aliens to the list.
        self.aliens += [
            Alien(window=self, x_pos=(spacing*number + Alien.strafe_step))
            for number in range(number_of_aliens)]

    def game_over(self, you_won=False):
        """
        Game over! Set the game_over_label.

        The text is determined by the boolean you_won argument.

        Arguments:
        you_won -- True for a player win, false for an Alien victory.
        """
        if you_won:
            text = "You Win!"
        else:
            text = "Game Over"

        self.game_over_label = pyglet.text.Label(
            text,
            font_size=30,
            anchor_x="center",
            x=self.window.width / 2,
            y=self.window.height / 2)

        pyglet.clock.unschedule(self.update)
        pyglet.clock.unschedule(self.change_alien_direction)
        pyglet.clock.unschedule(self.lurch_aliens_forward)
        for alien in self.aliens:
            pyglet.clock.unschedule(alien.strafe)
Ejemplo n.º 36
0
def run_simulation(args):
    # Init results class for saving the results
    # r = Results()
    if args.verbose:
        util.verbose = True
    # Print start message
    dev_print("Starting simulation")

    # Set simulation variables
    num_of_players = args.players
    # Go through set amount of simulations
    # Start a new game, run it and save the results
    # dev_print(args.trading_range)
    # dev_print(args.upgrading_range)
    strategy = args.strategy
    # for k in range(num_of_players):
    # 	dev_print(np.arange(args.buying_range[k * 3], args.buying_range[k * 3 + 1], args.buying_range[k * 3 + 2]))
    # single_player_param_list = []
    # for params in player_params:
    #
    # 	single_player_param_list.append(generate_combination(num=7, params=params))
    # # dev_print(single_player_param_list)
    # single_player_list = []
    player_combination = None
    if args.mode in [1, 3]:
        strategy_parameter = [[
            args.strategy_parameter[k * 3] +
            args.strategy_parameter[k * 3 + 1] * i
            for i in range(int(args.strategy_parameter[k * 3 + 2]))
        ] for k in range(num_of_players)]
        income = [[
            args.income[k * 3] + args.income[k * 3 + 1] * i
            for i in range(int(args.income[k * 3 + 2]))
        ] for k in range(num_of_players)]
        tax = [[
            args.tax[k * 3] + args.tax[k * 3 + 1] * i
            for i in range(int(args.tax[k * 3 + 2]))
        ] for k in range(num_of_players)]
        b_tax = [[
            args.building_tax[k * 3] + args.building_tax[k * 3 + 1] * i
            for i in range(int(args.building_tax[k * 3 + 2]))
        ] for k in range(num_of_players)]
        start_capital = [[
            args.start_capital[k * 3] + args.start_capital[k * 3 + 1] * i
            for i in range(int(args.start_capital[k * 3 + 2]))
        ] for k in range(num_of_players)]

        player_params = [[
            strategy_parameter[k], income[k], tax[k], start_capital[k],
            b_tax[k]
        ] for k in range(num_of_players)]
        # dev_print(player_params)
        if args.mode == 3:
            single_player_param_list = []
            for params in player_params:
                single_player_param_list.append(
                    generate_combination(num=5, params=params))
            # dev_print(single_player_param_list)
            single_player_list = []
            for num in range(num_of_players):
                tmp = []
                for p in single_player_param_list[num]:
                    tmp.append(
                        Player(num=num,
                               strategy=strategy[num],
                               strategy_para=p[0],
                               income=p[1],
                               tax=p[2],
                               start_capital=p[3],
                               building_tax=p[4]))
                single_player_list.append(tmp)

            player_combination = generate_combination(
                num=num_of_players, params=single_player_list)
        elif args.mode == 1:
            n = int(args.tax[2])
            player_combination = []
            for i in range(n):
                tmp = []
                for num in range(num_of_players):
                    tmp_player = Player(
                        num=num,
                        strategy=strategy[num],
                        strategy_para=strategy_parameter[num][i],
                        income=income[num][i],
                        tax=tax[num][i],
                        start_capital=start_capital[num][i],
                        building_tax=b_tax[num][i])

                    tmp.append(tmp_player)
                player_combination.append(tmp)
    elif args.mode == 2:
        player_combination = []
        para_list = [
            args.strategy_parameter, args.income, args.tax, args.start_capital,
            args.building_tax
        ]
        para_combination = generate_combination(5, para_list)
        for p in para_combination:
            tmp = []
            for i in range(num_of_players):
                tmp.append(
                    Player(num=i,
                           strategy=args.strategy[0],
                           strategy_para=p[0],
                           income=p[1],
                           tax=p[2],
                           start_capital=p[3],
                           building_tax=p[4]))
            player_combination.append(tmp)
    else:
        raise ValueError("Unknown type.")

    count = 1
    last = time.time()
    simulation_list = []
    for players in player_combination:
        cur_simulation_dic = {"settings": {}, "details": {}, "results": {}}
        player_info_lst = []
        for i in range(len(players)):
            cur_player_dic = {
                "strategy": players[i].strategy,
                "strategy_para": players[i].strategy_para,
                "income": players[i].income,
                "tax": players[i].tax,
                "start_capital": players[i].start_capital,
                "building_tax": players[i].building_tax
            }
            player_info_lst.append(cur_player_dic)
        cur_simulation_dic["settings"] = player_info_lst

        total_rounds = 0
        valid_simulation = 0
        if util.verbose:
            log.write("player combination: " + str(players) + "\n")
        for i in range(1, args.number + 1):
            if util.verbose:
                log.write("simulation number" + str(i) + "\n")
            for n in players:
                n.reset()
            g = Game(players, rounds=args.rounds)
            tmp_info_dic = g.run()

            if tmp_info_dic["end"] != -1:
                total_rounds += tmp_info_dic["end"]
                valid_simulation += 1

            cur_simulation_dic["details"][i] = tmp_info_dic
            if i % 100 == 0:
                dev_print(
                    "{} out of {} simulation of combination {} finished.".
                    format(i, args.number, count))

        # r.addHitResults(g.board.hits)

        # Calculate the amount of simulations per second
        now = time.time()
        duration = now - last
        avg_time = duration / args.number
        try:
            avg_round = total_rounds / valid_simulation
        except ZeroDivisionError:
            avg_round = float("inf")
        last = time.time()

        cur_simulation_dic["results"]["avg_time"] = avg_time
        cur_simulation_dic["results"]["avg_round"] = avg_round
        cur_simulation_dic["results"]["total_time"] = duration
        cur_simulation_dic["results"][
            "end_percent"] = valid_simulation / args.number
        # speed = i / (now - start)
        dev_print("ended: ", valid_simulation)
        dev_print("avg_time: ", avg_time)
        dev_print("avg_round: ", avg_round)
        # Display the progress every 1/1000 of the way to begin finished
        dev_print("{} out of {} combination finished.".format(
            count, len(player_combination)))
        count += 1
        simulation_list.append(cur_simulation_dic)
    metadata_dic["simulations"] = simulation_list
    prod_print(json.dumps(metadata_dic) + "\n")
    # Print that the simulation is finished
    dev_print("\nDone!")
Ejemplo n.º 37
0
class Ingame(Scene):
    def __init__(self, game, level_map=None):
        super(Ingame, self).__init__(game)

        self.p = Player(100, 700)
        self.map = level_map or TestMap()

        self.env = [obj for obj in self.map if obj and obj.obj_type == 'env']
        self.npc = [obj for obj in self.map if obj and obj.obj_type == 'npc']

        self.walls = self.env + self.npc

    def main_loop(self):
        self.get_player_input()
        self.calculate()
        self.draw()

    def get_player_input(self):
        # New input events
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            # Player movement events
            elif event.type == KEYDOWN:
                if event.key == MOVE_UP or event.key == MOVE_RIGHT or event.key == MOVE_DOWN or event.key == MOVE_LEFT:
                    self.p.gfx.set_state(WALKING)


        # Player orientation
        (mx, my) = pygame.mouse.get_pos()

        self.p.orientation = \
            math.degrees(math.atan2(mx - self.p.rect.left, my - self.p.rect.top))

        key = pygame.key.get_pressed()

        # Player movement
        to_move_x = 0
        to_move_y = 0
        if key[MOVE_UP]:
            to_move_y -= 1
        if key[MOVE_RIGHT]:
            to_move_x += 1
        if key[MOVE_DOWN]:
            to_move_y += 1
        if key[MOVE_LEFT]:
            to_move_x -= 1

        if to_move_x or to_move_y:
            self.p.update_vel((to_move_x, to_move_y))
        else:
            self.p.gfx.set_state(NEUTRAL)

        # TODO: Menu
        if key[K_ESCAPE]:
            pygame.quit()
            sys.exit()

    def calculate(self):
        self.calculate_player()
        self.calculate_npc()
        self.calculate_env()

    def draw(self):
        self.game.screen.surface.fill(Color(150,150,150))
        self.draw_player()
        self.draw_npc()
        self.draw_env()
        pygame.display.update()

    def calculate_player(self):
        self.p.update(self.walls)

    def calculate_npc(self):
        pass

    def calculate_env(self):
        pass

    def draw_env(self):
        for i in self.env:
            i.gfx.draw(self.game.screen.surface)

    def draw_npc(self):
        for i in self.npc:
            i.gfx.draw(self.game.screen.surface)

    def draw_player(self):
        self.p.gfx.draw(self.game.screen.surface)
class InvadersWindow(pyglet.window.Window):
    """
    This class does all managing: it draws to the screen, and
    updates all the bits and pieces flying around the screen!

    Extends pyglet.window.Window, overwriting the on_draw method.
    """

    def __init__(self):
        """
        This sets everything up. Factoid: Init is short for 'initialise'.

        We call up to pyglets Window init to do the heavy lifting,
        specifying a width, height and caption (title).
        """
        # Create pyglet window - the caption is the window title
        pyglet.window.Window.__init__(
            self,
            caption="Invaders From Space!",
            width=640,
            height=480)

        # A list of bullets!
        self.bullets = []

        from objects import Player
        # Our fearless tank, with a reference to ourselves being passed in.
        self.player = Player(window=self)
        # We make sure that the keyboard events are sent to the key handler.
        self.push_handlers(self.player.key_handler)

    def on_draw(self):
        """
        Overrides Window.on_draw.
        """
        # First off we wipe the slate clean.
        self.clear()

        # We draw our player
        self.player.draw()

        # We draw our bullets
        for bullet in self.bullets:
            bullet.draw()

    def update(self, elapsed_time):
        """
        Perform frame-rate indepent updates of game objects.
        """
        # Update the player
        self.player.update(elapsed_time=elapsed_time)

        # We update all our bullets!
        for bullet in self.bullets:
            bullet.update(elapsed_time=elapsed_time)
            # Check if it has gone off the screen
            if bullet.sprite.y > self.height:
                # It has, so destroy it.
                bullet.destroy()

        # Keep only the bullets that aren't 'destroyed'
        # This is a super cool and useful Python feature
        # called a 'list comprehension'. Make a list from a loop!
        self.bullets = [b for b in self.bullets if not b.destroyed]
Ejemplo n.º 39
0
sound_btn = Button(sound_on_img, (24, 24), WIDTH - WIDTH // 4 - 18,
                   HEIGHT // 2 + 50)

# OBJECTS *********************************************************************

tile_group = pygame.sprite.Group()

for i in range(8):
    tile = Tile(i, 1, win)
    tile_group.add(tile)
    tile = Tile(i, 2, win)
    tile_group.add(tile)

particle_group = pygame.sprite.Group()
skull_group = pygame.sprite.Group()
p = Player(win, tile_group)

# FUNCTIONS *******************************************************************

deadly_tiles_list = []


def get_index():
    if p.tile_type == 1:
        indices = [2 * index + 1 for index in range(8)]
    elif p.tile_type == 2:
        indices = [2 * index for index in range(8)]

    index = random.choice(indices)
    return index
Ejemplo n.º 40
0
class Game:
    def __init__(self):
        self.tk = Tk()
        self.tk.title('Chrome')
        self.tk.resizable(0, 0)
        self.canvas = Canvas(self.tk,
                             width=800,
                             height=200,
                             bd=0,
                             highlightthickness=0)
        self.canvas.config(bg='black')
        self.canvas.pack()

        self.player = Player(self.canvas)
        self.floor = Floor(self.canvas)
        self.obstacles = []
        self.current_speed = 5
        self.frame_number = 0

    def next_frame(self, action):
        done = False
        # Do we have to remove the first obstacle from obstacles
        elim = False

        # Creating image and drawing with PIL
        img = Image.new('L', (800, 200), 0)
        drawing = ImageDraw.Draw(img)

        # Creating new random obstacle and change speed of the game
        if self.frame_number % 40 == 0:
            if self.current_speed < 25:
                self.current_speed += 0.5
            else:
                print('Game beat!')
                done = True
            self.obstacles.append(
                Obstacle(self.canvas, random.choice([1, 2, 3, 4]),
                         self.current_speed))

        # Checking collision
        for i in range(len(self.obstacles)):
            obs_pos = self.obstacles[i].get_coords()
            player_pos = self.player.get_coords()

            # Getting coords of corners of player and obstacles
            obs_corners = [(obs_pos[0], obs_pos[1]), (obs_pos[2], obs_pos[1]),
                           (obs_pos[0], obs_pos[3]), (obs_pos[2], obs_pos[3])]
            player_corners = [(player_pos[0], player_pos[1]),
                              (player_pos[2], player_pos[1]),
                              (player_pos[0], player_pos[3]),
                              (player_pos[2], player_pos[3])]
            for corner in obs_corners:
                if player_pos[0] <= corner[0] <= player_pos[2] and player_pos[
                        1] <= corner[1] <= player_pos[3]:
                    done = True
            for corner in player_corners:
                if obs_pos[0] <= corner[0] <= obs_pos[2] and obs_pos[
                        1] <= corner[1] <= obs_pos[3]:
                    done = True

            # Removing obstacles or drawing them
            if obs_pos[2] < -1:
                self.obstacles[i].remove()
                elim = True
            else:
                self.obstacles[i].draw(drawing, self.current_speed)

        # Drawing a player
        self.player.draw(action, drawing)
        # Updating screen
        self.tk.update_idletasks()
        self.tk.update()

        # Remove obstacle if needed
        if elim:
            self.obstacles = self.obstacles[1:]

        return np.array(img)[:175, :], done

    def reset(self, mode='easy'):
        # Reseting player and params
        self.player.reset()
        self.frame_number = 0
        self.current_speed = 13

        # Removing obstacles
        for i in range(len(self.obstacles)):
            self.obstacles[i].remove()
        self.obstacles = []

        # Getting start frame (first action is jump)
        start_frame, _, _ = self.step('n', mode)
        return start_frame

    def step(self, action, mode='easy'):
        # Get params of the next frame
        cur_x, done = self.next_frame(action)

        # Calculating reward
        if done:
            reward = -500 / self.frame_number
        else:
            reward = 0.01 * self.frame_number

        # Increment frame_number (score)
        self.frame_number += 1

        if mode == 'hard':
            return cur_x, done, reward

        # Players current position
        pos_player = self.player.get_coords()

        player_y = (pos_player[1] - 85) / 90
        # Ensure that there are no errors
        obstacle_distance = -1
        obstacle_x = -1
        obstacle_y = -1
        min_y = -1
        try:
            # Get params and normalize them
            if self.obstacles[0].get_coords()[2] - pos_player[0] > 0:
                pos_obstacle = self.obstacles[0].get_coords()

                obstacle_distance = (pos_player[2] - pos_obstacle[0]) / 765
                obstacle_x = (pos_obstacle[2] - pos_obstacle[0]) / 40
                obstacle_y = (pos_obstacle[3] - pos_obstacle[1]) / 40
                min_y = (pos_obstacle[1] - 80) / 65
            elif len(self.obstacles) > 1:
                pos_obstacle = self.obstacles[1].get_coords()

                obstacle_distance = (pos_player[2] - pos_obstacle[0]) / 765
                obstacle_x = (pos_obstacle[2] - pos_obstacle()[0]) / 40
                obstacle_y = (pos_obstacle[3] - pos_obstacle[1]) / 40
                min_y = (pos_obstacle[1] - 80) / 65
        except:
            pass

        speed = (self.current_speed - 5) / 20

        return np.array([
            player_y, obstacle_distance, obstacle_x, obstacle_y, min_y, speed
        ]), done, reward
Ejemplo n.º 41
0
# SOUNDS **********************************************************************

player_bullet_fx = pygame.mixer.Sound('Sounds/gunshot.wav')
click_fx = pygame.mixer.Sound('Sounds/click.mp3')
collision_fx = pygame.mixer.Sound('Sounds/mini_exp.mp3')
blast_fx = pygame.mixer.Sound('Sounds/blast.wav')
fuel_fx = pygame.mixer.Sound('Sounds/fuel.wav')

pygame.mixer.music.load('Sounds/Defrini - Spookie.mp3')
pygame.mixer.music.play(loops=-1)
pygame.mixer.music.set_volume(0.1)

# GROUPS & OBJECTS ************************************************************

bg = Background(win)
p = Player(144, HEIGHT - 100)

enemy_group = pygame.sprite.Group()
player_bullet_group = pygame.sprite.Group()
enemy_bullet_group = pygame.sprite.Group()
explosion_group = pygame.sprite.Group()
fuel_group = pygame.sprite.Group()
powerup_group = pygame.sprite.Group()

# FUNCTIONS *******************************************************************


def shoot_bullet():
    x, y = p.rect.center[0], p.rect.y

    if p.powerup > 0:
Ejemplo n.º 42
0
server = "192.168.0.64"
port = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind((server, port))
except socket.error as e:
    str(e)

s.listen(2)
print('Waiting for connection, Server started')

game = Game([
    Player(45, 285, 10, 150, (255, 255, 255)),
    Player(945, 285, 10, 150, (255, 255, 255))
], Ball(465, 330, 25, (255, 255, 255)), -1, 0, 0)


def threaded_client(conn, player):
    global playersCount
    conn.send(str.encode(str(player)))

    while True:
        try:
            data = pickle.loads(conn.recv(2048))
            if not data:
                print('Disconnected')
                break
            else: