Пример #1
0
    def gameEngine(self):

        print("TEST TEST TEST")

        p1 = Player("p1")
        p2 = Player("p2")
        p3 = Player("p3")
        p4 = Player("p4")
        p5 = interactivePlayer("ip5")
        p6 = smarterPlayer("sp6")

        self.agent = p5

        aTable = table()
        aTable.setMaxGames(1000)

        aTable.addPlayer(p1, 100)
        aTable.addPlayer(p2, 100)
        aTable.addPlayer(p3, 100)
        aTable.addPlayer(p4, 100)
        aTable.addPlayer(p5, 100)
        aTable.addPlayer(p6, 100)

        print("Table Setted up with Six dummy player")
        print("Number of Players " + str(aTable.getNPlayer()))
        print("Number of Active Players " + str(aTable.getNPlayer_active()))
        print("Number of inGame Players " + str(aTable.getNPlayer_inGame()))

        aTable.runGame()
Пример #2
0
    def __init__(self):
        self.score = 0
        self.scroll = 0
        self.cam_speed = 700

        self.clouds = []
        self.projectiles = []

        self.stage = stageGeneration.Stage(self.projectiles)

        cloud_amount = 3
        for i in range(cloud_amount):
            min_x = i * (1920/cloud_amount)
            max_x = min_x+(1920/cloud_amount-500)
            x = random.randrange(min_x, max_x)
            y = random.randrange(-100, 100)
            background.Cloud((x, y), self.clouds)

        self.Mark = Player(position=(300, -200),
                           speed=(self.cam_speed, 0),
                           size=(83, 111),
                           gun='shotgun',
                           platforms=self.stage.platforms,
                           spikes=self.stage.spikes,
                           coins=self.stage.coins,
                           projectiles=self.projectiles,
                           enemies=self.stage.enemies)
 def loadPlayer(self):
     # TODO: Add player creation menu here
     self.player = Player()
     self.player.race = Race(self.races["human"])
     self.player.disp = self.disp
     self.player.weapon = Weapon(self.weapons["weapon_ironSword"])
     self.player.armor = Armor(self.armor["armor_hideArmor"])
     self.player.inv.append(
         generateWeapon(self.weapons["template_IronSword"]))
     self.player.gold = 100
     self.loadStartingArea()
     self.player.hp = self.player.getMaxHP()
Пример #4
0
    def testEnemyDetection(self):
        """ tests to see if the function is_enemy correctly checks this """
        guineaPig = Player()
        testCaseP = Player()

        guineaPig.team_number = 1
        testCaseP.team_number = 2

        assert(guineaPig.is_enemy(testCaseP) == True)

        guineaPig.team_number = 2
        assert(guineaPig.is_enemy(testCaseP) != True)
Пример #5
0
 def join(self, ctx):
     """:If you are new, use this to start playing."""
     user = Player()
     user.name = str(ctx.message.author)
     author = str(ctx.message.author)
     if not path.isfile(str(ctx.message.author) + "player11" + ".txt"):
         userlist.append(user)
         usernamelist.append(user.name)
         userlist[findPlayer(author)].update()
         userlist[findPlayer(author)].update()
         userlist[findPlayer(author)].move(level.root.index)
         userlist[findPlayer(author)].update()
         yield from self.bot.send_message(ctx.message.author, "Welcome" + str(ctx.message.author) + ' ' + level.find(user.location).desc)
     else:
         yield from self.bot.send_message(ctx.message.author, "You are already a registered user.")
         del user
Пример #6
0
def main():
    # These 4 lines just to prepare the window of the game, no need to change them
    root = tkinter.Tk()
    root.title("eetmeet")
    cv = ScrolledCanvas(root, 600, 600, 600, 600)
    cv.pack(side=tkinter.LEFT)
    #Here we prepre the new shapes of the game
    t = RawTurtle(cv)
    screen = t.getscreen()
    screen.setworldcoordinates(screenMinX, screenMinY, screenMaxX, screenMaxY)
    screen.register_shape("Character.gif")
    frame = tkinter.Frame(root)
    frame.pack(side=tkinter.RIGHT, fill=tkinter.BOTH)
    screen.tracer(10)
    sb = Spikes_bottom(cv)
    st = Spikes_top(cv)
    plr = Player(cv)
    t.goto(20, 40)
    t.circle(8)

    # this function when it is called the game will exit
    def quitHandler():
        root.destroy()
        root.quit()

    #here we are creating the button that you will see it on the right side of the game called Quit
    # the part it says command=quitHandler is telling the button when we click it to run the function quitHandler that we defined above
    quitButton = tkinter.Button(frame, text="Quit", command=quitHandler)
    quitButton.pack()

    # GAME LOOP (BEGIN)
    def play():
        # Tell all the elements of the game to move
        # Tell the ship to move
        plr.move()
        st.move(0.3)
        sb.move(0.7)
        if (intersect(plr, st) or intersect(plr, sb)):
            print(" ")
            print("boom")
            quitHandler()
        # Set the timer to go off again in 5 milliseconds
        screen.ontimer(play, 5)
        # GAME LOOP (ENDS)

    # Set the timer to go off the first time in 5 milliseconds
    screen.ontimer(play, 5)
    screen.onkeypress(plr.jump, "Up")
    screen.onkeypress(plr.duck, "Down")
    screen.listen()
    tkinter.mainloop()
Пример #7
0
def main():
    """Run code to choose pokemon and begin battle in loop."""
    # welcome_to_pokemon_screen()

    # initialize outer game loop
    still_playing = True

    # play background music on loop
    pygame.mixer.music.play(-1)

    user_name = welcome_to_pokemon_screen()

    while still_playing:
        print("Select user pokemon.")
        P1 = Player(choose_pokemon("player", user_name), gv.PLAYER_LOCATION,
                    DISPLAYSURF)
        print("Select opponent pokemon.")
        P2 = Player(choose_pokemon("enemy", user_name), gv.ENEMY_LOCATION,
                    DISPLAYSURF)

        battle_screen(P1, P2)

    pygame.mixer.music.stop()
Пример #8
0
    def __init__(self):
        """ Constructor. Create all our attributes and initialize
        the game. """

        # Create the player
        self.player = Player()
        
        self.screen = None
        
        self.LB = False
        self.B_Button = False
        
        self.minimap_on = False
        
        self.world_shift_x = 0
        self.world_shift_y = 0

        self.game_over = False
        self.paused = False
        
        self.controller = False

        self.joystick_count = pygame.joystick.get_count()
        if self.joystick_count == 0:
            # No joysticks!
            print("Error, I didn't find any joysticks.")
        else:
            # Use joystick #0 and initialize it
            self.my_joystick = pygame.joystick.Joystick(0)
            self.my_joystick.init()
            self.controller = True

        self.active_sprite_list = pygame.sprite.Group()
        
        self.active_sprite_list.add(self.player)
        
        self.current_level_no = 0
        
        self.level_list = []
        self.level_list.append(levels.Level(self.player))
        self.current_level = self.level_list[self.current_level_no]
        
        self.player.level = self.current_level
Пример #9
0
class RandomPlayer(Player):
    """ a data type (subclass of Player class) for a Random Computer playing Connect Four"""
    def next_move(self, b):
        """ This method function takes the player "X" or "O"
                and the given board, and makes a random selection
                of where to place its next checker based on the 
                validity of the move.
            input: b, a string of the board
        """
        if b.is_full() == True:
            return -1
        else:
            choice = random.choice(range(b.width))
            if b.can_add_to(choice) == True:
                return choice
            else:
                while b.can_add_to(choice) == False:
                    choice = random.choice(range(b.width))
                return choice

    connect_four(Player("X"), AIPlayer("O", "LEFT", 2))
Пример #10
0
 def testDeath(self):
     """ tests to see if death is properly reported by is_dead """
     redshirt = Player()
     redshirt.state = 10 # the state for the player being
     assert(redshirt.is_dead() == True)
Пример #11
0
class Game(object):
    def __init__(self):
        '''Initializes the Game object. This also sets some required variable
        to empty so they can be initialized later.'''
        self.player = None

        self.disp = ApplicationWindow()

        self.loaded = False
        self.settings = {}
        self.gameSettings = {}
        self.dataPackSettings = {}

        # TODO deprecate self.currentArea and replace with self.areaController
        self.currentArea = None
        self.areaController = None
        self.starter = None

        self.logos = []
        self.descs = []

        self.displayIsInitialized = False

    def initialLoad(self, folder="res/", settingsdata={}):
        '''This does all of the heavy duty loading. Once this is complete, all
        game data is loaded until the game is closed, which cuts down on load
        times.'''
        self.cleanDataPackInfo()

        global DELAY, DEBUG, EVENTDELAY
        self.settings = settingsdata
        self.loadGameSettings()
        DELAY = self.settings["DELAY"]
        EVENTDELAY = self.settings["EVENTDELAY"]
        DEBUG = self.settings["DEBUG"]
        DISPLAYSETTINGS = self.settings["DISPLAYSETTINGS"]
        DEBUGDISPLAY = self.gameSettings["DEBUGDISPLAY"]

        # Set up the display with a delay and whether or not to debug
        if not self.displayIsInitialized:
            self.disp.initiate_window(
                f'Project: EMPTY v{self.settings["VERSION"]}', DISPLAYSETTINGS,
                DELAY, self.gameSettings["DELAYENABLED"], DEBUGDISPLAY)
            self.displayIsInitialized = True
        else:
            self.disp.set_settings(DISPLAYSETTINGS, DELAY,
                                   self.gameSettings["DELAYENABLED"],
                                   DEBUGDISPLAY)

        self.loadDataPackSettings()
        packs = self.dataPackSettings["packsToLoad"]
        self.starter = self.dataPackSettings["start"]
        print("\nLoading assets...")

        for pack in packs:
            if pack[1]:
                pack = pack[0]

                print("Loading pack \"{}\"...".format(pack))
                self.packs[pack] = loadJson("%s%s/meta.json" % (folder, pack))

                if "gameLogo" in self.packs[pack].keys():
                    self.logos.append(self.packs[pack]["gameLogo"])
                if "gameDesc" in self.packs[pack].keys():
                    for desc in self.packs[pack]["gameDesc"]:
                        self.descs.append(desc)

                # Asset loading
                for w in self.packs[pack]["weapons"]:
                    self.weapons[w] = loadJson("%s%s/weapons/%s.json" %
                                               (folder, pack, w))
                    self.disp.dprint("Loaded asset %s" % w)
                for a in self.packs[pack]["armor"]:
                    self.armor[a] = loadJson("%s%s/armor/%s.json" %
                                             (folder, pack, a))
                    self.disp.dprint("Loaded asset %s" % a)
                for m in self.packs[pack]["misc"]:
                    self.misc[m] = loadJson("%s%s/misc/%s.json" %
                                            (folder, pack, m))
                    self.disp.dprint("Loaded asset %s" % m)
                for a in self.packs[pack]["areas"]:
                    self.areas[a] = loadJson("%s%s/areas/%s.json" %
                                             (folder, pack, a))
                    self.disp.dprint("Loaded asset %s" % a)
                for r in self.packs[pack]["races"]:
                    raceData = loadJson("%s%s/races/%s.json" %
                                        (folder, pack, r))
                    self.races[raceData["id"]] = raceData
                    self.disp.dprint("Loaded asset %s" % r)
                for n in self.packs[pack]["npcs"]:
                    self.npcs[n] = loadJson("%s%s/npcs/%s.json" %
                                            (folder, pack, n))
                    self.disp.dprint("Loaded asset %s" % n)
                for e in self.packs[pack]["enemies"]:
                    self.enemies[e] = loadJson("%s%s/enemies/%s.json" %
                                               (folder, pack, e))
                    self.disp.dprint("Loaded asset %s" % e)
                for q in self.packs[pack]["quests"]:
                    self.quests[q] = loadJson("%s%s/quests/%s.json" %
                                              (folder, pack, q))
                    self.disp.dprint("Loaded asset %s" % q)
                for e in self.packs[pack]["events"]:
                    self.events[e] = loadJson("%s%s/events/%s.json" %
                                              (folder, pack, e))
                    self.disp.dprint("Loaded asset %s" % e)
                for m in self.packs[pack]["modifiers"]:
                    mods = loadJson("%s%s/%s.json" % (folder, pack, m))
                    for mod in mods.keys():
                        self.modifiers[mod] = Modifier(mod, mods[mod])
                print("Finished loading assets.")

        # Adds all loaded quests into a list of possible quests, as well as
        # loads thems into actual objects
        for quest in self.quests.keys():
            self.possibleQuests.append(Quest(self.quests[quest]))
        if DEBUG:
            for q in self.possibleQuests:
                self.disp.dprint(q)

        self.loadStartingArea()

        # Sets up the player variables and also gives the player some starting gear.
        # Spawns in an extra weapon for the player to switch between.
        self.loadPlayer()
        self.loaded = True

    def loadStartingArea(self):
        self.areaController = AreaController(
            self.areas, self.packs[self.starter]["startingArea"], (0, 0),
            self.weapons, self.armor, self.misc, self.enemies, self.npcs,
            self.events, self.modifiers)
        '''
        # TODO deprecate this loading function
        self.currentArea = Area(self.areas[self.packs[self.starter][
                                "startingArea"]], DEBUG, **{"playerLevel": 1, "difficultyModifier": 1})
        self.currentArea.load(self.weapons, self.armor, self.misc,
                              self.enemies, self.npcs, self.events, self.modifiers)
        '''

        self.currentArea = self.areaController.loadArea((0, 0))
        # Disables enemies in the first area.
        self.currentArea.enemy = []

    def loadPlayer(self):
        # TODO: Add player creation menu here
        self.player = Player()
        self.player.race = Race(self.races["human"])
        self.player.disp = self.disp
        self.player.weapon = Weapon(self.weapons["weapon_ironSword"])
        self.player.armor = Armor(self.armor["armor_hideArmor"])
        self.player.inv.append(
            generateWeapon(self.weapons["template_IronSword"]))
        self.player.gold = 100
        self.loadStartingArea()
        self.player.hp = self.player.getMaxHP()

    def cleanDataPackInfo(self):
        self.packs = {}
        self.weapons = {}
        self.armor = {}
        self.misc = {}
        self.areas = {}
        self.races = {}
        self.quests = {}
        self.events = {}
        self.npcs = {}
        self.enemies = {}
        self.modifiers = {}

        self.possibleQuests = []
        self.currentQuests = []
        self.completedQuests = []
        self.backlog = []
        self.importantQuestInfo = []

    def loadGameSettings(self):
        self.gameSettings = {}
        for setting in self.settings["GAMESETTINGS"]:
            self.gameSettings[setting[0]] = setting[2]

    def loadDataPackSettings(self):
        self.dataPackSettings = {}
        for setting in self.settings["DATAPACKSETTINGS"].keys():
            self.dataPackSettings[setting] = self.settings["DATAPACKSETTINGS"][
                setting]

    def close_display(self):
        if self.displayIsInitialized:
            self.disp.close_window()
            self.displayIsInitialized = False

    def displayCurrentArea(self):
        '''Displays info on the area the player is currently in.'''
        self.disp.clearScreen()
        title = "%s (%s) - Hostility: %d" % (self.currentArea.name,
                                             self.currentArea.aType,
                                             self.currentArea.hostility)
        self.disp.displayHeader(title)
        for desc in self.currentArea.desc.split("\n"):
            self.disp.display(desc)
        print("|{}|".format(" " * 78))
        # Display enemies that are in the area (if there are any)
        if self.currentArea.enemy != []:
            self.disp.closeDisplay()
            self.disp.display("You can see enemies in the distance:", 1, 1)
            for enemy in self.currentArea.enemy:
                self.disp.display(
                    f'{enemy.name} (Danger - {enemy.getDanger()})', 0, 0)
        self.disp.closeDisplay()

        # input("\nEnter to continue")
        self.disp.wait_for_enter()
        self.workOnBacklog()

    def reactCurrentArea(self):
        '''This is where the player becomes able to respond to any action that
        has occured within the game, such as enemies appearing, or quest
        objectives getting updated.'''

        self.fightEnemies()
        if self.player.quit:
            return None

        ##### Random event Code #####
        if self.currentArea.event and self.gameSettings[
                "DISABLEFLAVOREVENTS"] and self.currentArea.event.eventType == "flavor":
            self.currentArea.event = None
        if self.currentArea.event:
            self.disp.dprint(self.currentArea.event.name)
            while not self.currentArea.event.finished:
                self.disp.clearScreen()
                self.disp.displayHeader(self.currentArea.event.name)
                self.disp.display(self.currentArea.event.msg, 1)
                x = 0
                choices = self.currentArea.event.getPossibleActions(
                    self.player)
                if len(choices) > 0:
                    self.disp.displayHeader("Actions", 1, 1)
                    for choice in choices:
                        x += 1
                        action = choice["action"]
                        self.disp.display(f'{x}. {action}', 0)
                    self.disp.closeDisplay()

                    try:
                        #cmd = int(input())
                        cmd = self.disp.get_input(True)
                    except:
                        cmd = -1
                    if cmd > 0 and cmd <= x:
                        for action in choices[cmd - 1]["eventDo"]:
                            self.disp.dprint(action)
                            if action[0] == "say":
                                self.displayEventAction(action[1])
                            elif action[0] == "goto":
                                self.currentArea.event.gotoPart(
                                    random.choice(action[1]))
                            elif action[0] == "addTag":
                                self.player.tags.append(
                                    self.currentArea.event.getTag(action[1]))
                            elif action[0] == "take":
                                self.currentArea.event.takeItem(
                                    action[1], action[2], self.player)
                            elif action[0] == "give":
                                self.currentArea.event.giveItem(
                                    action[1], action[2], self.player,
                                    self.weapons, self.armor, self.misc)
                            elif action[0] == "finish":
                                self.currentArea.event.finish()
                else:
                    self.disp.closeDisplay()
                    self.currentArea.event.finish()
                    if self.gameSettings["EVENTDELAYENABLED"]:
                        time.sleep(EVENTDELAY)
                    #input("\nEnter to continue")
                    self.disp.wait_for_enter()

        ##### Interacting with an NPC Code #####
        if self.currentArea.npc:
            self.disp.clearScreen()
            self.disp.displayHeader(self.currentArea.npc.name)
            self.disp.display(self.currentArea.npc)

    def displayEventAction(self, message):
        self.disp.clearScreen()
        self.disp.displayHeader(self.currentArea.event.name)
        self.disp.display(message)
        self.disp.closeDisplay()
        # input("\nEnter to continue")
        self.disp.wait_for_enter()

    def fightEnemies(self):
        ##### Fighting Code #####
        if self.currentArea.enemy != []:
            self.disp.clearScreen()
            for areaEnemy in self.currentArea.enemy:
                enemyhp = areaEnemy.getHealth()
                while enemyhp > 0 and self.player.hp:
                    self.disp.dprint("Enemy Danger Level:   {}".format(
                        areaEnemy.getDanger()))
                    self.disp.dprint("Enemy Max Health:     {}".format(
                        areaEnemy.hpMax))
                    self.disp.dprint("Enemy Current Health: {}".format(
                        areaEnemy.hp))
                    self.disp.dprint("Enemy Strength:       {}".format(
                        areaEnemy.getStrength()))
                    self.disp.dprint("Enemy Weapon Damage:  {}".format(
                        areaEnemy.getRawWeaponDamage()))

                    cmd = -1
                    self.disp.clearScreen()
                    while not ((int(cmd) <= 2 and int(cmd) >= 0) or
                               (cmd == 90 and DEBUG)):
                        self.disp.displayHeader("Enemy Encountered - %s" %
                                                (areaEnemy.name))
                        self.disp.display(
                            "%s The enemy has a danger level of %d." %
                            (areaEnemy.desc, areaEnemy.getDanger()), 1, 1)
                        self.disp.displayHeader("Info")
                        self.disp.display("Player: %s - %dHP" %
                                          (self.player.name, self.player.hp))
                        self.disp.display(
                            "HP: %s" % ("#" * self.player.getHealth()), 0)
                        self.disp.display(
                            "Weapon: %s" % (str(self.player.weapon)), 0)
                        self.disp.display("Enemy: %s - %dHP" %
                                          (areaEnemy.name, areaEnemy.hp))
                        self.disp.display(
                            "HP: %s" % ("#" * areaEnemy.getHealth()), 0)
                        self.disp.display(
                            "Weapon: %s" % (str(areaEnemy.weapon)), 0, 1)
                        self.disp.displayHeader("Actions")
                        self.disp.display("1. Use your weapon (%s)" %
                                          str(self.player.weapon))
                        self.disp.display("2. Attempt to escape", 0)
                        self.disp.display("0. Player Menu")
                        self.disp.closeDisplay()
                        try:
                            # cmd = int(input())
                            cmd = self.disp.get_input(True)
                            if not self.disp.window_is_open:
                                self.player.quit = True
                                return None
                            self.disp.clearScreen()
                        except ValueError:
                            self.disp.clearScreen()
                            cmd = -1
                        if cmd == 0:
                            self.player.playerMenu(self.currentQuests,
                                                   self.completedQuests)
                            if self.player.quit:
                                # TODO Exit the game completely
                                return None
                        elif cmd in (9, 90) and DEBUG:
                            self.disp.dprint("Healing player fully.")
                            self.player.hp = self.player.getMaxHP()
                        elif cmd not in (1, 2, 0):
                            self.disp.displayHeader("Error")
                            self.disp.display("That was not a valid response.",
                                              1, 1)

                    if cmd == 1 or cmd == 90:
                        self.disp.clearScreen()
                        damage = self.player.getWeaponDamage()
                        if DEBUG and cmd == 90:
                            damage *= 10
                        msg = self.player.getWeaponAction()
                        damage -= int(areaEnemy.getArmorDefence())
                        if damage < 0:
                            damage = 0
                        areaEnemy.hp -= damage
                        self.disp.displayHeader("You")
                        self.disp.display(
                            "%s You dealt %d damage." % (msg, damage), 1, 1)
                        self.disp.displayHeader(areaEnemy.name)
                        damage = areaEnemy.getWeaponDamage()
                        if self.player.armor:
                            damage -= self.player.getArmorDefence()
                        if damage < 0:
                            damage = 0
                        self.player.hp -= damage
                        self.disp.display("%s %s dealt %d damage." %
                                          (areaEnemy.weapon.getAction(),
                                           areaEnemy.name, damage))
                        self.disp.closeDisplay()
                        time.sleep(DELAY)
                        # input("\nEnter to continue.")
                        self.disp.wait_for_enter()
                    elif cmd == 2:
                        self.disp.clearScreen()
                        escape = False
                        if random.randint(
                                0,
                                self.player.getArmorDefence() +
                                areaEnemy.getWeaponDamage()
                        ) < areaEnemy.getArmorDefence():
                            escape = True
                        if escape:
                            self.disp.displayHeader("Escape Successful")
                            self.disp.display(
                                "You successfully escape from %s." %
                                (areaEnemy.name))
                        else:
                            self.disp.displayHeader("Escape Failed")
                            self.disp.display(
                                "You fail to escape from %s." %
                                (areaEnemy.name), 1, 1)
                            self.disp.displayHeader(areaEnemy.name)
                            damage = areaEnemy.weapon.damage
                            if self.player.armor:
                                damage += "-{0}".format(
                                    self.player.getArmorDefence())
                            damage = rollDice(damage)
                            if damage < 0:
                                damage = 0
                            self.player.hp -= damage
                            self.disp.display("%s %s dealt %d damage." %
                                              (areaEnemy.weapon.getAction(),
                                               areaEnemy.name, damage))
                        self.disp.closeDisplay()
                        time.sleep(DELAY)
                        # input("\nEnter to continue")
                        self.disp.wait_for_enter()
                        if escape:
                            break

                    self.disp.clearScreen()
                    enemyhp = areaEnemy.hp

                if self.player.hp > 0 and areaEnemy.hp <= 0:
                    self.disp.clearScreen()
                    self.disp.displayHeader("Victory")
                    self.disp.display(
                        "You defeated the enemy, and got %d experience." %
                        areaEnemy.xp)
                    self.importantQuestInfo.append(
                        ["isKilled", areaEnemy.eID, True, False])
                    self.disp.display("%s %s" %
                                      (areaEnemy.name, areaEnemy.deathMsg))
                    if random.randint(1, 100) < areaEnemy.itemChance:
                        self.disp.display("")
                        self.disp.displayHeader("Reward")
                        self.disp.display(areaEnemy.itemDrop[1])
                        self.disp.display("You recieved %s." %
                                          (areaEnemy.itemDrop[0].name))
                        self.player.inv.append(areaEnemy.itemDrop[0])
                    self.disp.closeDisplay()
                    # time.sleep(DELAY)
                    # input("\nEnter to continue")
                    self.disp.wait_for_enter()
                    self.player.giveXP(areaEnemy.xp)

                # UPDATE QUEST INFO
                self.updateQuestInfo()
                self.workOnBacklog()

    def chooseNewArea(self):
        '''This lets the player choose a new area to travel to.'''
        # Create various area choices:
        choices = self.randomAreaChoices()
        cmd = -1

        # Allow the player to choose from those places:
        while not 1 <= cmd <= len(choices):
            self.disp.clearScreen()
            self.disp.displayHeader("Where to next?")
            self.disp.display("", 1, 0)
            x = 0
            for area in choices:
                x += 1
                self.disp.display(
                    "%d. %-37s %12s   Hostility - %2d" %
                    (x, area.name, area.aType, area.hostility), 0)
            self.disp.display("0. Player Menu")
            self.disp.closeDisplay()
            try:
                # cmd = int(input())
                cmd = self.disp.get_input(True)
                # Make sure the GUI window is still open. Exit if it is not
                if not self.disp.window_is_open:
                    self.player.quit = True
                    return None
            except ValueError:
                self.disp.clearScreen()
                self.disp.displayHeader("Error")
                self.disp.display("That was not a valid response.")
                self.disp.closeDisplay()
                cmd = -1
                # time.sleep(DELAY)
                # input("\nEnter to continue")
                self.disp.wait_for_enter()

            if cmd == 0:
                self.player.playerMenu(self.currentQuests,
                                       self.completedQuests)
                if self.player.quit:
                    # TODO Exit the game completely
                    return None

        # Load the new area
        self.currentArea = choices[cmd - 1]
        self.currentArea.load(self.weapons, self.armor, self.misc,
                              self.enemies, self.npcs, self.events,
                              self.modifiers)

        self.importantQuestInfo.append(
            ["inAreaType", self.currentArea.aType, True, False])

        self.updateQuestInfo()

    def randomAreaChoices(self):
        '''This randomly generates areas for the player to choose from.'''
        choices = []
        # This is to guarantee that no "limited" areas are used more than once
        usedAreas = []

        # Grab all required areas and throw them into a seperate list. This is to
        # guarantee that they are generated.
        areatypes = self.currentArea.newAreaTypes[::]
        required = []
        for area in areatypes:
            if len(area) > 2:
                for flag in area[2]:
                    if flag == "required":
                        required.append(area)

        # Actually generate areas:
        for i in range(1, self.currentArea.newArea + 1):
            if len(required) > 0:
                newArea = required.pop(0)
            else:
                areatypes = self.currentArea.newAreaTypes[::]
                highroll = 0
                for aType in areatypes:
                    newroll = rollDice(aType[1])
                    alreadyUsed = False
                    if len(aType) > 2:
                        if "limited" in aType[2]:
                            if aType[0] in usedAreas:
                                alreadyUsed = True
                    if newroll > highroll and not alreadyUsed:
                        newArea = aType
                        highroll = newroll
            generatedArea = Area(self.areas[newArea[0]])
            usedAreas.append(newArea[0])
            choices.append(generatedArea)
        return choices

    def workOnBacklog(self):
        '''This collects and organizes the information in the backlog of
        actions to be carried out by the quest system.'''
        self.disp.dprint("\nWorking on backlog...")
        for collection in self.backlog:
            self.processActions(collection)
            self.backlog.remove(collection)

    def processActions(self, actions):
        '''This processes all actions that were given by the quest system.'''
        for action in actions:
            if action[0] == "say":
                self.disp.clearScreen()
                self.disp.displayHeader("Event")
                self.disp.display(action[1])
                self.disp.closeDisplay()
                if self.gameSettings["EVENTDELAYENABLED"]:
                    time.sleep(1)
                # input("\nEnter to continue")
                self.disp.wait_for_enter()
                self.disp.dprint("Processed say condition.")
            elif action[0] == "giveXP":
                self.player.xp += action[1]
                self.disp.display("You gained %d experience." % action[1])
                self.disp.dprint("Processed giveXP condition.")
            elif action[0] == "giveItem":
                itemKey = action[1]
                item = None
                if itemKey in self.weapons.keys():
                    item = generateWeapon(self.weapons[itemKey])
                elif itemKey in self.misc.keys():
                    item = Misc(self.misc[itemKey])
                elif itemKey in self.armor.keys():
                    item = Armor(self.armor[itemKey])
                if item != None:
                    self.disp.display("You recieved {}.".format(item.name))
                    self.player.inv.append(item)
            elif action[0] == "questComplete":
                for quest in self.currentQuests:
                    self.disp.dprint(action)
                    self.disp.dprint("Quest: {}".format(quest.qID))
                    self.disp.dprint("Completed Quest: {}".format(action[-1]))
                    if quest.qID == action[-1]:
                        quest.complete = True
                        self.completedQuests.append(quest)
                        self.currentQuests.remove(quest)
                self.disp.dprint("Processed questComplete condition.")
            elif action[0] == "spawnEnemy":
                self.currentArea.enemy.append(
                    Enemy(self.enemies[action[1]], self.weapons, self.armor,
                          self.misc, self.modifiers))
                self.disp.dprint("Processed spawnEnemy condition.")

    def updateQuestInfo(self):
        '''This updates all quest related variables and states.'''
        # update any currently loaded quests to see if any requirements are met
        self.disp.dprint("\nUnstarted quests:")
        for quest in self.possibleQuests:
            self.disp.dprint(quest)
            for event in self.importantQuestInfo:
                quest.setFlagToValue(event[0], event[1], event[2], event[3])
            do = quest.start()
            if do:
                self.currentQuests.append(quest)
                self.possibleQuests.remove(quest)
                self.backlog.append(do)
        self.disp.dprint("Started quests:")
        for quest in self.currentQuests:
            self.disp.dprint(quest)
            for event in self.importantQuestInfo:
                quest.setFlagToValue(event[0], event[1], event[2], event[3])
            do = quest.doNextStep()
            if do:
                self.backlog.append(do)
        self.disp.dprint("Completed Quests:")
        for quest in self.completedQuests:
            self.disp.dprint(quest)
        self.importantQuestInfo = []

    def displayMainMenu(self):
        self.disp.dprint("Debug Arguments: {}".format(self.settings["DEBUG"]))

        self.disp.clearScreen()
        self.disp.displayHeader("Main Menu")

        logo = random.choice(self.logos)
        firstLine = logo[0]
        self.disp.display(firstLine)
        for line in logo[1:]:
            self.disp.display(line, 0)

        self.disp.display(f'Version: {self.settings["VERSION"]}')

        self.disp.display(random.choice(self.descs))
        self.disp.display("1. New Game")
        self.disp.display("2. Settings", 0)
        self.disp.display("3. Data Packs", 0)
        self.disp.display("0. Exit")
        self.disp.closeDisplay()

    def openOptionsWindow(self):
        settingsOpen = True
        settingsPage = 0
        settingsNumOfPages = int(len(self.settings["GAMESETTINGS"]) / 9)

        while settingsOpen:
            toggleableOptions = self.displayOptions(settingsNumOfPages,
                                                    settingsPage)
            try:
                # cmd = int(input())
                cmd = self.disp.get_input(True)
            except ValueError:
                cmd = -1

            if cmd in range(1, 9) and cmd - 1 <= len(toggleableOptions):
                self.settings["GAMESETTINGS"][cmd - 1 +
                                              9 * settingsPage][2] ^= True
            elif cmd == 12 and settingsPage < settingsNumOfPages:
                settingsPage += 1
            elif cmd == 11 and settingsPage > 0:
                settingsPage -= 1
            elif cmd == 0:
                settingsOpen = False

    def displayOptions(self, numPages=1, page=0):
        self.disp.clearScreen()
        self.disp.displayHeader("Settings")

        startOptions = page * 9
        endOptions = 9 + (page * 9)

        listOfOptions = self.settings["GAMESETTINGS"][startOptions:endOptions]
        firstOption = listOfOptions.pop(0)
        enabled = "ENABLED" if firstOption[2] else "DISABLED"
        self.disp.display(f'1. {firstOption[1]:<50} {enabled:>18}')
        i = 1
        for option in listOfOptions:
            i += 1
            enabled = "ENABLED" if option[2] else "DISABLED"
            self.disp.display(f'{i}. {option[1]:<50} {enabled:>18}', 0)
        self.disp.display(
            "Input option # to toggle. Settings take effect on screen exit.")
        pagebreak = 1
        if page < numPages:
            self.disp.display("12. for next page of settings")
            pagebreak = 0
        if page > 0:
            self.disp.display("11. for previous page of settings", pagebreak)
            pagebreak = 0
        self.disp.display("0. to exit", pagebreak)
        self.disp.closeDisplay()

        return listOfOptions

    def openDataPacks(self):
        self.loadDataPackSettings()

        dataPacksWindow = True
        packPage = 0
        numPages = int(len(self.dataPackSettings["packsToLoad"]) / 9)

        while dataPacksWindow:
            toggleablePacks = self.displayPacks(numPages, packPage)
            try:
                # cmd = int(input())
                cmd = self.disp.get_input(True)
            except ValueError:
                cmd = -1

            if cmd in range(1, 9) and cmd - 1 <= len(toggleablePacks):
                if self.dataPackSettings["packsToLoad"][
                        cmd - 1 + 9 * packPage][0] != "official":
                    self.dataPackSettings["packsToLoad"][cmd - 1 + 9 *
                                                         packPage][1] ^= True
                else:
                    # TODO Display error when attempting to disable the official datapack.
                    pass
                    # The official data pack should be allowed to be disabled, only if
                    # another data pack is enabled
            elif cmd == 12 and packPage < numPages:
                packPage += 1
            elif cmd == 11 and packPage > 0:
                packPage -= 1
            elif cmd == 0:
                dataPacksWindow = False

        self.settings["DATAPACKSETTINGS"] = self.dataPackSettings

    def displayPacks(self, numPages=1, page=0):
        self.disp.clearScreen()
        self.disp.displayHeader("Data Packs")

        startOptions = page * 9
        endOptions = 9 + (page * 9)

        listOfOptions = self.dataPackSettings["packsToLoad"][
            startOptions:endOptions]
        firstOption = listOfOptions.pop(0)
        enabled = "ENABLED" if firstOption[1] else "DISABLED"
        firstOption = loadJson(self.dataPackSettings["folder"] +
                               firstOption[0] + "/meta.json")
        packName = firstOption["name"]
        packDesc = firstOption["desc"]
        packAuth = firstOption["author"]
        packType = firstOption["packType"].upper()

        self.disp.display(f'1. {packName:<50} {enabled:>18}')
        self.disp.display(f'\tPack Type: {packType}', 0)
        self.disp.display(f'\t{packDesc}', 0)
        self.disp.display(f'\tBy: {packAuth}', 0)

        i = 1

        for pack in listOfOptions:
            i += 1
            enabled = "ENABLED" if pack[1] else "DISABLED"
            pack = loadJson(self.dataPackSettings["folder"] + pack[0] +
                            "meta.json")
            packName = pack["name"]
            packDesc = pack["desc"]
            packAuth = pack["author"]

            self.disp.display(f'{i}. {packName:<50} {enabled:>18}')
            self.disp.display(f'\t{packDesc}', 0)
            self.disp.display(f'\tBy {packAuth}', 0)
        self.disp.display(
            "Input pack # to toggle. Changes to enabled data packs take effect on screen exit."
        )
        pagebreak = 1
        if page < numPages:
            self.disp.display("12. for next page of settings")
            pagebreak = 0
        if page > 0:
            self.disp.display("11. for previous page of settings", pagebreak)
            pagebreak = 0
        self.disp.display("0. to exit", pagebreak)
        self.disp.closeDisplay()

        return listOfOptions

    # GAME SHUTDOWN
    def shutdown_game(self):
        self.close_display()
Пример #12
0
    def testWalk(self):
        """ tests to see if walking is correctly updated """
        walker = Player()
        walker.state = 4 # walking upwards
        assert(walker.is_walking() == True)
        walker.state = 5  # walking right
        assert(walker.is_walking() == True)
        walker.state = 6  # walking downwards
        assert(walker.is_walking() == True)
        walker.state = 7  # walking left
        assert(walker.is_walking() == True)

        # what if we are idle

        walker.state = 2 # idle down state
        assert(walker.is_walking() == False)
Пример #13
0
 def testWinCount(self):
     """ tests to see if set_wins and get_wins is correctly updated """
     winTestP = Player()
     winTestP.set_wins(7)
     assert(winTestP.get_wins() == 7), "Player wins not successfully updated"
Пример #14
0
 def testKillCount(self):
     """ tests to see if set_kills and get_kills is correctly updated """
     killTestP = Player()
     killTestP.set_kills(3)
     assert(killTestP.get_kills() == 3), "player kills not successfully updated"
Пример #15
0
@author: terry
"""

import os
import sys
sys.path.append("..")
from deckClass import Deck
from playerClass import Player
from smarterPlayer import smarterPlayer
from interactivePlayer import interactivePlayer
from PokerTableClass import table

if __name__ == "__main__":
    print("TEST TEST TEST")

    p1 = Player("p1")
    p2 = Player("p2")
    p3 = Player("p3")
    p4 = Player("p4")
    p5 = Player("ip5")
    p6 = smarterPlayer("sp6")

    aTable = table()
    aTable.setMaxGames(1000)

    aTable.addPlayer(p1, 100)
    aTable.addPlayer(p2, 100)
    aTable.addPlayer(p3, 100)
    aTable.addPlayer(p4, 100)
    aTable.addPlayer(p5, 100)
    aTable.addPlayer(p6, 100)
Пример #16
0
class Game(object):
    """ This class represents an instance of the game. If we need to
        reset the game we'd just need to create a new instance of this
        class. """

    def __init__(self):
        """ Constructor. Create all our attributes and initialize
        the game. """

        # Create the player
        self.player = Player()
        
        self.screen = None
        
        self.LB = False
        self.B_Button = False
        
        self.minimap_on = False
        
        self.world_shift_x = 0
        self.world_shift_y = 0

        self.game_over = False
        self.paused = False
        
        self.controller = False

        self.joystick_count = pygame.joystick.get_count()
        if self.joystick_count == 0:
            # No joysticks!
            print("Error, I didn't find any joysticks.")
        else:
            # Use joystick #0 and initialize it
            self.my_joystick = pygame.joystick.Joystick(0)
            self.my_joystick.init()
            self.controller = True

        self.active_sprite_list = pygame.sprite.Group()
        
        self.active_sprite_list.add(self.player)
        
        self.current_level_no = 0
        
        self.level_list = []
        self.level_list.append(levels.Level(self.player))
        self.current_level = self.level_list[self.current_level_no]
        
        self.player.level = self.current_level
        
        #self.player.rect.x = self.current_level.pos_x
        #self.player.rect.y = self.current_level.pos_y

        #self.player.rect.x = 100
        #self.player.rect.y = 100

    def next_level(self):
        self.level_list.append(levels.Level(self.player))
        self.current_level_no += 1
        self.current_level = self.level_list[self.current_level_no]
        self.player.level = self.current_level
        self.player.change_x = 0
        self.player.change_y = 0
        self.player.player_health += 50

    def process_events(self):
        """ Process all of the events. Return a "True" if we need
            to close the window. """
        if self.controller:
            if self.paused:
                for event in pygame.event.get(): # User did something
                    if event.type == pygame.QUIT: # If user clicked close
                        return True
                        
                    if event.type == pygame.JOYBUTTONDOWN:
                        if self.my_joystick.get_button(7): # Start
                            self.paused = False
                            self.minimap_on = False
                
            else:
                for event in pygame.event.get(): # User did something
                    if event.type == pygame.QUIT: # If user clicked close
                        return True
        
                    if event.type == pygame.JOYBUTTONDOWN:
                        if self.my_joystick.get_button(0): # A
                            self.player.jump()
                        if self.my_joystick.get_button(1): # B
                            ()
                            #self.next_level()
                        if self.my_joystick.get_button(2): # X
                            if self.player.point_down:
                                self.player.hit_down = True
                                self.player.hit_up = False
                                self.player.max_fall_speed = 30
                                self.player.change_y = 20
                            elif self.player.point_up:
                                self.player.hit_up = True
                                self.player.hit_down = False
                            elif self.player.facing_right:
                                self.player.face = True
                                self.player.hit_up = False
                                self.player.hit_down = False
                            else:
                                self.player.face = False
                                self.player.hit_up = False
                                self.player.hit_down = False
                            self.player.melee_attack()
                        if self.my_joystick.get_button(3): # Y
                            () #self.minimap_on = not self.minimap_on
                        if self.my_joystick.get_button(5): # RB
                            self.player.jetpack()
                        if self.my_joystick.get_button(6): # Back
                            self.__init__()
                        if self.my_joystick.get_button(7): # Start
                            self.paused = True
                            self.minimap_on = True
                            
                    if self.my_joystick.get_button(4): # LB
                        if event.type == pygame.JOYBUTTONDOWN:
                            self.LB = True
                            self.player.hover()
                            self.player.hit_down = False
                    if self.LB and event.type == pygame.JOYBUTTONUP:
                            self.LB = False
                            self.player.stop_hover()
        
                if self.joystick_count != 0:
                    horiz_axis_pos = self.my_joystick.get_axis(0)
                    if horiz_axis_pos > 0.2 or horiz_axis_pos < -0.2:
                        self.player.rect.x += horiz_axis_pos * self.player.speed
                    if horiz_axis_pos > 0.2:
                        self.player.facing_right = True
                    elif horiz_axis_pos < -0.2:
                        self.player.facing_right = False
                    vert_axis_pos = self.my_joystick.get_axis(1)
                    if vert_axis_pos > 0.4:
                        self.player.point_down = True
                        self.player.point_up = False
                    elif vert_axis_pos < -0.4:
                        self.player.point_up = True
                        self.player.point_down = False
                    else:
                        self.player.point_up = False
                        self.player.point_down = False
                    triggers = self.my_joystick.get_axis(2)
                    if triggers < -0.5:
                        self.player.dodge_right()
                    elif triggers > 0.5:
                        self.player.dodge_left()
                return False
        else:
            if self.paused:
                for event in pygame.event.get(): # User did something
                    if event.type == pygame.QUIT: # If user clicked close
                        return True
                        
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_p:
                            self.paused = False
                            self.minimap_on = False
                
            else:
                for event in pygame.event.get(): # User did something
                    if event.type == pygame.QUIT: # If user clicked close
                        return True
                        
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_LEFT:
                            self.player.go_left()
                            self.player.facing_right = False
                        if event.key == pygame.K_RIGHT:
                            self.player.go_right()
                            self.player.facing_right = True
                        if event.key == pygame.K_UP:
                            self.player.point_up = True
                            self.player.point_down = False
                        if event.key == pygame.K_DOWN:
                            self.player.point_up = False
                            self.player.point_down = True
                        if event.key == pygame.K_z:
                            self.player.jump()
                        if event.key == pygame.K_x:
                            if self.player.point_down:
                                self.player.hit_down = True
                                self.player.hit_up = False
                                self.player.max_fall_speed = 30
                                self.player.change_y = 20
                            elif self.player.point_up:
                                self.player.hit_up = True
                                self.player.hit_down = False
                            elif self.player.facing_right:
                                self.player.face = True
                                self.player.hit_up = False
                                self.player.hit_down = False
                            else:
                                self.player.face = False
                                self.player.hit_up = False
                                self.player.hit_down = False
                            self.player.melee_attack()
                        if event.key == pygame.K_a:
                            self.player.jetpack()
                        if event.key == pygame.K_s:
                            self.player.hover()
                        if event.key == pygame.K_p:
                            self.paused = True
                            self.minimap_on = True
                        if event.key == pygame.K_ESCAPE:
                            return True
                
                    if event.type == pygame.KEYUP:
                        if event.key == pygame.K_LEFT and self.player.change_x < 0:
                            self.player.stop()
                        if event.key == pygame.K_RIGHT and self.player.change_x > 0:
                            self.player.stop()
                        if event.key == pygame.K_UP:
                            self.player.point_up = False
                            self.player.point_down = False
                        if event.key == pygame.K_DOWN:
                            self.player.point_up = False
                            self.player.point_down = False
                        if event.key == pygame.K_s:
                            self.player.stop_hover()
                        
            return False

    def run_logic(self):
        """
        This method is run each time through the frame. It
        updates positions and checks for collisions.
        """
        
        if self.paused:
            ()

        elif not self.game_over:
            self.active_sprite_list.update()

            # Update items in the level
            self.current_level.update()

            self.player.level = self.current_level
            
            player_hit_list = pygame.sprite.spritecollide(self.player, self.current_level.enemy_list, False)
            interactable_hit_list = pygame.sprite.spritecollide(self.player, self.current_level.interact_list, False)
            
            for platforms in self.current_level.platform_list:           
                enemy_platform_hit = pygame.sprite.spritecollide(platforms, self.current_level.enemy_list, False)
                for enemy in enemy_platform_hit:
                    if isinstance(enemy, eProjectile.Projectile) and enemy.hits_walls:
                        enemy.die()
            
            if len(player_hit_list) > 0:
                for enemy in player_hit_list:
                    self.player.get_hit(enemy.enemy_attack)
                    if isinstance(enemy, eProjectile.Projectile):
                        enemy.die()
                    
            if len(interactable_hit_list) > 0:
                for interactable in interactable_hit_list:
                    if isinstance(interactable, iDoor.Door) and self.player.point_up:
                        self.next_level()
                    if isinstance(interactable, iCoin.Coin):
                        interactable.pickup_money()
                    if isinstance(interactable, iGold.Gold):
                        interactable.pickup_gold()
                    if isinstance(interactable, iChest.Chest) and self.player.point_up:
                        interactable.open_chest()
                    
            if self.player.player_health <= 0:
                self.game_over = True
            
            for swords in self.player.sword_list:
                enemy_hit_list = pygame.sprite.spritecollide(swords, self.current_level.enemy_list, False)
                for enemy in enemy_hit_list:
                    if isinstance(enemy, eProjectile.Projectile):
                        ()
                    else:
                        enemy.enemy_get_hit(swords.sword_damage)

            left_wall = self.current_level.level_boundary_left + self.current_level.world_shift_x
            right_wall = self.current_level.level_boundary_right + self.current_level.world_shift_x
            floor = self.current_level.level_boundary_bottom + self.current_level.world_shift_y
            ceiling = self.current_level.level_boundary_top + self.current_level.world_shift_y

            self.cur_pos_x = self.current_level.level_boundary_left + self.player.rect.x - self.current_level.world_shift_x
            self.cur_pos_y = self.current_level.level_boundary_top + self.player.rect.y - self.current_level.world_shift_y
            
            move_bound = constants.SCREEN_WIDTH - 300

            # If the player gets near the right side, shift the world left (-x)
            if right_wall >= constants.SCREEN_WIDTH and self.player.rect.right >= move_bound:
                diff = self.player.rect.right - move_bound
                self.player.rect.right = move_bound
                self.current_level.shift_world_x(-diff)
                
            move_bound = 300

            # If the player gets near the left side, shift the world right (+x)
            if left_wall <= 0 and self.player.rect.left <= move_bound:
                diff = move_bound - self.player.rect.left
                self.player.rect.left = move_bound
                self.current_level.shift_world_x(diff)
                
            move_bound = 200

            if ceiling <= 0 and self.player.rect.top <= move_bound:
                diff = self.player.rect.top - move_bound
                self.player.rect.top = move_bound
                self.current_level.shift_world_y(-diff)
                
            move_bound = constants.SCREEN_HEIGHT - 400

            if floor >= constants.SCREEN_HEIGHT and self.player.rect.bottom >= move_bound:
                diff = move_bound - self.player.rect.bottom
                self.player.rect.bottom = move_bound
                self.current_level.shift_world_y(diff)


    def draw_HUD(self, screen):
        font = pygame.font.SysFont("serif", 25, True)
        text = font.render("Health: ", True, constants.BLACK)
        screen.blit(text, [20,20])
        pygame.draw.rect(screen, constants.RED, (110, 20, self.player.player_max_health, 25), 0)
        if self.player.player_health >= 0:
            pygame.draw.rect(screen, constants.DARK_GREEN, (110, 20, self.player.player_health, 25), 0)
        pygame.draw.rect(screen, constants.BLACK, (110, 20, self.player.player_max_health, 25), 3)
        
        text = font.render("Energy: ", True, constants.BLACK)
        screen.blit(text, [constants.SCREEN_WIDTH - text.get_width() - 150,20])
        pygame.draw.rect(screen, constants.RED, (constants.SCREEN_WIDTH- 150, 20, self.player.player_max_energy, 25), 0)
        if self.player.player_energy >= 0:
            pygame.draw.rect(screen, constants.ORANGE, (constants.SCREEN_WIDTH - 150, 20, self.player.player_energy, 25), 0)
        pygame.draw.rect(screen, constants.BLACK, (constants.SCREEN_WIDTH - 150, 20, self.player.player_max_energy, 25), 3)
        
        text = font.render("Money: " + str(self.player.player_money), True, constants.BLACK)
        screen.blit(text, [20, 50])
        text = font.render("Level no: " + str(self.current_level_no), True, constants.BLACK)
        screen.blit(text, [20, 80])
        
    def minimap(self, screen):
        p = 10
        buffer = 100
        center_x = (constants.SCREEN_WIDTH // 2)
        pygame.draw.rect(screen, constants.BLACK, (center_x - (constants.screen_tiles_width*p//2)-10, buffer-10, constants.screen_tiles_width*p+20, constants.screen_tiles_height*p+20), 0)
        pygame.draw.rect(screen, constants.WHITE, (center_x - (constants.screen_tiles_width*p//2), buffer, constants.screen_tiles_width*p, constants.screen_tiles_height*p), 0)
        for r in range(0, constants.screen_tiles_height):
            for c in range(0, constants.screen_tiles_width):
                if self.current_level.level[r][c] in (constants.PERM_WALL, constants.WALL, constants.FLOOR):
                    pygame.draw.rect(screen, constants.GREY, (center_x - (constants.screen_tiles_width*p//2) + c*p, r*p + buffer, p, p), 0)
        pygame.draw.rect(screen, constants.RED, ((center_x - (constants.screen_tiles_width*p//2)) + (self.cur_pos_x//constants.tile_size)*p, (self.cur_pos_y//constants.tile_size)*p + buffer, p, p*2), 0)
        
    def display_frame(self, screen):
        """ Display everything to the screen for the game. """
        screen.fill(constants.WHITE)
        
        if self.game_over:
            # font = pygame.font.Font("Serif", 25)
            self.current_level.draw(screen)
            self.draw_HUD(screen)
            font2 = pygame.font.SysFont('Arial Black', 40)
            text = font2.render("Game Over", True, constants.BLACK)
            font_small = pygame.font.SysFont('Arial Black', 20)
            text2 = font_small.render("Press Back to restart", True, constants.BLACK)
            center_x = (constants.SCREEN_WIDTH // 2) - (text.get_width() // 2)
            center_y = (constants.SCREEN_HEIGHT // 2) - (text.get_height() // 2)
            screen.blit(text, [center_x, center_y - 10])
            screen.blit(text2, [center_x, center_y + text2.get_height() + 10])
            
        elif self.paused:
            self.current_level.draw(screen)
            self.draw_HUD(screen)
            self.active_sprite_list.draw(screen)
            font2 = pygame.font.SysFont('Arial Black', 40)
            text = font2.render("Paused", True, constants.BLACK)
            center_x = (constants.SCREEN_WIDTH // 2) - (text.get_width() // 2)
            center_y = (constants.SCREEN_HEIGHT // 2) - (text.get_height() // 2)
            if self.minimap_on:
                self.minimap(screen)
            screen.blit(text, [center_x, 30])
            
        else:
            self.current_level.draw(screen)
            self.active_sprite_list.draw(screen)
            self.draw_HUD(screen)
            if self.minimap_on:
                self.minimap(screen)
                
        pygame.display.flip()
Пример #17
0
layout = loadtxt('a.txt', dtype=str)
rows, cols = layout.shape
for col in range(cols):
    for row in range(rows):
        value = layout[row][col]
        lead_x = col * width
        lead_y = row * height
        if value == '0':
            pos = (col * width, row * height)
            wall = Wall(blue, lead_x, lead_y)
            all_sprites.add(wall)
            walls.add(wall)

ghost = Ghost(12, white)
ghosts.add(ghost)
player = Player(size, ghosts)
all_sprites.add(player)
all_sprites.add(ghost)

###################################################
timer = 0
while not gameOver:
    timer = timer + 1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameOver = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                player.direction = 1
            elif event.key == pygame.K_DOWN:
                player.direction = 2
Пример #18
0
# set width/height
size = width, height = 800, 600

# create the screen
screen = pygame.display.set_mode(size)
# create screen rectangle for setting borders around screen
screenRect = screen.get_rect()

# set window title
pygame.display.set_caption(title)

# create clock object
clock = pygame.time.Clock()

# create a Player object
player = Player("player_soldier.png", width * 0.45, height * 0.5)

# create a Base object
base = Base("base3.png", 0, height * 0.4)

# list that will hold 4 different possible start spots for the zombies
zombieStartSpot = [(500,10), (775,100), (775, 500), (500,550)]

# this will be used to keep track of ticks
tickCount = 0

# container for the zombies
zombieGroup = pygame.sprite.Group()

# container for the bullets
bulletGroup = pygame.sprite.Group()
Пример #19
0
    def __init__(self, parent, controller, vs, gameLength):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.vs = vs
        self.gameLength = gameLength

        compName = tk.StringVar()
        compRound1 = tk.StringVar()
        compRound2 = tk.StringVar()
        compRound3 = tk.StringVar()
        compRound4 = tk.StringVar()
        compRound5 = tk.StringVar()
        playerName = tk.StringVar()
        playerRound1 = tk.StringVar()
        playerRound2 = tk.StringVar()
        playerRound3 = tk.StringVar()
        playerRound4 = tk.StringVar()
        playerRound5 = tk.StringVar()
        game1Title = tk.StringVar()
        game2Title = tk.StringVar()
        game3Title = tk.StringVar()
        game4Title = tk.StringVar()
        game5Title = tk.StringVar()
        compName.set("Computer")
        compRound1.set("0")
        compRound2.set("0")
        compRound3.set("0")
        compRound4.set("0")
        compRound5.set("0")
        playerName.set("Player 1")
        playerRound1.set("0")
        playerRound2.set("0")
        playerRound3.set("0")
        playerRound4.set("0")
        playerRound5.set("0")
        game1Title.set("Game 1")
        game2Title.set("Game 2")
        game3Title.set("Game 3")
        game4Title.set("Game 4")
        game5Title.set("Game 5")

        comp = Player("Computer", [compName, compRound1, compRound2, compRound3, compRound4, compRound5])
        player = Player("Player 1", [playerName, playerRound1, playerRound2, playerRound3, playerRound4, playerRound5])

        title = tk.Label(self, text = "ROCK Paper Scissors", fg= "#800D02")
        title.config(font=("Arial Black", 44))
        title.pack()

        curScores = tk.Label(self, text="Scores:")
        curScores.pack()
      
        scoreCardFrame = tk.Frame(self, height = 100, width = 700)
        playerLabel = tk.Label(scoreCardFrame, text="Player 1")
        computerLabel = tk.Label(scoreCardFrame, text="Computer")
        numGames = 3
        if gameLength == "Best 3 of 5":
            numGames = 5
        titles = Player("titles", ["", game1Title, game2Title, game3Title, game4Title, game5Title])
        for r in range(3):
            for c in range(numGames+1):
                rowInfo = Player("", [])
                if r == 0:
                    rowInfo = titles
                if r == 1:
                    rowInfo = comp
                if r == 2:
                    rowInfo = player
                Label = tk.Label(scoreCardFrame, textvariable=rowInfo.scores[c])
                Label.grid(row=r, column=c)

        scoreCardFrame.pack()

        image = Image.open('ball.png')
        image = image.resize((600, 600))
        image = ImageTk.PhotoImage(image)
        self.imageView = tk.Label(self, height = 350, width = 250, bg ="#9CAAFF", image = image)
        self.imageView.pack(side="left", padx=10, pady=10)



        emojes = tk.Label(self, text = "")
        emojes.config(font=("Arial Black", 70))
        emojes.pack()

        goButton = tk.Button(self, text = 'Start Round', fg='green', bg='red', width=30, height=6)
        goButton.pack()

        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        tempButton = tk.Button(self, text="add point for computer")
        def incrementComputer(event):
             #compRound2.set("1")
             comp.scores[2].set("1")
        tempButton.bind("<Button-1>", incrementComputer)
        tempButton.pack()

        button.pack()
        self.thread = threading.Thread(target=self.getVideo, args=())
        self.thread.start()

        def didTapStartButton(event):
            beginRound()
        goButton.bind("<Button-1>", didTapStartButton)

        def beginRound():
            if self.curRoundNumber > 3:
                endGame()
            else:
                showRock()
                self.after(1000, showPaper)
                self.after(2000, showScissors)
                self.after(3000, showGo)
                self.after(3100, detectHand)

        def endGame():
            print("Game over!")


        def showRock():
            emojes["text"] = "✊"
        def showPaper():
            emojes["text"] = "✋"
        def showScissors():
            emojes["text"] = "✌️"
        def showGo():
            emojes["text"] = "Go!"
            print("SHOWING GOOOOOO!")

        def detectHand():
            #global curRoundNumber
            roundNumber = self.curRoundNumber
            print("Running detect hand!!!!!!!")
            counter = 0
            usersAnswers = []
            while counter < 500:
                frame = self.vs.read()
                tempUserAnswer = getFingerCount(frame, False)
                print(tempUserAnswer)
                usersAnswers.append(tempUserAnswer)
                counter += 1

            #sort list by most common
            result = [item for items, c in Counter(usersAnswers).most_common() 
                                      for item in [items] * c] 
            usersAnswer = result[0]
            computerAnser = pickRandom()
            print("User says " + str(usersAnswer))
            print("Computer says " + str(computerAnser))

            if usersAnswer != computerAnser:
                findWinner(computerAnser, usersAnswer, roundNumber)
                roundNumber += 1
            else:
                print("Tie...try again!")
            self.curRoundNumber = roundNumber

            # time.sleep(3)
            # if roundNumber == 4:
            #     endGame()
            # else:
            #     beginRound()

        def pickRandom():
            compAnswer = random.randint(1,3)
            if compAnswer == 1:
                showRock()
                return(1)
            elif compAnswer == 2:
                showPaper()
                return(2)
            else:
                showScissors()
                return(3)

        def findWinner(compAnswer, userAnswer, roundNum):
            print("Updating section " + str(roundNum))
            if compAnswer == 1:
                if userAnswer == 2:
                    print("Player wins!")
                    player.scores[roundNum].set("1")
                else:
                    print("Computer wins!")
                    comp.scores[roundNum].set("1")
            if compAnswer == 2:
                if userAnswer == 3:
                    print("Player wins!")
                    player.scores[roundNum].set("1")
                else:
                    print("Computer wins!")
                    comp.scores[roundNum].set("1")
            if compAnswer == 3:
                if userAnswer == 1:
                    print("Player wins!")
                    player.scores[roundNum].set("1")
                else:
                    print("Computer wins!")
                    comp.scores[roundNum].set("1")
Пример #20
0
    print("level read in")
    return readlevel


level = Floor()
level.floorgen()
#level = readfloor("currentfloor.txt")
level.updateFloor()
level.printFloor()



for file in listdir('./'):
    print("in file loop")
    if file.find("player11") != -1:
        user = Player()
        user.name = file.strip("player11.txt")
        user.readplayer()
        userlist.append(user)
        usernamelist.append(user.name)



class commands():
    "game commands"

    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context=True, no_pm=False)
    @asyncio.coroutine
Пример #21
0
class Model():
    def __init__(self, screenWidth, screenHeight, hitboxes=False):
        self.screenWidth = screenWidth
        self.screenHeight = screenHeight
        self.hitboxes = hitboxes
        self.view = View(screenWidth, screenHeight)
        self.resourceHandler = ResourceHandler()
        self.num_levels = 3
        self.next_new_life_score_level = 100
        self.lifes = 3

        self.difficulties = 3
        # easy = 0, normal = 1, hard = 2
        self.difficulty = 1

        # per difficulty
        self.boss_life = [75, 150, 250]
        self.num_enemies = [10, 15, 25]
        self.time_between_enemies = [27 * 5, 27 * 4, int(27 * 3.5)]

        self.start_screen = False
        self.game_over = False
        self.in_level = False
        self.level_finished = False
        self.paused = False

        self.new_high_score_index = None
        self.new_high_score_name = []

        # the following counters are used to prevent that
        # single key presses are registered more than once (in subsequent frames)
        self.high_score_name_counter = 0
        self.start_screen_counter = 0
        self.game_over_counter = 0
        self.pause_counter = 0
        self.difficulty_counter = 0
        self.instruction_screen_counter = 0

        self.end_music_started = False

        self.startScreen()

    """
    Prepares the start screen
    """

    def startScreen(self):
        self.start_screen = True
        self.game_over = False
        self.view.playMusic('start_screen')
        self.curr_level = 0
        self.view.startScreen(self.difficulty)

    """
    Prepares the instruction screen
    """

    def instructionScreen(self):
        self.instruction_screen = True
        self.start_screen = False
        self.instruction_screen_counter = 5
        self.view.instructionScreen()

    """
    Pause the game, can only pause when in an actual level and after a shorter
    cooldown (10 frames)
    """

    def paus(self):
        if self.in_level and not self.level_finished and self.pause_counter == 0:
            if not self.paused:
                self.paused = True
                self.view.paus()
            else:
                self.paused = False
            self.pause_counter = 10

    """
    The player has pressed the return button, it is used between levels, to
    start the next level etc.
    """

    def enter(self):
        # do nothing if we are in a level and have not finished it
        if self.in_level and not self.level_finished:
            return

        # start new game if on start screen, if start screen counter is zero
        if self.start_screen and self.start_screen_counter == 0:
            self.instructionScreen()

        if self.instruction_screen and self.instruction_screen_counter == 0:
            self.newGame()

        # go to start screen if on high score screen and no new high score
        elif  self.game_over and self.game_over_counter == 0 and \
                                self.new_high_score_index is None:
            self.start_screen_counter = 8
            self.startScreen()

        # if on high score screen with new high score and a choosen name
        # save high score and start new game
        elif  self.game_over and self.new_high_score_index is not None and \
                            len(self.new_high_score_name) == 3:
            self.writeHighScore()
            self.start_screen_counter = 8
            self.startScreen()

        # if we have finished a level, move to the next one
        elif self.level_finished:
            self.nextLevel()

    """
    Start a new game, starting level 1
    """

    def newGame(self):
        self.instruction_screen = False
        self.score = 0
        self.lifes = 3
        self.curr_level = 1
        self.next_new_life_score_level = 100
        self.initializeLevel(self.curr_level)

    """
    Starts the next level. If current level is the last one - goes to high
    score screen (game over screen)
    """

    def nextLevel(self):

        if self.curr_level == self.num_levels:
            self.game_over_counter = 8
            self.gameOver()
        else:
            # recreate player object between levels, so saves number of lifes
            self.lifes = self.player.lifes
            self.curr_level += 1
            self.initializeLevel(self.curr_level)

    """
    Initializes the specificed level
    """

    def initializeLevel(self, level):
        self.enemies = []
        self.platforms = []
        self.projectiles = []
        self.enemy_clock = 0
        self.powerups = []
        self.enemies_killed = 0
        self.enemy_projectiles = []
        self.boss = False
        self.boss_dead = False
        self.boss_dead_counter = 0
        self.level_finished = False
        self.game_over = False
        self.new_high_score_index = None
        self.new_high_score_name = []
        self.end_music_started = False

        if level == 1:

            self.surfaceLevel = 470
            x1 = random.randrange(self.screenWidth - 150)
            x2 = random.randrange(self.screenWidth - 150)
            self.enemies.append(
                Goblin(x1, 55, 5, 8, 1, self.screenWidth, self.surfaceLevel,
                       self.resourceHandler, self.hitboxes))
            self.enemies.append(
                Zombie(x2, 55, 6, 8, -1, self.screenWidth, self.surfaceLevel,
                       self.resourceHandler, self.hitboxes))
            self.platforms.append(Platform(150, 300, 50, 50, self.curr_level))
            self.platforms.append(Platform(570, 300, 50, 50, self.curr_level))
            self.view.playMusic('level1')
            self.boss_music = 'bossmusic1'
            self.boss_type = ZombieBoss
            x_start_position = 300
            y_start_position = 400
            self.player = Player(x_start_position,
                                 y_start_position,
                                 self.lifes,
                                 self.screenHeight,
                                 self.screenWidth,
                                 self.resourceHandler,
                                 surfaceLevel=self.surfaceLevel,
                                 showHitboxes=self.hitboxes)

        elif level == 2:

            self.surfaceLevel = 460
            self.platforms.append(Platform(150, 300, 50, 50, self.curr_level))
            self.platforms.append(Platform(255, 240, 50, 50, self.curr_level))
            self.platforms.append(Platform(570, 300, 50, 50, self.curr_level))
            self.platforms.append(Platform(465, 240, 50, 50, self.curr_level))
            x1 = random.randrange(self.screenWidth - 150)
            x2 = random.randrange(self.screenWidth - 150)
            self.enemies.append(
                Mushroom(x1, 55, 3, 10, 1, self.screenWidth, self.surfaceLevel,
                         self.resourceHandler, self.hitboxes))
            self.enemies.append(
                FlyingEye(x2, 55, 5, 2, -1, self.screenWidth,
                          self.surfaceLevel, self.resourceHandler,
                          self.hitboxes))
            self.view.playMusic('level2')
            self.boss_music = 'bossmusic2'
            self.boss_type = FlyingEyeBoss
            x_start_position = 300
            y_start_position = 400
            self.player = Player(x_start_position,
                                 y_start_position,
                                 self.lifes,
                                 self.screenHeight,
                                 self.screenWidth,
                                 self.resourceHandler,
                                 surfaceLevel=self.surfaceLevel,
                                 showHitboxes=self.hitboxes)

        elif level == 3:

            self.surfaceLevel = None
            self.platforms.append(Platform(60, 360, 50, 50, self.curr_level))
            self.platforms.append(Platform(100, 200, 50, 50, self.curr_level))
            self.platforms.append(Platform(40, 50, 50, 50, self.curr_level))
            self.platforms.append(Platform(155, 420, 50, 50, self.curr_level))
            self.platforms.append(Platform(165, 300, 50, 50, self.curr_level))
            self.platforms.append(Platform(245, 370, 50, 50, self.curr_level))
            self.platforms.append(Platform(270, 240, 50, 50, self.curr_level))
            self.platforms.append(Platform(375, 180, 50, 50, self.curr_level))
            self.platforms.append(Platform(480, 240, 50, 50, self.curr_level))
            self.platforms.append(Platform(585, 300, 50, 50, self.curr_level))
            self.platforms.append(Platform(690, 360, 50, 50, self.curr_level))
            self.platforms.append(Platform(650, 200, 50, 50, self.curr_level))
            self.platforms.append(Platform(600, 50, 50, 50, self.curr_level))
            self.platforms.append(Platform(480, 50, 50, 50, self.curr_level))
            self.platforms.append(Platform(500, 370, 50, 50, self.curr_level))
            x1 = random.randrange(self.screenWidth - 150)
            x2 = random.randrange(self.screenWidth - 150)
            self.enemies.append(
                FlyingEye(x1, 55, 4, 3, 1, self.screenWidth, self.surfaceLevel,
                          self.resourceHandler, self.hitboxes))
            self.enemies.append(
                FlyingEye(x2, 55, 4, 3, -1, self.screenWidth,
                          self.surfaceLevel, self.resourceHandler,
                          self.hitboxes))
            self.view.playMusic('level3')
            self.boss_music = 'bossmusic2'
            self.boss_type = FlyingEyeBoss
            x_start_position = 60
            y_start_position = 230
            self.player = Player(x_start_position,
                                 y_start_position,
                                 self.lifes,
                                 self.screenHeight,
                                 self.screenWidth,
                                 self.resourceHandler,
                                 surfaceLevel=self.surfaceLevel,
                                 showHitboxes=self.hitboxes)

        self.in_level = True

    """
    Method called when player runs out of lifes, or when the playe
    has beat the game
    """

    def gameOver(self):

        self.game_over = True
        if self.player.lifes == 0:
            self.view.playMusic('game_over')
        elif not self.end_music_started:
            self.view.playMusic('end_music')
            self.end_music_started = True

        self.in_level = False
        self.level_finished = False

        self.high_scores = self.loadHighScores()

        if self.score > 0 and (len(self.high_scores) < 5 or \
                    self.score > self.high_scores[-1][0]):

            # set name of new score to a in order to make it come after any
            # other entry with the same score. Score tuples are sorted on score, but
            # if the score is equal they are sorted on name
            self.high_scores.append((self.score, 'a'))
            self.high_scores.sort(reverse=True)

            # if more than 5 high scores pop lowest score
            if len(self.high_scores) > 5:
                self.high_scores.pop()

            # get index of new score in sorted list
            self.new_high_score_index = self.high_scores.index(
                (self.score, 'a'))

        self.view.gameOver(self.curr_level,
                           self.high_scores,
                           self.difficulty,
                           high_score_name=self.new_high_score_name,
                           high_score_index=self.new_high_score_index)

    """
    Loads high scores from text file
    """

    def loadHighScores(self):
        difficulties = ['easy', 'medium', 'hard']
        with open('highscore-' + str(difficulties[self.difficulty]) + '.txt',
                  'r') as f:
            lines = f.readlines()
            high_scores = []
            for line in lines:
                (score, name) = line.split()
                high_scores.append((int(score), name))

            return high_scores

    """
    Used for writing the players name when he gets a new high score
    """

    def addCharToName(self, i):

        if self.new_high_score_index is not None and \
           len(self.new_high_score_name) < 3 and \
           self.high_score_name_counter == 0:

            chars = 'abcdefghijklmnopqrstuvwxyz'
            self.new_high_score_name.append(chars[i])
            self.high_score_name_counter = 5

            self.view.gameOver(self.curr_level,
                               self.high_scores,
                               self.difficulty,
                               high_score_name=self.new_high_score_name,
                               high_score_index=self.new_high_score_index)

    """
    Removes the last choosen character from the players name when he gets
    a new high score
    """

    def removeCharFromName(self):
        if self.new_high_score_index is not None and \
           len(self.new_high_score_name) > 0 and \
           self.high_score_name_counter == 0:

            self.new_high_score_name.pop()
            self.high_score_name_counter = 5
            self.view.gameOver(self.curr_level,
                               self.high_scores,
                               self.difficulty,
                               high_score_name=self.new_high_score_name,
                               high_score_index=self.new_high_score_index)

    """
    Writes the new high score to the high score text file
    """

    def writeHighScore(self):
        # inser correct name in high score list
        self.high_scores[self.new_high_score_index] = (self.score, "".join(
            self.new_high_score_name))
        # format high score list as strings
        high_scores_format = []
        for hs in self.high_scores:
            high_scores_format.append(str(hs[0]) + " " + hs[1] + "\n")

        # write to the file
        difficulties = ['easy', 'medium', 'hard']
        with open('highscore-' + str(difficulties[self.difficulty]) + '.txt',
                  'w') as f:
            f.writelines(high_scores_format)

    """
    Methods for controlling the player, if not in a level (or start screen)
    or if the game is paused they do nothing. walkLeft/right are also used
    for choosing the difficulty on the start screen.
    """

    def walkLeft(self):
        #choosing difficulty on start screen
        if self.start_screen and self.difficulty_counter == 0:
            self.difficulty = max(0, self.difficulty - 1)
            self.difficulty_counter = 5
            self.view.startScreen(self.difficulty)

        if self.in_level and not self.paused:
            self.player.walkLeft(self.platforms)

    def walkRight(self):
        #choosing difficulty on start screen
        if self.start_screen and self.difficulty_counter == 0:
            self.difficulty = min(2, self.difficulty + 1)
            self.difficulty_counter = 5
            self.view.startScreen(self.difficulty)

        if self.in_level and not self.paused:
            self.player.walkRight(self.platforms)

    def jump(self):
        if self.in_level and not self.paused:
            self.player.jump()

    def fire(self):
        if self.in_level and not self.paused:
            # can't fire more than 5 projectiles at the same time (9 if shootThreeDirections
            # power up is active
            if len(self.projectiles
                   ) < 5 or self.player.shootThreeDirections and len(
                       self.projectiles) < 9:
                projectiles = self.player.fire()
                if projectiles != -1:
                    for projectile in projectiles:
                        self.projectiles.append(projectile)

    """
    The main update function which is run for every frame of the game
    """

    def update(self):

        if self.difficulty_counter > 0:
            self.difficulty_counter -= 1

        if self.start_screen_counter > 0:
            self.start_screen_counter -= 1

        if self.instruction_screen_counter > 0:
            self.instruction_screen_counter -= 1

        if self.game_over_counter > 0:
            self.game_over_counter -= 1

        if self.high_score_name_counter > 0:
            self.high_score_name_counter -= 1

        # dealing with paused game state
        if self.pause_counter > 0:
            self.pause_counter -= 1

        # if paused or not in a level just return
        if self.paused or not self.in_level:
            return

        # give extra life for every 100 points
        if self.score >= self.next_new_life_score_level:
            x = random.randrange(self.screenWidth - 100)
            self.powerups.append(Life(x, 55, 32, 35, 2, self.surfaceLevel))
            self.next_new_life_score_level += 100

        if self.boss_dead:
            self.boss_dead_counter += 1

            if self.boss_dead_counter == 27 * 6:
                self.view.playMusic('endmusic')
                self.end_music_started = True

        # remove projectiles which are off screen
        for projectile in self.projectiles:
            if not projectile.update():
                self.projectiles.pop(self.projectiles.index(projectile))

        # update enemies
        for enemy in self.enemies:
            if enemy.remove:
                self.enemies.pop(self.enemies.index(enemy))

            projectiles = enemy.move()
            if projectiles is not None:
                for projectile in projectiles:
                    self.enemy_projectiles.append(projectile)

        # update enemy projectiles
        for projectile in self.enemy_projectiles:
            if not projectile.update():
                self.enemy_projectiles.pop(
                    self.enemy_projectiles.index(projectile))

        # update power-ups
        for powerup in self.powerups:
            if not powerup.update():
                self.powerups.pop(self.powerups.index(powerup))

        # update player
        if self.player.updateEveryFrame(self.platforms) == "game_over":
            self.gameOver()
            return

        # add new enemies
        self.enemy_clock += 1

        if not self.boss_dead:
            if (self.enemy_clock == self.time_between_enemies[self.difficulty] \
                        and self.enemies_killed < self.num_enemies[self.difficulty]) or \
                            (self.enemy_clock == 27*8 and self.boss):
                self.addNewEnemy()
                self.enemy_clock = 0

            elif not self.boss and self.enemy_clock == 27 * 8:
                self.view.playMusic(self.boss_music)
                self.addNewEnemy(boss=True)
                self.enemy_clock = 0
                self.boss = True

        # do enemies hit player
        for enemy in self.enemies:
            if not enemy.dead:
                if self.compareHitboxes(self.player.hitbox, enemy.hitbox):
                    hit = self.player.hit()
                    if hit == 'game_over':
                        self.gameOver()
                        return

        # do player get power up
        for powerup in self.powerups:
            if self.compareHitboxes(self.player.hitbox, powerup.hitbox):
                powerup.effect(self.player, self, self.view)
                powerup.remove = True

        # do enemy projectiles hit player
        for projectile in self.enemy_projectiles:
            if self.compareHitboxes(self.player.hitbox, projectile.hitbox):

                # can cause a bug so in try/except block
                if projectile.remove():
                    try:
                        self.enemy_projectiles.pop(
                            self.enemy_projectiles.index(projectile))
                    except:
                        pass

                hit = self.player.hit()
                if hit == 'game_over':
                    self.gameOver()
                    return
                elif hit == 'lost_life':
                    self.view.playMusic('lost_life')

        # do projectlies hit enemies
        for projectile in self.projectiles:
            for enemy in self.enemies:
                if not enemy.dead:
                    if self.compareHitboxes(enemy.hitbox, projectile.hitbox):
                        projectile.hitEnemySound(self.view)
                        enemy.hit(projectile.x_direction, projectile.damage,
                                  projectile.damageMultiplier)
                        if enemy.dead:
                            if isinstance(enemy, self.boss_type):
                                self.score += 100
                                # kill all other current enemies
                                for e in self.enemies:
                                    e.dead = True
                                self.view.playMusic('victory')
                                self.boss_dead = True
                                self.level_finished = True

                            else:
                                self.score += 1
                                self.enemies_killed += 1

                                # add treasure/power-up
                                x = random.randrange(self.screenWidth - 100)
                                if self.boss:
                                    r = random.randint(1, 4)
                                else:
                                    r = random.randint(1, 6)
                                if r == 1:
                                    self.powerups.append(
                                        Fireball(x, 55, 41, 40, 2,
                                                 self.surfaceLevel))
                                elif r == 2:
                                    self.powerups.append(
                                        DamageX2(x, 55, 41, 40, 2,
                                                 self.surfaceLevel))
                                elif r == 3:
                                    if self.curr_level == 1:
                                        self.powerups.append(
                                            ShootBothWays(
                                                x, 55, 41, 40, 2,
                                                self.surfaceLevel))
                                    elif self.curr_level == 2 or self.curr_level == 3:
                                        self.powerups.append(
                                            ShootThreeWays(
                                                x, 55, 41, 40, 2,
                                                self.surfaceLevel))
                                else:
                                    self.powerups.append(
                                        Treasure(x, 55, 41, 40, 2,
                                                 self.surfaceLevel))

                        # bug sometimes crashes so put in try/except
                        if projectile.remove():
                            try:
                                self.projectiles.pop(
                                    self.projectiles.index(projectile))
                            except:
                                pass


        self.view.redraw_game_window(self.curr_level, self.player, self.enemies, self.enemy_projectiles, self.platforms, \
                                            self.projectiles, self.powerups, self.score, self.boss_dead, self.difficulty)

    """
    Returns true if the two hitboxes overlap, otherwise returns false
    """

    def compareHitboxes(self, hitbox1, hitbox2):

        #bug
        if hitbox1 is None or hitbox2 is None:
            return False

        if  hitbox1[0] < hitbox2[0] + hitbox2[2] and \
                hitbox1[0] + hitbox1[2] > hitbox2[0] and \
                hitbox1[1] < hitbox2[1] + hitbox2[3] and \
                hitbox1[1] + hitbox1[3] > hitbox2[1]:
            return True
        else:
            return False

    """
    Adds a new enemy
    """

    def addNewEnemy(self, boss=False):

        while True:
            x = random.randrange(self.screenWidth - 150)
            # don't add new enemies to close to the player
            if abs(self.player.x - x) > 220:
                break

        dir = random.randrange(2)
        if dir == 0:
            dir = -1

        # adding the boss
        if boss:
            if self.curr_level == 1:
                self.enemies.append(
                    ZombieBoss(x, 55, 3, self.boss_life[self.difficulty], dir,
                               self.screenWidth, self.surfaceLevel,
                               self.resourceHandler, self.hitboxes))
            elif self.curr_level == 2:
                self.enemies.append(
                    FlyingEyeBoss(x, 0, 3, self.boss_life[self.difficulty],
                                  dir, self.screenWidth, self.surfaceLevel,
                                  self.resourceHandler, self.hitboxes))
            elif self.curr_level == 3:
                boss = FlyingEyeBoss2(x, 0, 3,
                                      self.boss_life[self.difficulty] // 2,
                                      dir, self.screenWidth, self.surfaceLevel,
                                      self.resourceHandler, self.hitboxes)
                if self.difficulty == 2:
                    boss.setHardLevel()
                self.enemies.append(boss)

        # adding normal enemies
        else:

            if self.curr_level == 1:
                enemy = random.randrange(2)
                if enemy == 0:
                    self.enemies.append(
                        Zombie(x, 55, 6, 8, dir, self.screenWidth,
                               self.surfaceLevel, self.resourceHandler,
                               self.hitboxes))
                else:
                    self.enemies.append(
                        Goblin(x, 55, 5, 8, dir, self.screenWidth,
                               self.surfaceLevel, self.resourceHandler,
                               self.hitboxes))

            if self.curr_level == 2:
                enemy = random.randrange(3)
                if enemy == 0:
                    self.enemies.append(
                        Mushroom(x, 55, 3, 10, dir, self.screenWidth,
                                 self.surfaceLevel, self.resourceHandler,
                                 self.hitboxes))
                elif enemy == 1:
                    self.enemies.append(
                        FlyingEye(x, 55, 5, 2, dir, self.screenWidth,
                                  self.surfaceLevel, self.resourceHandler,
                                  self.hitboxes))
                else:
                    self.enemies.append(
                        Zombie(x, 55, 5, 8, dir, self.screenWidth,
                               self.surfaceLevel, self.resourceHandler,
                               self.hitboxes))

            if self.curr_level == 3:
                y = random.randrange(50, self.screenHeight - 100)
                self.enemies.append(
                    FlyingEye(x, y, 4, 3, dir, self.screenWidth,
                              self.surfaceLevel, self.resourceHandler,
                              self.hitboxes))
Пример #22
0
class GameInstance:

    def __init__(self):
        self.score = 0
        self.scroll = 0
        self.cam_speed = 700

        self.clouds = []
        self.projectiles = []

        self.stage = stageGeneration.Stage(self.projectiles)

        cloud_amount = 3
        for i in range(cloud_amount):
            min_x = i * (1920/cloud_amount)
            max_x = min_x+(1920/cloud_amount-500)
            x = random.randrange(min_x, max_x)
            y = random.randrange(-100, 100)
            background.Cloud((x, y), self.clouds)

        self.Mark = Player(position=(300, -200),
                           speed=(self.cam_speed, 0),
                           size=(83, 111),
                           gun='shotgun',
                           platforms=self.stage.platforms,
                           spikes=self.stage.spikes,
                           coins=self.stage.coins,
                           projectiles=self.projectiles,
                           enemies=self.stage.enemies)

    def update(self, delta_time, jump_pressed, shoot_pressed, sound_on):
        self.scroll += self.cam_speed * delta_time
        self.score = round(self.scroll / 200)

        for Cloud in self.clouds:
            Cloud.update(self.scroll)

        self.stage.update(self.scroll, delta_time)

        for projectile in self.projectiles:
            projectile.update(delta_time)

        self.Mark.update(delta_time, self.cam_speed, jump_pressed, shoot_pressed, sound_on)
        return self.Mark.coin_collected, self.Mark.dead, self.score

    def draw(self, screen, screen_scale):
        screen.fill((74, 228, 255))

        for cloud in self.clouds:
            cloud.draw(screen, self.scroll, screen_scale)

        for platform in self.stage.platforms:
            platform.draw(screen, self.scroll, screen_scale)

        for spike in self.stage.spikes:
            spike.draw(screen, self.scroll, screen_scale)

        for coin in self.stage.coins:
            coin.draw(screen, self.scroll, screen_scale)

        for enemy in self.stage.enemies:
            enemy.draw(screen, self.scroll, screen_scale)

        for projectile in self.projectiles:
            projectile.draw(screen, self.scroll, screen_scale)

        self.Mark.draw(screen, self.scroll, screen_scale)
Пример #23
0
 def setUp(self):
     testPlayer = Player()
Пример #24
0
 def testNumber(self):
     """ tests to see if a player's number is correctly updated """
     numTestP = Player()
     numTestP.number = 0
     assert(numTestP.number == 0), "player number was not correctly set!"
Пример #25
0
    def initializeLevel(self, level):
        self.enemies = []
        self.platforms = []
        self.projectiles = []
        self.enemy_clock = 0
        self.powerups = []
        self.enemies_killed = 0
        self.enemy_projectiles = []
        self.boss = False
        self.boss_dead = False
        self.boss_dead_counter = 0
        self.level_finished = False
        self.game_over = False
        self.new_high_score_index = None
        self.new_high_score_name = []
        self.end_music_started = False

        if level == 1:

            self.surfaceLevel = 470
            x1 = random.randrange(self.screenWidth - 150)
            x2 = random.randrange(self.screenWidth - 150)
            self.enemies.append(
                Goblin(x1, 55, 5, 8, 1, self.screenWidth, self.surfaceLevel,
                       self.resourceHandler, self.hitboxes))
            self.enemies.append(
                Zombie(x2, 55, 6, 8, -1, self.screenWidth, self.surfaceLevel,
                       self.resourceHandler, self.hitboxes))
            self.platforms.append(Platform(150, 300, 50, 50, self.curr_level))
            self.platforms.append(Platform(570, 300, 50, 50, self.curr_level))
            self.view.playMusic('level1')
            self.boss_music = 'bossmusic1'
            self.boss_type = ZombieBoss
            x_start_position = 300
            y_start_position = 400
            self.player = Player(x_start_position,
                                 y_start_position,
                                 self.lifes,
                                 self.screenHeight,
                                 self.screenWidth,
                                 self.resourceHandler,
                                 surfaceLevel=self.surfaceLevel,
                                 showHitboxes=self.hitboxes)

        elif level == 2:

            self.surfaceLevel = 460
            self.platforms.append(Platform(150, 300, 50, 50, self.curr_level))
            self.platforms.append(Platform(255, 240, 50, 50, self.curr_level))
            self.platforms.append(Platform(570, 300, 50, 50, self.curr_level))
            self.platforms.append(Platform(465, 240, 50, 50, self.curr_level))
            x1 = random.randrange(self.screenWidth - 150)
            x2 = random.randrange(self.screenWidth - 150)
            self.enemies.append(
                Mushroom(x1, 55, 3, 10, 1, self.screenWidth, self.surfaceLevel,
                         self.resourceHandler, self.hitboxes))
            self.enemies.append(
                FlyingEye(x2, 55, 5, 2, -1, self.screenWidth,
                          self.surfaceLevel, self.resourceHandler,
                          self.hitboxes))
            self.view.playMusic('level2')
            self.boss_music = 'bossmusic2'
            self.boss_type = FlyingEyeBoss
            x_start_position = 300
            y_start_position = 400
            self.player = Player(x_start_position,
                                 y_start_position,
                                 self.lifes,
                                 self.screenHeight,
                                 self.screenWidth,
                                 self.resourceHandler,
                                 surfaceLevel=self.surfaceLevel,
                                 showHitboxes=self.hitboxes)

        elif level == 3:

            self.surfaceLevel = None
            self.platforms.append(Platform(60, 360, 50, 50, self.curr_level))
            self.platforms.append(Platform(100, 200, 50, 50, self.curr_level))
            self.platforms.append(Platform(40, 50, 50, 50, self.curr_level))
            self.platforms.append(Platform(155, 420, 50, 50, self.curr_level))
            self.platforms.append(Platform(165, 300, 50, 50, self.curr_level))
            self.platforms.append(Platform(245, 370, 50, 50, self.curr_level))
            self.platforms.append(Platform(270, 240, 50, 50, self.curr_level))
            self.platforms.append(Platform(375, 180, 50, 50, self.curr_level))
            self.platforms.append(Platform(480, 240, 50, 50, self.curr_level))
            self.platforms.append(Platform(585, 300, 50, 50, self.curr_level))
            self.platforms.append(Platform(690, 360, 50, 50, self.curr_level))
            self.platforms.append(Platform(650, 200, 50, 50, self.curr_level))
            self.platforms.append(Platform(600, 50, 50, 50, self.curr_level))
            self.platforms.append(Platform(480, 50, 50, 50, self.curr_level))
            self.platforms.append(Platform(500, 370, 50, 50, self.curr_level))
            x1 = random.randrange(self.screenWidth - 150)
            x2 = random.randrange(self.screenWidth - 150)
            self.enemies.append(
                FlyingEye(x1, 55, 4, 3, 1, self.screenWidth, self.surfaceLevel,
                          self.resourceHandler, self.hitboxes))
            self.enemies.append(
                FlyingEye(x2, 55, 4, 3, -1, self.screenWidth,
                          self.surfaceLevel, self.resourceHandler,
                          self.hitboxes))
            self.view.playMusic('level3')
            self.boss_music = 'bossmusic2'
            self.boss_type = FlyingEyeBoss
            x_start_position = 60
            y_start_position = 230
            self.player = Player(x_start_position,
                                 y_start_position,
                                 self.lifes,
                                 self.screenHeight,
                                 self.screenWidth,
                                 self.resourceHandler,
                                 surfaceLevel=self.surfaceLevel,
                                 showHitboxes=self.hitboxes)

        self.in_level = True
Пример #26
0
targetLabelI = Label(window, text="I")
targetLabelJ = Label(window, text="J")

targetLabel1 = Label(window, text="1")
targetLabel2 = Label(window, text="2")
targetLabel3 = Label(window, text="3")
targetLabel4 = Label(window, text="4")
targetLabel5 = Label(window, text="5")
targetLabel6 = Label(window, text="6")
targetLabel7 = Label(window, text="7")
targetLabel8 = Label(window, text="8")
targetLabel9 = Label(window, text="9")
targetLabel10 = Label(window, text="10")

# Se crean objetos de tipo Player para los jugadores de la partida
player = Player(generateGrid(), generateGrid(), generateButtonGrid(),
                generateButtonGrid(), "Jugador", False)
machine = Player(generateGrid(), generateGrid(), generateButtonGrid(),
                 generateButtonGrid(), "Maquina", True)

# Boton para cambiar la direccion en la que se ponen los barcos
changeDirButton = Button(window,
                         text="Direccion: Horizontal",
                         command=changeDir)

# Label que se usara para mostrar la informacion sobre los disparos
shotsLabel = Label(window, text="")

# Label para el titulo del juego en el menu inicial
titleLabel = Label(window, text="BATALLA NAVAL", font=("Comic Sans MS", 20))

# Componentes para el campo donde el jugador digitara su nombre
Пример #27
0
    import traceback
    traceback.print_exception(exc_type, exc_value, tb)
    input("Press key to exit.")
    sys.exit(-1)


import sys
sys.excepthook = show_exception_and_exit

from playerClass import Player
from playerClass import Alien
import random

name = input("Type in your player name: ")

player = {'a': Player(name)}
badguy = {
    'a': Alien("Sectoid"),
    'b': Alien("Sectopod"),
    'c': Alien("Mechtoid"),
    'd': Alien("Thin Man"),
    'e': Alien("Chosen"),
    'f': Alien("Muton"),
    'g': Alien("Chryssalid")
}
score = 0

print()
print('*' * 30)
print("You are %s" % name)
print(player['a'])