def __init__(self):
        Character.__init__(self)
        Keylistener.__init__(self)
        
        #TODO: These values are just for testing. 
        self.rect.x = 320
        self.rect.y = 320
        #
        
        self.walk_speed = 256;
        
        self.key_inputs = {'up': False, 
                           'right': False,
                           'down': False, 
                           'left': False,  
                           'atk': False}
        
        self.knife = weapons.Knife()
        
        self.lock_face = False
        self.swinging = False
        self.holding = False
        self.invulnerable = False
    
        self.anim_timer = 0
        self.hit_invuln_duration = 1024
        self.invuln_flash_frequency = 32

        self.take_damage_listeners = []
示例#2
0
文件: player.py 项目: derrida/shmuppy
 def __init__(self, scene):
     size = (16,16)
     color = (255,0,0)
     name = "Player 1"
     speed = 2
     hp = 20
     Character.__init__(self, scene, size, color, name, speed, hp)
示例#3
0
    def update(self, dt):
        Character.update(self, dt)
        self.midair = abs(self.body.linearVelocity[1]) > 0.01
        self.time_since_jump += dt
        if self.keys[2]:
            self.body.linearVelocity = (-self.xspeed * Settings.B2SCALE, self.body.linearVelocity[1] )
        if self.keys[3]:
            self.body.linearVelocity = (self.xspeed * Settings.B2SCALE, self.body.linearVelocity[1] )
        if self.keys[1]:
            if not self.midair:
                self.jump()
                self.can_double_jump = True
                self.time_since_jump = 0
            elif self.can_double_jump and self.has_pickup("double_jump") and self.time_since_jump > 10:
                self.jump()
                self.can_double_jump = False

        self.upsidedown = False        
        for contact_edge in self.body.contacts:
            if contact_edge.contact.touching:
                if contact_edge.other.position[1] - self.body.position[1] < 0:
                    self.upsidedown = True
            
        self.going_left = self.body.linearVelocity[0] < -0.1
        self.going_right = self.body.linearVelocity[0] > 0.1

        self.update_animation(dt)
        self.update_pickups(dt)

        self.score += 0.01*(2**self.pickup_count("double_points"))
        if self.rect.top < self.max_height:
            self.max_height = self.rect.top
示例#4
0
 def key_control(self, key, event):
     Character.key_control(self, key, event)
     # Custom hero control
     if (key == pygame.K_w):
         if event == pygame.KEYDOWN:
             self.vel = (self.vel[0], self.vel[1]-1)
         elif event == pygame.KEYUP:
             self.vel = (self.vel[0], self.vel[1]+1)
     elif (key == pygame.K_s):
         if event == pygame.KEYDOWN:
             self.vel = (self.vel[0], self.vel[1]+1)
         elif event == pygame.KEYUP:
             self.vel = (self.vel[0], self.vel[1]-1)
     elif (key == pygame.K_a):
         if event == pygame.KEYDOWN:
             self.vel = (self.vel[0]-1, self.vel[1])
         elif event == pygame.KEYUP:
             self.vel = (self.vel[0]+1, self.vel[1])
     elif (key == pygame.K_d):
         if event == pygame.KEYDOWN:
             self.vel = (self.vel[0]+1, self.vel[1])
         elif event == pygame.KEYUP:
             self.vel = (self.vel[0]-1, self.vel[1])
     elif (key == pygame.K_SPACE):
         if event == pygame.KEYDOWN:
             self.firing = True
         elif event == pygame.KEYUP:
             self.firing = False
示例#5
0
    def __init__(self, g, player_new, dimentions, p=0):
        LevelBase.__init__(self, g, player_new, dimentions)
        self.prevlevel = p
        self.title = "Airport"
        # current level
        TW, TH = 32, 32

        # load tile set
        g.tga_load_tiles(os.path.join("textures", "tiles5.png"), (TW, TH), self.tdata)
        g.tga_load_level(os.path.join("levels", "level29.tga"), 1)
        g.bounds = pygame.Rect(TW, TH, (len(g.tlayer[0]) - 2) * TW, (len(g.tlayer) - 2) * TH)
        g.code_events(self.edata)

        self.g.player.hidden = 0
        self.pan_camera(None)

        self.doctor = Character("monster3a.png", "monster3a.png", self.g, "doctor")
        self.doctor.pos((25, 20))  # 25, 20
        self.doctor.health = 0
        self.doctor.dead = 1

        self.movie = 0
        self.assistant = Character("assistant.png", "faceassistant.png", g)
        self.assistant.pos((33, 27))
        self.assistant.feeling = "coma"
        self.nurse = Character("monster4.png", "facenurse.png", self.g, "nurse")
        self.nurse.pos((29, 27))
        self.nurse.direction = 0
        if not "scene14" in g.saveData:
            self.nurse.feeling = "dead"
        g.run_codes(self.cdata, (0, 0, g.dimentions[0], g.dimentions[1]))
示例#6
0
    def __init__(self, g, player_new, dimentions, p = 0):
        LevelBase.__init__(self, g, player_new, dimentions)
        self.prevlevel = p
        self.title = "Tree House"

        # current level
        currentLevel = os.path.join("levels",  "level7.tga")

        TW,TH = 32,32

        # load tile set
        tileTexture = os.path.join("textures",  "tiles2.png")
        g.tga_load_tiles(tileTexture, (TW,TH), self.tdata)
        g.tga_load_level(currentLevel, 1)
        g.bounds = pygame.Rect(TW,TH,(len(g.tlayer[0])-2)*TW,(len(g.tlayer)-2)*TH)
        g.code_events(self.edata)

        self.fox = Character("fox.png","facefox.tga", g, 'fox')
        self.fox.pos((3, 9))
        self.fox.direction = 0
        self.fox.hidden = 1

        self.assistant = Character("assistant.png","faceassistant.png", g)
        self.assistant.pos((9, 10))
        self.assistant.direction = 0
        
        g.run_codes(self.cdata,(0,0,g.dimentions[0],g.dimentions[1]))
        self.g.player.direction = 1
        g.intermission = 1
        if 'scene5' in g.saveData:
            self.assistant.hidden = 1
            self.fox.hidden = 1
            self.dialog = 10
示例#7
0
	def __init__(self, world_map, path, shoottime):
		Character.__init__(self, world_map, world_map.group, world_map.enemies_group)
		self.path = path
		self.x = 0
		self.y = 0
		self.shoottime = shoottime
		self.frame_counter = 0
示例#8
0
    def __init__(self, g, player_new, dimentions, p = 0):
        LevelBase.__init__(self, g, player_new, dimentions)
        self.prevlevel = p
        self.title = 'Underground'
        # current level
        TW,TH = 32,32

        # load tile set
        g.tga_load_tiles(os.path.join("textures",  "tiles5.png"), (TW,TH), self.tdata)
        g.tga_load_level(os.path.join("levels",  "level24.tga"), 1)
        g.bounds = pygame.Rect(TW,TH,(len(g.tlayer[0])-2)*TW,(len(g.tlayer)-2)*TH)
        g.code_events(self.edata)

        self.doctor = Character("monster3a.png", "monster3a.png", self.g, 'doctor')
        self.doctor.pos((25, 20)) # 25, 20

        self.assistant = Character("assistant.png","faceassistant.png", g)
        self.assistant.pos((33, 27))
        self.assistant.direction = 1
        self.assistant.feeling  = 'coma'

        self.nurse = None # will get set by character.py later on

        g.run_codes(self.cdata,(0,0,g.dimentions[0],g.dimentions[1]))
        self.g.player.hidden = 0
        self.movie = 0
        
        # battled and destoryed the doctor
        if  'scene13' in g.saveData:
            self.doctor.health = 0
            self.nurse = Character("monster4.png", "facenurse.png", self.g, 'nurse')
            self.nurse.pos((29, 27))
            if not 'scene14' in g.saveData:
                self.nurse.feeling = 'dead'
示例#9
0
    def __init__(self, g, player_new, dimentions, p = 0):
        LevelBase.__init__(self, g, player_new, dimentions)
        self.prevlevel = p
        self.title = 'Flooded Lab'
        # current level
        TW,TH = 32,32

        # load tile set
        g.tga_load_tiles(os.path.join("textures",  "tiles6.png"), (TW,TH), self.tdata)
        g.tga_load_level(os.path.join("levels",  "level33.tga"), 1)
        g.bounds = pygame.Rect(TW,TH,(len(g.tlayer[0])-2)*TW,(len(g.tlayer)-2)*TH)
        g.code_events(self.edata)

        self.stygian = Character('stygian.png', 'facestygian.png', g)
        self.stygian.pos((8, 9))
        self.stygian.direction = 1
        self.boat = Character('boat.png', 'facestygian.png', g, 'boat')
        self.boat.pos((9, 11))
        
        self.professor = Character("professor.png","faceprofessor.tga", g)
        self.professor.pos((5, 9))
        self.professor.direction = 0
        
        g.run_codes(self.cdata,(0,0,g.dimentions[0],g.dimentions[1]))
        self.initBack('bg0.png', 140)
示例#10
0
    def __init__(self, characters):
        """Initialize all attributes and music.

        utils -- SpriteGroup, contains background and timer
        players -- SpriteGroup, contains two characters
        skills -- SkillManager, contains the skills of both characters

        """
        SpriteGroup.__init__(self)

        self.background = Background(random.choice(glob.
                                                   glob("assets/fields/*")))
        self.mana_time = 0
        self.timer = Timer()
        self.timer.position = Vec2D(DEFAULT_SCREEN_SIZE[0] / 2, 30)

        self.mixer = Mixer(glob.glob("assets/sound/play_menu/*"))
        self.mixer.play_random()

        self.player1 = Character(1, characters[0], (0, 0))
        self.player2 = Character(2, characters[1], DEFAULT_SCREEN_SIZE)

        self.skills = SkillManager(self.player1.skills, self.player2.skills)

        self.players = SpriteGroup(self.player1, self.player2)
        self.utils = SpriteGroup(self.background, self.timer)
        self.add(self.utils, self.players, self.skills)
示例#11
0
文件: enemy.py 项目: j-a-c/avengers
    def __init__(self, x, y, ai, level=None):
        #general stuff
        self.isFlying = False   #is the player flying?
        self.facingRight = False #player facing right?
        self.peaking = False     #is player at the peak of its jump?
        self.canMove = False
        self.canJump = False
        self.player = None
        self.ai = ai
        #shooting timer
        self.sattack_timer = 0
        #level instance - pass if enemy interacts with level
        self.level = level

        #choose AI to implement
        self.AI_implementations = { NONE:       self.AI_nothing,
                                    FLOOR:      self.AI_floor,
                                    PLATFORM:   self.AI_platform,
                                    JUMP:       self.AI_jump,
                                    HOP:        self.AI_hop,
                                    FLYVERT:    self.AI_flyvert,
                                    FLYHORIZ:   self.AI_flyhoriz,
                                    FLYSWOOP:   self.AI_flyswoop,
                                    FLYATTACK:  self.AI_flyattack,
                                    RPROJ:      self.AI_rproj,
                                    RPROJSTAND: self.AI_rprojstand,
                                    SHY:        self.AI_shy,
                                    CUSTOM:     None}

        Character.__init__(self,x,y)
    def update(self, dt):
        if dt == 0:
            return      
            
        #Set the walking state
        self.setWalking(Character.Direction.UP, self.key_inputs['up'])
        self.setWalking(Character.Direction.RIGHT, self.key_inputs['right'])
        self.setWalking(Character.Direction.DOWN, self.key_inputs['down'])
        self.setWalking(Character.Direction.LEFT, self.key_inputs['left'])
        
        #Set the facing direction
        if not self.lock_face:
            if (not self.key_inputs['down']) and self.key_inputs['up']:
                self.facing = Character.Direction.UP
            if (not self.key_inputs['up']) and self.key_inputs['down']:
                self.facing = Character.Direction.DOWN
            if (not self.key_inputs['left']) and self.key_inputs['right']:
                self.facing = Character.Direction.RIGHT
            if (not self.key_inputs['right']) and self.key_inputs['left']:
                self.facing = Character.Direction.LEFT

        if self.key_inputs['atk']:
            self.knife.attack(self, self.facing)
            self.lock_face = True
        else:
            if self.knife.attacking:
                self.knife.endAttack()
            self.lock_face = False
            
        #TODO: "holding" state determination code needs to be made better.
        self.holding = self.key_inputs['atk']
        
        self.swinging = self.knife.isSlashing() 
        
        Character.makeMove(self, dt)
示例#13
0
    def __init__(self, x, imgFile="npc_sprite.png"):
        Character.__init__(self, imgFile)

        self.images = []  # 0=idle, 1=running#1 , 2=running#2

        for i in range(3):
            image = pygame.Surface([100, 200], pygame.SRCALPHA, 32).convert_alpha()
            image.blit(self.image, (0, 0), (i*100, 0, 100, 200))
            self.images.append(image)

        self.images.append(pygame.transform.flip(self.images[0], True, False))
        self.images.append(pygame.transform.flip(self.images[1], True, False))
        self.images.append(pygame.transform.flip(self.images[2], True, False))

        self.rect = self.images[0].get_rect()
        
        self.rect.x = x
        self.home = x
        self.rect.y = screen_h - 150
        self.time = pygame.time.get_ticks()
        self.state = "idle"  # idle/moving   idle == maksmata
        self.idle_job = [0, 0]  # [job, time when to stop] jobs: 0=right, 1=left, 2=wait
        self.x_speed = 0
        self.move_to = self.home


        self.frame_counter = 0
示例#14
0
    def create_animated_sprite():
        """Create animation"""
        char = Character()
        sprites = char.create_sprites("Images/player.png", "Images/player2.png")

        source = pyglet.image.Animation.from_image_sequence(sprites, 0.5, True)
        sprite = pyglet.sprite.Sprite(source)
        return sprite
示例#15
0
    def __init__(self, x, y):

        self.direction = Direction.WEST
        self.health = Zombie.START_HEALTH
        self.img = Zombie.ORIGINAL_ZOMBIE_IMAGE

        Character.__init__(self, x, y)
        Zombie.list_.append(self)
示例#16
0
	def __init__(self, x, y):

		self.health = Survivor.START_HEALTH
		self.current = 0 # 0 -> pistol, 1 -> shotgun, 2 -> automatic
		self.direction = Direction.WEST
		self.img = pygame.image.load('images/survivor/survivor_w.png')

		Character.__init__(self, x, y)
示例#17
0
 def attack(self, enemy):
     """
     attack method that uses the method of the father class and makes a print
     :param enemy: Character your going to attack
     :return:
     """
     Character.attack(self, enemy)
     print "You attacked a " + enemy.character_type
示例#18
0
    def __init__(self, g, player_new, dimentions, p = 0):
        LevelBase.__init__(self, g, player_new,dimentions)
        self.prevlevel = p
        self.title = 'Engineers Lab'

        # current level
        currentLevel = os.path.join("levels",  "level2.tga")

        TW,TH = 32,32

        # load tile set
        tileTexture = os.path.join("textures",  "tiles0.png")
        g.tga_load_tiles(tileTexture, (TW,TH), self.tdata)
        g.tga_load_level(currentLevel, 1)
        g.bounds = pygame.Rect(TW,TH,(len(g.tlayer[0])-2)*TW,(len(g.tlayer)-2)*TH)
        g.code_events(self.edata)

        self.microwave = Inventory(g, 'microwave')
        self.microwave.pos((6, 9))

        self.professor = Character("professor.png","faceprofessor.tga", g)
        self.professor.pos((6, 9))
        self.professor.direction = 0

        self.assistant = Character("assistant.png","faceassistant.png", g)
        self.assistant.pos((12, 9))
        self.assistant.direction = 1
        
        g.intermission = 1

        # already done the cut scene
        if 'scene1' in g.saveData:
            g.intermission = 0
            self.professor.pos((11, 9))
            self.dialog = 9
            self.g.sprites.remove(self.assistant)

        # if you've put the transmitter in
        if 'scene3' in g.saveData:
            self.assistant = Character("assistant.png","faceassistant.png", g)
            self.assistant.pos((13, 9))
            self.professor.pos((8, 9))
            self.assistant.direction = 1
            self.dialog = 10
            g.intermission = 1
        
        # already had the talk after putting in the transmitter
        if 'scene4' in g.saveData:
            self.dialog = 19
            g.intermission = 0
            self.g.sprites.remove(self.assistant)

        if 'scene5' in g.saveData:
            self.dialog = 20
            self.professor.pos((11,9))
            self.professor.faceup = 1

        g.run_codes(self.cdata,(0,0,g.dimentions[0],g.dimentions[1]))
示例#19
0
文件: linder.py 项目: bpittman/pydnd
    def __init__(self):
        Character.__init__(self)
        self.setAbilities(str=13, con=12, dex=24, int=11, wis=15, cha=22)

        self.setSkills(
            acrobatics=True, athletics=True, bluff=True, perception=True, stealth=True, streetwise=True, thievery=True
        )

        # racial bonuses
        self.skill["diplomacy"].miscBonus = 2
        self.skill["insight"].miscBonus = 2

        # Devastating Critical feat
        self.extraCrit = "1d10"

        # jet black stone bonus
        self.skill["stealth"].miscBonus = 4

        self.proficiency["dagger"] = 3 + 1  # proficient + rogue class bonus
        self.proficiency["handCrossbow"] = 2
        self.setLvl(17)

        # at-wills
        self.setPower(slyFlourish=SlyFlourish(), acrobaticStrike=AcrobaticStrike())

        # encounters
        self.setPower(
            shadowJaunt=ShadowJaunt(),
            fadingStrike=FadingStrike(),
            jumpingBladeAssault=JumpingBladeAssault(),
            escapeArtistsGambit=EscapeArtistsGambit(),
            cleverMove=CleverMove(),
            sneakInTheAttack=SneakInTheAttack(),
            rockyIVPunch=RockyIVPunch(),
            criticalOpportunity=CriticalOpportunity(),
            tumblingDodge=TumblingDodge(),
            combatTumbleset=CombatTumbleset(),
            tornadoStrike=TornadoStrike(),
            oathOfEnmity=OathOfEnmity(),
        )

        # dailies
        self.setPower(
            slayingStrike=SlayingStrike(),
            aerialAssault=AerialAssault(),
            trickStrike=TrickStrike(),
            badIdeaFriend=BadIdeaFriend(),
        )

        self.setWeapon(
            misericorde=Misericorde(),
            poisonedCrossbow=PoisonedCrossbow(),
            cloakedDagger=CloakedDagger(),
            unarmed=Unarmed(),
        )

        self.setEquip(main="misericorde")
示例#20
0
 def draw(self,screen,viewport):
     if self.has_pickup("trampoline"):
         pygame.draw.line(screen, (0,255,255), (0, HEIGHT/2 + self.trampoline_height),(WIDTH, HEIGHT/2 + self.trampoline_height))
     Character.draw(self, screen, viewport)
     h = 0
     for pickup in self.pickups:
         text = PICKUP_NAMES[pickup.pickup_type] + " " + str(pickup.duration)
         text_render = self.font.render(text, True, (255, 255, 255))
         screen.blit(text_render, (600, h))
         h += 20
示例#21
0
文件: mage.py 项目: Jamakazie/dnd
	def __init__(self, level, race, name='no name'):
		Character.__init__(self,level, race, name)
		self.cclass = "Mage"
		self.stats()
		self.hp(4)
		self.base_attack_bonus(.5)
		self.base_saves()
		self.equipment()
		self.skills()
		self.totaltohit = self.base_attack_bonus
示例#22
0
   def load(name, center=None, walkDelay=settings.fps):
      jsonData = load_character_data(name)

      self = DumbBattleNPC()

      Character.__init__(self, center, jsonData['spritename'])
      DumbNPC.__init__(self, walkDelay)
      BattleCharacter.__init__(self, jsonData)

      return self
示例#23
0
文件: rogue.py 项目: Jamakazie/dnd
	def __init__(self, level, race, name='no name'):
		Character.__init__(self,level, race, name)
		self.cclass = "Rogue"
		self.stats()
		self.base_attack_bonus(.75)
		self.hp(6)
		self.base_saves()
		self.equipment()
		self.skills()
		self.totaltohit = int(self.stats.dexterity) + int(.75 * self.level)
示例#24
0
文件: priest.py 项目: Jamakazie/dnd
	def __init__(self, level, race, name='no name'):
		Character.__init__(self,level, race, name)
		self.cclass = "Priest"
		self.stats()
		self.hp(8)
		self.base_attack_bonus(.75)
		self.base_saves()
		self.equipment()
		self.skills()
		self.totaltohit = int((max(self.stats.strength, self.stats.dexterity) - 10 ) / 2) + int(self.level * .75)
示例#25
0
文件: mobfactory.py 项目: dahui58/rpg
	def populateSynthMob(stage):
		stageCounts = {0:1,1:2,2:2,3:3,4:3,5:4}
		mob = []
		for i in range (1,stageCounts[stage]+1):
			nameString = "synth" + str(i)
			synth = Character(nameString, endurance=19, agility=20, strength=22, dexterity=25, isPlayable=False, humanity=0.0)
			possibleWeapons = [0,1,7]
			selectedWeapon = RandUtils.pickRandomFromList(possibleWeapons)
			synth.weapon = State.weapons[selectedWeapon]
			mob.append(synth)
		return mob
示例#26
0
文件: fighter.py 项目: Jamakazie/dnd
	def __init__(self, level, race, name='no name'):
		Character.__init__(self,level, race, name)
		self.cclass = "Fighter"
		self.stats()
		self.hp(10)
		self.base_attack_bonus(1.0)
		self.base_saves()
		self.skills()
		self.ac = 10 + int((self.stats.dexterity - 10) / 2 )
		self.equipment()
		self.totaltohit += int(1.0 * self.level) + int((self.stats.strength - 10) / 2)
示例#27
0
文件: gravis.py 项目: bpittman/pydnd
   def __init__(self):
      Character.__init__(self)
      self.setAbilities(str=12, con=10, dex=10, int=12, wis=18, cha=17)

      self.setSkills(heal=True, insight=True, arcana=True, history=True,
                     religion=True)

      #background trait
      self.skill['insight'].miscBonus = 2

      #combat medic feat bonus
      self.skill['heal'].miscBonus = 2

      #armor penalties
      self.skill['acrobatics'].miscBonus = -1
      self.skill['athletics'].miscBonus = -1
      self.skill['endurance'].miscBonus = -1
      self.skill['stealth'].miscBonus = -1
      self.skill['thievery'].miscBonus = -1

      #proficiencies (only bothering with relevant ones)
      self.proficiency['staff'] = 2
      self.proficiency['mace'] = 2
      self.proficiency['implement'] = 1 #implement expertise feat
      self.setLvl(5)

      #at-wills
      self.setPower(lanceOfFaith=LanceOfFaith(),
                    sacredFlame=SacredFlame(),
                    astralSeal=AstralSeal())

      #encounters
      self.setPower(shieldBearer=ShieldBearer(),
                    channelDivinityTurnUndead=ChannelDivinityTurnUndead(),
                    channelDivinityDivineFortune=ChannelDivinityDivineFortune(),
                    healingWord=HealingWord(),
                    hymnOfResurgence=HymnOfResurgence(),
                    radiantSmite=RadiantSmite())

      #dailies
      self.setPower(astralCondemnation=AstralCondemnation(),
                    shieldOfFaith=ShieldOfFaith(),
                    spiritualWeapon=SpiritualWeapon())

      self.setWeapon(mace=Mace(),
                     orbOfLight=OrbOfLight())

      self.setEquip(main='mace',
                    implement='orbOfLight')
示例#28
0
    def __init__(self, g, player_new, dimentions, p = 0):
        LevelBase.__init__(self, g, player_new, dimentions)
        self.prevlevel = p
        self.title = 'Water of Leith'

        # current level
        currentLevel = os.path.join("levels",  "level3.tga")

        TW,TH = 32,32

        # load tile set
        tileTexture = os.path.join("textures",  "tiles0.png")
        g.tga_load_tiles(tileTexture, (TW,TH), self.tdata)
        g.tga_load_level(currentLevel, 1)
        g.bounds = pygame.Rect(TW,TH,(len(g.tlayer[0])-2)*TW,(len(g.tlayer)-2)*TH)
        g.code_events(self.edata)

        self.assistant = Character("assistant.png","faceassistant.png", g)
        self.assistant.pos((3, 10))
        self.assistant.direction = 0
        g.intermission = 1
        
        g.run_codes(self.cdata,(0,0,g.dimentions[0],g.dimentions[1]))

        # already done the cut scene
        if 'scene2' in g.saveData:
            self.dialog = 5
        if 'scene4' in g.saveData:
            self.g.sprites.remove(self.assistant)
        self.initBack('bg0.png', 180)
示例#29
0
	def configure(self):
		Character.configure(self)
		self.rect.x, self.rect.y = 10, 1000
		self.gravity = 1
		self.acceleration_x = 0
		self.jumping = False
		self.blinking = False
		
		self.jump_energy_max = 3
		self.jump_energy = self.jump_energy_max
		self.life_max = 5
		self.life = self.life_max
		
		self.weapon = Weapon(self)
		
		self.JUMP_SPEED = 10
示例#30
0
	def setup(self):
		self.player = Character()
		self.monsters = [
		Goblin(),
		Troll(),
		Dragon()]
		self.monster = self.get_next_monster()
    def test_player_set_location(self):
        f = open(os.path.join(parentdir, "data/character_data.json"), "r")
        data = json.load(f)
        f.close()
        characters = data.keys()
        for character in characters:
            char = Character(type_=character)
            player = Player(char)
            prev_pos = player.pos

            # invalid moves #
            self.assertEqual(player.set_location(-1, 0), prev_pos)
            self.assertEqual(player.set_location(0, -1), prev_pos)
            self.assertEqual(player.set_location(config.display_width + 1, 0),
                             prev_pos)
            self.assertEqual(player.set_location(0, config.display_height + 1),
                             prev_pos)
            # valid moves #
            self.assertEqual(player.set_location(100, 100), player.pos)
            self.assertEqual(player.set_location(0, config.display_height),
                             player.pos)
            self.assertEqual(player.set_location(config.display_width, 0),
                             player.pos)
示例#32
0
    def start_game(self):
        """Starts Game"""
        """Sets the number of guesses"""
        used_lives = self.total_lives
        """Game loop"""
        while True:

            self.phrase_output(self.selected_phrase)
            """If no "_" in output then game is won"""
            if "_" not in self.consol_output:
                self.you_won()
            self.guess_input()
            """Checks if guess input matches phrase in Character file and then counts down if not correct
"""
            true_guess = Character(self.player_guess, self.selected_phrase)
            if true_guess.was_guessed is False:
                used_lives -= 1
                """If all 5 lives are used then end game"""
            if used_lives <= 0:
                self.better_luck()
                """Output how many lives are left"""
            print('You have {} out of {} lives remaining!'.format(
                used_lives, self.total_lives))
示例#33
0
    def update(self, frame_time):
        global e_bullet, character
        character = Character()
        distance = Enemy.RUN_SPEED_PPS * frame_time
        self.total_frames += Enemy.FRAMES_PER_ACTION * Enemy.ACTION_PER_TIME * frame_time
        self.frame = int(self.total_frames) % 1
        self.f_time += frame_time
        self.x += (self.xdir * distance)
        self.y += (self.ydir * distance)

        if self.f_time >= 0.5:
            e_bullet += [Enemy_Bullet(self.x, self.y - 70)]
            self.f_time = 0

        if self.stage2 == 1:
            if self.f_time >= 0.5:
                e_bullet += [Enemy_Bullet(self.x, self.y - 70)]
                self.f_time = 0

        if self.HP <= 0:
            self.death = True

        if self.x > 750:
            self.xdir = -1
            self.x = 750
            self.state = self.LEFT_RUN
        elif self.x < 50:
            self.xdir = 1
            self.x = 50
            self.state = self.RIGHT_RUN
        for i in e_bullet:
            i.update(frame_time)
            if collide(character, i):
                print("character collision")

        if character.C_HP <= 80:
            print("gameover")
示例#34
0
    def __init__(self, ipAddr, portNum, parent=None):
        QObject.__init__(self, parent)

        self.ipAddr = ipAddr
        self.portNum = portNum

        controller = RobotController()
        controller.reset_pos()
        self.b = board.Board()
        self.bot = Character(ipAddr, portNum, self.b, controller, self)
        self.bot.changed_location.connect(self.change_picture)

        self.startButton = QPushButton("Start the game!")
        self.startButton.clicked.connect(self.start_playing)

        self.endButton = QPushButton("End the game!")
        self.endButton.clicked.connect(self.end_game)

        self.image_label = QLabel(self)
        pixmap = QtGui.QPixmap("gui_images/entrance.jpg")
        pixmap = pixmap.scaled(self.image_size,self.image_size, PyQt5.QtCore.Qt.KeepAspectRatio)
        self.image_label.setPixmap(pixmap)
        self.image_label.setAlignment(PyQt5.QtCore.Qt.AlignCenter)

        # main layout
        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.image_label)
        self.mainLayout.addWidget(self.startButton)
        self.mainLayout.addWidget(self.endButton)

        # central widget
        self.centralWidget = QWidget()
        self.centralWidget.setLayout(self.mainLayout)

        # set central widget
        self.setCentralWidget(self.centralWidget)
示例#35
0
 def __init__(self, id_: int, total: int):
     _wave = uData.setting['wave']
     self.id = id_
     self.ch_id = 'right'
     self.__chara_list = ['left', 'middle', 'right']
     self.total = total
     self.__myTurn_count = 0
     self.auto = _wave[str(self.id)]['auto']
     self.name = f'wave_{self.id}-{self.total}'
     self.objects = Load_Objects("wave")
     self.icon = Icon(f'{self.name}.png', uData.setting['confidence'])
     if not self.auto:
         self.characters = {
             c: Character(c, self.id)
             for c in self.__chara_list
         }
         self.chars_sp_order = self.__sp_order_init(
         ) if 'sp_weight_enable' in _wave[str(self.id)] and _wave[str(
             self.id)]['sp_weight_enable'] else []  # noqa: E501
         self.orbs = self.__orb_init()
         self.__friend = uData.setting['friend_support'] if uData.setting[
             'friend_support'] and uData.setting['friend_support'][
                 'wave_N'] == self.id else None  # noqa: E501
     self.__auto_button_multi_check = 0
示例#36
0
def init_character_map():
    char_map = {}

    # add characters
    char_map[clue.CHARACTER_NAME_MRS_WHITE] = Character(
        clue.CHARACTER_NAME_MRS_WHITE,
        clue.LOCATION_NAME_MRS_WHITE_HOME).__dict__
    char_map[clue.CHARACTER_NAME_MR_GREEN] = Character(
        clue.CHARACTER_NAME_MR_GREEN,
        clue.LOCATION_NAME_MR_GREEN_HOME).__dict__
    char_map[clue.CHARACTER_NAME_MRS_PEACOCK] = Character(
        clue.CHARACTER_NAME_MRS_PEACOCK,
        clue.LOCATION_NAME_MRS_PEACOCK_HOME).__dict__
    char_map[clue.CHARACTER_NAME_PROF_PLUM] = Character(
        clue.CHARACTER_NAME_PROF_PLUM,
        clue.LOCATION_NAME_PROF_PLUM_HOME).__dict__
    char_map[clue.CHARACTER_NAME_MISS_SCARLET] = Character(
        clue.CHARACTER_NAME_MISS_SCARLET,
        clue.LOCATION_NAME_MISS_SCARLET_HOME).__dict__
    char_map[clue.CHARACTER_NAME_COLONEL_MUSTARD] = Character(
        clue.CHARACTER_NAME_COLONEL_MUSTARD,
        clue.LOCATION_NAME_COLONEL_MUSTARD_HOME).__dict__

    return char_map
示例#37
0
import pyglet
from pyglet.gl import *
from worldview import WorldView
from input import Input
from character import Character

window = pyglet.window.Window(600, 300)
input = Input(window)
char = Character(input)
wView = WorldView()


def init():
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glClearColor(1.0, 1.0, 1.0, 1.0)
    char.init()
    wView.init()


@window.event
def on_draw():
    window.clear()
    wView.draw()
    char.draw()


def update(dt):
    char.update(dt)

示例#38
0
                    break
            else:
                process_player_autoturn(board, key, players)
                if not game_continues(players):
                    break
        else:
            players.get(key).token = 0

        for p in players.values():
            p.endurance = p.max_endurance


if __name__ == '__main__':
    dim = 8
    board = Board(dim, dim)
    player1 = Character(name="p1", pos=57, token='<', attack=1,
                        defense=1, speed=3, endurance=2, health=2, strategy='')
    player2 = Character("p2", 63, 'V', 1, 1, 1, 1, 2, 'aggressive')
    player3 = Character("p3", 49, '^', 1, 1, 1, 1, 2, 'defensive')
    player4 = Character("p4", 4, '>', 1, 1, 1, 1, 2, 'aggressive')
    player5 = Character("p5", 16, '<', 1, 1, 1, 1, 2, 'aggressive')
    players = {'player1': player1, 'player2': player2, 'player3': player3, 'player4': player4, 'player5': player5}
    board.update(players)

    board.print_board()

    while game_continues(players):

        process_turns(players)
        board.update(players)

        print("player1 health " + str(player1.health))
示例#39
0
 def test_map_description_position_3_4(self, mock_stdout):
     test_character = Character('Jihyo', 10, [3, 4], 0)
     dialogue_and_scripts.map_description(test_character)
     expected_stdout = "You look outside the window, there is a full moon tonight."
     self.assertIn(expected_stdout, mock_stdout.getvalue())
示例#40
0
class Game:
	def steup(self):
		self.player = Character()
		self.monsters = [
			Goblin(),
			Troll(),
			Dragon()
		]
		self.monster = self.get_next_monster()

	def get_next_monster(self):
		try:
			return self.monsters.pop(0)
		except IndexError:
			return None

	def monster_turn(self):
		if self.monster.attack():
			print("{} is attacking!".format(self.monster))

			if input("Dodge? Y/N ").lower() == "y":
				if self.player.dodge():
					print("You dodged the attack!")
				else:
					print("You got hit anyway!")
					self.player.hit_points -= 1
			else:
				print("{} hit you for 1 point!".format(self.monster))
				self.player.hit_points -= 1
		else:
			print("{} isn't attacking this turn.".format(self.monster))

	def player_turn(self):
		player_choice = input("[A]ttack, [R]est, [Q]uit? ").lower()
		if player_choice == 'a':
			print("You're attacking {}!".format(self.monster))

			if self.player.attack():
				if self.monster.dodge():
					print("{} dodged your attack!".format(self.monster))
				else:
					if self.player.leveled_up():
						self.monster.hit_points -= 2
					else:
						self.monster.hit_points -= 1

						print("You hit {} with your {}!".format(self.monster, self.player.weapon))
			else:
				print("You missed!")
		elif player_choice == 'r':
			self.player.rest()
		elif player_choice == 'q':
			sys.exit()
		else:
			self.player_turn()

	def cleanup(self):
		if self.monster.hit_points <= 0:
			self.player.experience += self.monster.experience
			print("You killed {}!".format(self.monster))
			self.monster = self.get_next_monster()

	def __init__(self):
		self.steup()

		while self.player.hit_points and (self.monster or self.monsters):
			print('\n'+'='*20)
			print(self.player)
			self.monster_turn()
			print('-'*20)
			self.player_turn()
			self.cleanup()
			print('\n'+'='*20)

		if self.player.hit_points:
			print("You win!")
		elif self.monsters or self.monster:
			print("You lose!")
		sys.exit()
示例#41
0
class Game:
    """ This class manages the game """
    def __init__(self, level):
        self.window = self.__define_window()
        self.level = level
        self.screen_interaction = pygame.Surface(
            (X_SCREEN_INTERACTION, Y_SCREEN_INTERACTION))

        self.labyrinth = Level(self.level)
        self.hero = Character("hero")
        self.bad_guy = Character("bad_guy")

        self.needle = Item(NEEDLE_STRIPE)
        self.tube = Item(TUBE_STRIPE)
        self.ether = Item(ETHER_STRIPE)

        self.selected_button = "play_game"
        self.play_button_color = WHITE
        self.quit_button_color = BLACK
        self.menu_message = "READY TO PLAY?"

        self.start_program = True
        self.menu = True
        self.play_game = False

    def __define_window(self):
        """ This method defines the window of the game """

        window = pygame.display.set_mode((X_WINDOW_GAME, Y_WINDOW_GAME))
        background = pygame.image.load(
            "sources/background-jail-800x800.jpg").convert()
        window.blit(background, (0, 0))

        return window

    def __prepare(self):
        """ This method positions the characters and objects in the labyrinth structure """

        # Be sure to initialize all the characteristic of the game_over
        self.labyrinth = Level(self.level)
        self.hero = Character("hero")
        self.bad_guy = Character("bad_guy")

        self.needle = Item(NEEDLE_STRIPE)
        self.tube = Item(TUBE_STRIPE)
        self.ether = Item(ETHER_STRIPE)

        # Define Characters' position
        for index_line, line in enumerate(self.labyrinth.structure):
            for index_stripe, stripe in enumerate(line):
                if stripe == HERO_STRIPE:
                    self.hero.x_index = index_stripe
                    self.hero.y_index = index_line
                elif stripe == BAD_GUY_STRIPE:
                    self.bad_guy.x_index = index_stripe
                    self.bad_guy.y_index = index_line

        # Define Objects' position
        random_positions = self.__get_item_positions(3)
        self.needle.x_index = random_positions[0][0]
        self.needle.y_index = random_positions[0][1]
        self.tube.x_index = random_positions[1][0]
        self.tube.y_index = random_positions[1][1]
        self.ether.x_index = random_positions[2][0]
        self.ether.y_index = random_positions[2][1]

        self.labyrinth.set_stripe(self.needle.x_index, self.needle.y_index,
                                  NEEDLE_STRIPE)
        self.labyrinth.set_stripe(self.tube.x_index, self.tube.y_index,
                                  TUBE_STRIPE)
        self.labyrinth.set_stripe(self.ether.x_index, self.ether.y_index,
                                  ETHER_STRIPE)

    def __get_item_positions(self, numb_position):
        valid_location = []
        for index_line, line in enumerate(self.labyrinth.structure):
            for index_stripe, stripe in enumerate(line):
                if stripe == self.labyrinth.floor_stripe_face:
                    valid_location.append((index_stripe, index_line))

        winner_locations = random.sample(valid_location, numb_position)
        return winner_locations

    def __update_level_design(self, screen):
        """ This method updates the image of labyrinth labyrinth_case according
        the labyrinth structure """

        labyrinth_case = pygame.Surface((X_LEVEL_DIM_CASE, Y_LEVEL_DIM_CASE))

        num_line = 0
        for line in self.labyrinth.structure:
            num_stripe = 0
            for stripe in line:
                x_corner_top_left = num_stripe * X_LEVEL_DIM_CASE
                y_corner_top_left = num_line * Y_LEVEL_DIM_CASE
                if stripe == WALL_STRIPE:
                    labyrinth_case.blit(self.labyrinth.wall_image, (0, 0))
                    screen.blit(labyrinth_case,
                                (x_corner_top_left, y_corner_top_left))
                elif stripe == FLOOR_STRIPE:
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 0))
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 20))
                    screen.blit(labyrinth_case,
                                (x_corner_top_left, y_corner_top_left))
                elif stripe == HERO_STRIPE:
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 0))
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 20))
                    labyrinth_case.blit(
                        self.hero.image, (4, 0),
                        (0, 0, X_LEVEL_DIM_CASE, Y_LEVEL_DIM_CASE))
                    screen.blit(labyrinth_case,
                                (x_corner_top_left, y_corner_top_left))
                elif stripe == BAD_GUY_STRIPE:
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 0))
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 20))
                    labyrinth_case.blit(
                        self.bad_guy.image, (4, 4),
                        (0, 0, X_LEVEL_DIM_CASE, Y_LEVEL_DIM_CASE))
                    screen.blit(labyrinth_case,
                                (x_corner_top_left, y_corner_top_left))
                elif stripe == NEEDLE_STRIPE:
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 0))
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 20))
                    labyrinth_case.blit(self.needle.object_image, (4, 4))
                    screen.blit(labyrinth_case,
                                (x_corner_top_left, y_corner_top_left))
                elif stripe == TUBE_STRIPE:
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 0))
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 20))
                    labyrinth_case.blit(self.tube.object_image, (4, 4))
                    screen.blit(labyrinth_case,
                                (x_corner_top_left, y_corner_top_left))
                elif stripe == ETHER_STRIPE:
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 0))
                    labyrinth_case.blit(self.labyrinth.floor_image, (0, 20))
                    labyrinth_case.blit(self.ether.object_image, (4, 4))
                    screen.blit(labyrinth_case,
                                (x_corner_top_left, y_corner_top_left))
                num_stripe += 1
            num_line += 1

    def __update_level_console(self, screen):
        """ This method updates the console which contains the number and the
        image of items collected by the Hero """

        console = pygame.Surface((600, 50))
        console.fill(BLACK)

        title_console = pygame.Surface((200, 50))
        font_text = pygame.font.SysFont('freesans', 36)
        item_text = font_text.render(
            "Item Number: " + str(self.hero.numb_items), True, WHITE)

        title_console.blit(item_text, (0, 0))
        console.blit(title_console, (0, 12))

        if self.needle.found:
            self.__update_item_console(self.needle, 200, console)
        if self.ether.found:
            self.__update_item_console(self.ether, 250, console)
        if self.tube.found:
            self.__update_item_console(self.tube, 300, console)

        screen.blit(console, (0, 600))

    def __update_item_console(self, item, x_position, surface):
        """ This method loads the item surface in the console """

        item_console = pygame.Surface((50, 50))
        item_console.blit(item.object_image, (9, 9))
        surface.blit(item_console, (x_position, 0))

    def __update_menu_design(self, screen):
        """ This method updates the menu selection """

        # Get the fonts
        choice_text = pygame.font.SysFont('freesans', 50)

        # Creation of game statut
        game_statut = pygame.Surface((X_MESSAGE, Y_MESSAGE))
        game_statut.fill(DARKGRAY)
        text_statut = choice_text.render(self.menu_message, True, WHITE)
        text_statut_position = text_statut.get_rect()
        text_statut_position.centerx = game_statut.get_rect().centerx
        text_statut_position.centery = game_statut.get_rect().centery
        game_statut.blit(text_statut, text_statut_position)

        # Creation of play button
        play_button = pygame.Surface((X_BUTTON, Y_BUTTON))
        play_button.fill(DARKGRAY)
        pygame.draw.rect(play_button, self.play_button_color,
                         (0, 0, X_BUTTON, Y_BUTTON), BORDER)
        play_text = choice_text.render("PLAY", True, self.play_button_color)
        play_text_position = play_text.get_rect()
        play_text_position.centerx = play_button.get_rect().centerx
        play_text_position.centery = play_button.get_rect().centery
        play_button.blit(play_text, play_text_position)

        # Creation of quit button
        quit_button = pygame.Surface((X_BUTTON, Y_BUTTON))
        quit_button.fill(DARKGRAY)
        pygame.draw.rect(quit_button, self.quit_button_color,
                         (0, 0, X_BUTTON, Y_BUTTON), BORDER)
        quit_text = choice_text.render("QUIT", True, self.quit_button_color)
        quit_text_position = quit_text.get_rect()
        quit_text_position.centerx = quit_button.get_rect().centerx
        quit_text_position.centery = quit_button.get_rect().centery
        quit_button.blit(quit_text, quit_text_position)

        # Integration of the different elements into screen
        screen.blit(game_statut, (20, 0))
        screen.blit(play_button, (150, 300))
        screen.blit(quit_button, (150, 425))

    def __update_screen_interaction(self):
        """ This method updates the labyrinth screens """
        self.screen_interaction.fill(DARKGRAY)
        if self.menu:
            self.__update_menu_design(self.screen_interaction)
        elif self.play_game:
            self.__update_level_design(self.screen_interaction)
            self.__update_level_console(self.screen_interaction)

        self.window.blit(
            self.screen_interaction,
            (X_CORNER_SCREEN_INTERACTION, Y_CORNER_SCREEN_INTERACTION))

    def __process_event_menu(self, event: pygame.event):
        """ This method groups all the interaction the player can have with the menu """

        self.__interact_with_button_menu(event)
        self.__select_option_menu(event)

    def __interact_with_button_menu(self, event: pygame.event):
        """ This method manages the switch between menu button """

        if self.selected_button == "play_game" and event.key == pygame.K_DOWN:
            self.play_button_color = BLACK
            self.quit_button_color = WHITE
            self.selected_button = "quit_game"
        elif self.selected_button == "quit_game" and event.key == pygame.K_UP:
            self.play_button_color = WHITE
            self.quit_button_color = BLACK
            self.selected_button = "play_game"

    def __select_option_menu(self, event: pygame.event):
        """ This method manages the menu button selection """

        if self.selected_button == "play_game" and event.key == pygame.K_RETURN:
            self.menu = False
            self.play_game = True
            self.__prepare()
        elif self.selected_button == "quit_game" and event.key == pygame.K_RETURN:
            self.start_program = False

    def __process_event_game(self, event: pygame.event):
        """ This method manages the process of the game"""

        if event.key == pygame.K_RIGHT:
            self.hero.move("right", self.labyrinth)
            self.labyrinth.update_labyrinth_structure(self.hero)
        elif event.key == pygame.K_LEFT:
            self.hero.move("left", self.labyrinth)
            self.labyrinth.update_labyrinth_structure(self.hero)
        elif event.key == pygame.K_UP:
            self.hero.move("up", self.labyrinth)
            self.labyrinth.update_labyrinth_structure(self.hero)
        elif event.key == pygame.K_DOWN:
            self.hero.move("down", self.labyrinth)
            self.labyrinth.update_labyrinth_structure(self.hero)

    def __get_status_game(self, event: pygame.event):
        """ this method will determine the statut of the game when Mac Gyver
        will touch Murdoc or an item """

        game_status = ""
        if event.key == pygame.K_RIGHT:
            game_status = self.hero.touch_something("right", self.labyrinth)
        elif event.key == pygame.K_LEFT:
            game_status = self.hero.touch_something("left", self.labyrinth)
        elif event.key == pygame.K_UP:
            game_status = self.hero.touch_something("up", self.labyrinth)
        elif event.key == pygame.K_DOWN:
            game_status = self.hero.touch_something("down", self.labyrinth)

        if game_status == "game_over":
            self.play_game = False
            self.menu = True
            self.menu_message = "GAME OVER - ANOTHER ONE?"
        elif game_status == "win":
            self.play_game = False
            self.menu = True
            self.menu_message = "WINNER - ANOTHER ONE?"
        elif game_status == "found_needle":
            self.needle.found = True
        elif game_status == "found_ether":
            self.ether.found = True
        elif game_status == "found_tube":
            self.tube.found = True

    def start(self):
        """ This method loads the game """

        while self.start_program:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.start_program = False
                elif event.type == pygame.KEYDOWN:
                    if self.menu:
                        self.__process_event_menu(event)
                    elif self.play_game:
                        self.__get_status_game(event)
                        self.__process_event_game(event)
                    else:
                        self.start_program = False
            self.__update_screen_interaction()
            pygame.display.flip()
示例#42
0
class Game:
	def setup(self):
		self.player = Character()
		self.monsters = [
			Goblin(),
			Troll(),
			Dragon()
		]
		self.monster = self.get_next_monster()
	
	def get_next_monster(self):
		try:
			return self.monsters.pop(0)
		except IndexError:
			return None

	def monster_turn(self):
		# check to see if the monster attacks
		if self.monster.attack():
			print("{} is attacking!".format(self.monster))
			if input("Dodge? Y/N ").lower() == 'y':
				if self.player.dodge():
					print("You dodged the attack! ")
				else:
					print("You got hit anyway!")
					self.player.hit_points -= 1
			else:
				print("{} hit you for 1 point!".format(self.monster))
				self.player.hit_points -= 1
		else:
			print("{} isn't attacking this turn.".format(self.monster))
		# If so, tell the player
		# Check if the player wants to dodge
		# If so, see if the dodge is successful
		# If it is, move on
		# If it's not, remove one player hit point
		# If monster isn't attacking, tell that to the player too
		
	def player_turn(self):
		player_choice = input("[A]ttack, [R]est, [Q]uit? ").lower()
		if player_choice == 'a':
			print("You're attacking {}".format(self.monster))
			if self.player.attack():
				if self.monster.dodge():
					print("{} dodged your attack!".format(self.monster))
				else:
					if self.player.leveled_up():
						self.monster.hit_points -= 2
					else:
						self.monster.hit_points -= 1

					print("You hit {} with your {}".format(self.monster,self.player.weapon))
			else:
				print("You missed!")
		elif player_choice == 'r':
			self.player.rest()
		elif player_choice == 'q':
			sys.exit()
		else:
			self.player_turn()
		
		
		# Let the player attack, rest, or quit
		# If they attack:
			# See if the attack is successful
			# If so, see if the monster dodges
				#If dodged, print that
				#If not dodged, subtract the right num of hit points from the monster
			# If not a good attack, tell the player
		# If they rest:
			# Call the player.rest() method
		# If they quit, exit the game
		# If they pick anything else, re-run this method
	
	def cleanup(self):
		if self.monster.hit_points <= 0:
			self.player.experience += self.monster.experience
			print("You killed {}!".format(self.monster))
			self.monster = self.get_next_monster()


		# If the monster has no more hit points:
			#Up the player's experience
			# print a message
			# get a new monster

	def __init__(self):
		self.setup()

		while self.player.hit_points and (self.monster or self.monsters):
			print("\n"+"="*20)
			print(self.player)
			self.monster_turn()
			print('-'*20)
			self.player_turn()
			self.cleanup()
			print("\n"+"="*20)

		if self.player.hit_points:
			print("You win!")
		elif self.monsters or self.monster:
			print("You lose!")
		sys.exit()
示例#43
0
def comm(request):
    input = request.POST.get('i')
    _in = str(input).lower()

    print 'input: %s => %s' % (str(input), str(_in))

    session = request
    print 'session:'
    pprint(session)

    res = response()

    _character = Character()
    res.update({'character': _character.dump()})

    print 'input: %s' % _in
    if not _in:
        res['output'] = {
            'klass': 'red',
            'data': 'Sorry, I do not recognize that request',
        }

    if _in.isalnum():
        words = _in.split(' ')

        print 'words: %s' % str(words)

        if isinstance(words, list):

            if len(words) != 1:
                #error... at the moment
                """
                at some point this is where the nltk would come into play
                """
                res['output'].update({
                    'klass':
                    'red',
                    'data': [
                        'Please state one word commands,',
                        'I am a basic program.', 'Thank you.'
                    ]
                })
            else:
                word = str(words[0])
                if word == '0':
                    res['output'].update({
                        'klass': 'yellow',
                        'data': 'Welcome to Catacombs!!!'
                    })

                elif word in res['character']['commands']:
                    res.update({'output': _character.fetch(word)})

                elif word in ['north', 'south', 'east', 'west', 'up', 'down']:
                    res.update({'output': 'heading %s' % word})

                else:
                    #error
                    res.update({
                        'color': 'red',
                        'output': 'unrecognized command.'
                    })

    else:
        #error
        res.update({
            'color':
            'red',
            'output': [
                'Letters and numbers only please...',
                'Special characters are rejected.'
            ]
        })

    return res
示例#44
0
 def generateCharacters(self, actors):
     characters = []
     for ii in range(0, actors):
         name = "Actor " + str(ii+1)
         characters.append(Character(name))
     return characters
示例#45
0
def main():
    screen_width = 80
    screen_height = 50
    cardtable_width = 18
    cardtable_height = screen_height
    cardtable_x = screen_width - cardtable_width

    panel_height = 10
    panel_y = screen_height - panel_height
    panel_width = screen_width - cardtable_width

    map_width = screen_width - cardtable_width
    map_height = screen_height - panel_height

    message_x = 2
    message_width = panel_width - 2
    message_height = panel_height - 1

    message_log = MessageLog(message_x, message_width, message_height)

    panel = tcod.console.Console(panel_width, panel_height)
    mapcon = tcod.console.Console(map_width, map_height)
    cardtable = tcod.console.Console(cardtable_width, cardtable_height)

    # number of dice, sideness of dice. values used taken from gunslinger pregen, pg88
    player_charactersheet = Character()
    print(player_charactersheet)


    player = Entity(int(screen_width / 2), int(screen_height / 2), '@', tcod.white, 'Player', True, RenderOrder.ACTOR, Fighter(6))
    entities = [player]

    game_map = tcod.map.Map(map_width, map_height)
    generate_map(game_map, player, entities)

    fov_recompute = True


    fate_pot = Counter({'white': 50, 'red': 25, 'blue':10})
    player_fate = Counter()
    player_fate.update(sample(list(fate_pot.elements()), 3))
    fate_pot.subtract(player_fate)



    # FIXME: Currently, this does not include Jokers, which are required
    #        for decks used in Deadlands. The class can be instantiated to
    #        use jokers, but its use of jokers does not differentiate between
    #        red and black jokers (as required in Deadlands) so the issue of
    #        jokers is left to another day.

    # Also probably the suit hierarchy is not the same as Deadlands; that should be easy
    # to fix when I get to it.
    marshal_deck = pydealer.Deck()
    posse_deck = pydealer.Deck()

    marshal_deck.shuffle()
    posse_deck.shuffle()

    player_hand = pydealer.Stack() # pydealer.Stack()
    marshal_hand = pydealer.Stack()

    player_hand.sort()

    posse_discard = pydealer.Stack()
    marshal_discard = pydealer.Stack()

    tcod.console_set_custom_font('cp437_10x10.png', tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_CP437)
    root_console = tcod.console_init_root(screen_width, screen_height, 'Deadlands Duel', False, tcod.RENDERER_SDL2, vsync=True)

    player_round_movement_budget = player_charactersheet.get_movement_budget()
    move_this_action = 0

    active_card = pydealer.Stack() # posse_deck.deal(1)

    colt_army = {'shots': 6,
                 'max_shots': 6,
                 'range': 10,
                 'damage': {'number_of_dice': 3, 'sideness_of_dice': 6}}

    game_state = GameStates.PLAYERS_TURN

    # FIXME: There's probably an elegant solution to be found in generalizing this
    # list to include the player, and sorting it by action cards, or something.
    enemy_combatants = []

    while True:

        if fov_recompute:
            game_map.compute_fov(player.x, player.y, algorithm=tcod.FOV_PERMISSIVE(5))

            if game_state ==GameStates.PLAYERS_TURN:
                for entity in entities:
                    if entity.name == 'Bandit' and game_map.fov[entity.y, entity.x]:
                        game_state = GameStates.BEGIN_DETAILED_COMBAT_ROUND
                        break

            if game_state ==GameStates.ROUNDS_PLAYERS_ACTION:
                enemies_in_view = False
                for entity in entities:
                    if entity.name == 'Bandit' and game_map.fov[entity.y, entity.x]:
                        enemies_in_view = True
                if enemies_in_view == False:
                    message_log.add_message(Message("All visible bandits dead, leaving combat rounds..."))
                    posse_discard.add(active_card.deal(active_card.size))
                    posse_discard.add(player_hand.deal(player_hand.size))
                    game_state =GameStates.PLAYERS_TURN
                    enemy_combatants = []

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if (entity.name == 'Bandit') and (not game_map.fov[entity.y, entity.x]):
                    if entity.fighter.shots < 6:
                        # When the player ducks behind a wall to reload their revolver,
                        # the bandits also take advantage of the opportunity!
                        entity.fighter.shots += 1
            game_state = GameStates.PLAYERS_TURN


        if game_state == GameStates.BEGIN_DETAILED_COMBAT_ROUND:
            # Let the player know what's going on
            message_log.add_message(Message("Beginning of combat round!"))

            # Deal the player a hand from the posse deck and calc their movement
            player_round_movement_budget = player_charactersheet.get_movement_budget()
            roll_new_round(player_hand, player_charactersheet, posse_deck, posse_discard, message_log)

            # We *should* deal the enemies an action hand, and calc their movement.
            # FIXME: Currently, we use the ultra-simple shortcut for enemies
            # from the Marshal Tricks section of the rules, dealing them a single card.
            # This combat really isn't on a scale where that is justified, at least not until
            # more enemies are clued in to the combat via sound or a vague awareness metric.
            # Also, enemy movement is not yet implemented, so we don't calc their move rate.
            for entity in entities:
                if entity.name == 'Bandit' and game_map.fov[entity.y, entity.x]:
                    entity.fighter.action_hand = marshal_deck.deal(1)
                    enemy_combatants.append(entity)

            game_state = GameStates.MEDIATE_COMBAT_ROUNDS

        if game_state == GameStates.MEDIATE_COMBAT_ROUNDS:
            # FIXME: Should we keep track of a list of combat activated enemies?
            # As a quick hack, right now it's just FOV.
            # (calculated in BEGIN_DETAILED_COMBAT_ROUNDS conditional above)
            remaining_enemy_cards = False
            for combatant in enemy_combatants:
                if combatant.fighter.action_hand.size > 0:
                    # print(combatant.fighter.action_hand.size)
                    remaining_enemy_cards = True

            if remaining_enemy_cards or (player_hand.size > 0): # and (active_card.size > 0)):

                highest_player = None
                if player_hand.size > 0:
                    highest_player = player_hand[player_hand.size - 1]
                # print("highest player card " + str(highest_player))

                highest_combatant = None
                highest_comb_card = None
                if remaining_enemy_cards:
                    for combatant in enemy_combatants:
                        print("combatant card: " + str(combatant.fighter.action_hand[combatant.fighter.action_hand.size - 1]))
                        if highest_comb_card == None:
                            highest_combatant = combatant
                            highest_comb_card =  combatant.fighter.action_hand[combatant.fighter.action_hand.size - 1]
                        elif combatant.fighter.action_hand[combatant.fighter.action_hand.size - 1] > highest_comb_card:
                            highest_combatant = combatant
                            highest_comb_card =  combatant.fighter.action_hand[combatant.fighter.action_hand.size - 1]

                # print("highest combatant card " + str(highest_comb_card))

                if remaining_enemy_cards and ((highest_combatant) and ((highest_player == None)) or (highest_comb_card > highest_player)):
                    # Enemy turn, in combat rounds. Placeholder.
                    message_log.add_message(Message("The " + highest_combatant.name + " acts on a " + str(highest_comb_card) + "!", tcod.orange))
                    if highest_combatant.fighter.shots > 0:
                        tn = 5
                        modifier = 0 - highest_combatant.fighter.get_most_severe_wound()[1]
                        range_increments = (highest_combatant.distance_to(player) / 3) // colt_army['range']
                        tn += range_increments

                        shootin_roll = skill_roll(2, 8, tn, modifier)
                        success = shootin_roll.get('success')
                        if success:
                            vital_hit = False
                            body_part = None
                            hitlocation = unexploding_roll(20)
                            if (hitlocation == 20):
                                vital_hit = True
                                body_part = 'head'
                            elif 15 <= hitlocation <= 19:
                                body_part = 'guts' #upper
                            elif 11 <= hitlocation <= 14:
                                body_part = '_arm'
                                if unexploding_roll(2) == 1:
                                    body_part = 'left' + body_part
                                else:
                                    body_part = 'right' + body_part
                            elif hitlocation == 10:
                                vital_hit = True
                                body_part = 'guts' #gizzards
                            elif 5 <= hitlocation <= 9:
                                body_part = 'guts' #lower
                            else:
                                body_part = '_leg'
                                if unexploding_roll(2) == 1:
                                    body_part = 'left' + body_part
                                else:
                                    body_part = 'right' + body_part


                            message_log.add_message(Message("The bandit takes aim and shoots, hitting you in the " + body_part + "!", tcod.red))
                            dmg = ranged_weapon_damage_roll(colt_army['damage']['sideness_of_dice'], colt_army['damage']['number_of_dice'], vital_bonus = vital_hit)
                            message_log.add_message(player.fighter.take_positional_damage(dmg, body_part, fate_pot, player_fate))
                            if (player.fighter.body_wounds['guts'] >= 5) or (player.fighter.body_wounds['head'] >= 5):
                                message_log.add_message(kill_monster(player))
                                game_state = GameStates.PLAYER_DEAD
                        else:
                            message_log.add_message(Message("The bandit takes aim and shoots! The bullet whizzes past you!", tcod.orange))
                        highest_combatant.fighter.shots -= 1
                    else:
                        message_log.add_message(Message("The bandit loads his revolver..."))
                        highest_combatant.fighter.shots += 1
                    marshal_discard.add(highest_combatant.fighter.action_hand.deal(1))
                    enemy_combatants.remove(highest_combatant)
                else:
                    # FIXME: This erroneously includes tied situations, which the rules say
                    # should result in simultaneous actions.

                    # Player's turn, in combat rounds.
                    game_state = GameStates.ROUNDS_PLAYERS_ACTION
            else:
                game_state = GameStates.BEGIN_DETAILED_COMBAT_ROUND

        if game_state == GameStates.ROUNDS_ENEMY_ACTION:
            print("Shouldn't be possible???")


        render_all(root_console, entities, mapcon, game_map, cardtable, cardtable_x, player_hand, active_card, player_fate, panel, panel_y, message_log, player.fighter.body_wounds)

        tcod.console_flush()

        action = handle_events()

        move = action.get('move')

        activate_card = action.get('activate_card')

        shoot = action.get('shoot')

        pass_turn = action.get('pass_turn')

        reload = action.get('reload')

        if move and (game_state == GameStates.PLAYERS_TURN):
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy
            if (0 <= destination_x < game_map.width) and (0 <= destination_y < game_map.height):
                if game_map.walkable[destination_y, destination_x]:
                    target = get_blocking_entities_at_location(entities, destination_x, destination_y)

                    if target:
                        message_log.add_message(Message('You kick the ' + target.name + ' in the shins, much to its annoyance!'))
                    else:
                        player.move(dx, dy)
                        fov_recompute = True
                    game_state = GameStates.ENEMY_TURN


        if pass_turn and (game_state == GameStates.ROUNDS_PLAYERS_ACTION): # pass action would be more accurate, for how i have modified this since creating it
            # if active_card.size == 0:
            #     posse_discard.add(player_hand.deal(player_hand.size))
            #
            #     player_round_movement_budget = player_charactersheet.get_movement_budget()
            #     roll_new_round(player_hand, player_charactersheet, posse_deck, posse_discard, message_log)
            #elif
            if active_card.size > 0:
                posse_discard.add(active_card.deal(active_card.size))
                game_state = GameStates.MEDIATE_COMBAT_ROUNDS
                # The following should be covered by the MEDIATE_COMBAT_ROUNDS

                # if player_hand.size == 0:
                #     posse_discard.add(player_hand.deal(player_hand.size))
                #
                #     player_round_movement_budget = player_charactersheet.get_movement_budget()
                #     roll_new_round(player_hand, player_charactersheet, posse_deck, posse_discard, message_log)

        if activate_card and (active_card.size == 0) and (game_state == GameStates.ROUNDS_PLAYERS_ACTION):

            #nominate new active card. (test-only terminiology)
            if activate_card == -1:
                move_this_action = 0
                if player_hand.size > 0:
                    active_card.add(player_hand.deal(1, 'top'))
                    # player_hand.sort()

        if reload and ((game_state == GameStates.ROUNDS_PLAYERS_ACTION) or (game_state ==GameStates.PLAYERS_TURN)):
            if colt_army['shots'] == colt_army['max_shots']:
                message_log.add_message(Message("Your revolver is fully loaded.", tcod.blue))
            elif (game_state ==GameStates.PLAYERS_TURN) or ((game_state == GameStates.ROUNDS_PLAYERS_ACTION) and (active_card.size > 0)):
                colt_army['shots'] += 1
                message_log.add_message(Message("You load a bullet into your revolver.", tcod.green))
                if (game_state ==GameStates.ROUNDS_PLAYERS_ACTION):
                    posse_discard.add(active_card.deal(active_card.size))
                    game_state = GameStates.MEDIATE_COMBAT_ROUNDS
                    # if player_hand.size == 0:
                    #     player_round_movement_budget = player_charactersheet.get_movement_budget()
                    #     roll_new_round(player_hand, player_charactersheet, posse_deck, posse_discard, message_log)

        if shoot and (game_state == GameStates.ROUNDS_PLAYERS_ACTION):
            if (active_card.size > 0) and (colt_army['shots'] == 0):
                message_log.add_message(Message("You need to reload!", tcod.red))
            elif (active_card.size > 0) and (colt_army['shots'] > 0):
                # Shoot is currently the only "real" action that uses up the active card.
                modifier = 0
                if move_this_action > ((player_charactersheet.pace * 3) // 5):
                    message_log.add_message(Message("You attempt to draw a bead while running...", tcod.orange))
                    modifier = -4
                elif move_this_action > 0:
                    message_log.add_message(Message("You fire while walking...", tcod.yellow))
                    modifier = -2

                wound_modifier = 0 - player.fighter.get_most_severe_wound()[1]
                modifier += wound_modifier

                nearest_target = None
                nearest_distance = 999
                for entity in entities:
                    if game_map.fov[entity.y, entity.x]:
                        if entity.fighter:
                            if not entity.name is 'Player':
                                new_distance = entity.distance_to(player)
                                if new_distance < nearest_distance:
                                    nearest_distance = new_distance
                                    nearest_target = entity
                tn = 5

                range_increments = (nearest_distance / 3) // colt_army['range']
                tn += range_increments

                shootin_roll = skill_roll(player_charactersheet.shootin_pistol['trait'], player_charactersheet.shootin_pistol['aptitude'], tn, modifier)

                bust = shootin_roll.get('bust')
                failure = shootin_roll.get('failure')
                success = shootin_roll.get('success')
                message_log.add_message(Message("BANG!!", tcod.brass))

                colt_army['shots'] -= 1
                if colt_army['shots'] == 0:
                    message_log.add_message(Message("That was your last loaded bullet!", tcod.red))

                if bust:
                    message_log.add_message(Message("You went bust, and narrowly avoided shooting your own foot!", tcod.red))
                else:
                    if not nearest_target:
                        if failure:
                            message_log.add_message(Message("You shoot the broad side of a barn!"))
                        elif success:
                            if success == 1:
                                message_log.add_message(Message("You shoot some bottles for target practice!", tcod.green))
                            else:
                                message_log.add_message(Message("You put a bullet hole in the forehead of a Wanted poster!", tcod.blue))
                    else:
                        if failure:
                            message_log.add_message(Message("The bullet whizzes past your target!"))
                        elif success:
                            vital_hit = False
                            hitlocation = unexploding_roll(20)
                            if (hitlocation == 20) or (hitlocation == 10):
                                vital_hit = True
                            if success == 1:
                                message_log.add_message(Message("You manage to hit your target!", tcod.green))
                            else:
                                if ((20 - hitlocation) <= success) or (0 < (10 - hitlocation) <= success) or (0 < (hitlocation - 10) <= success):
                                    vital_hit = True
                                message_log.add_message(Message("You accurately shoot your target!", tcod.blue))

                            dmg = ranged_weapon_damage_roll(colt_army['damage']['sideness_of_dice'], colt_army['damage']['number_of_dice'], vital_bonus = vital_hit)

                            message_log.add_message(nearest_target.fighter.take_simple_damage(dmg))
                            if nearest_target.fighter.get_most_severe_wound()[1] >= 5:
                                message_log.add_message(kill_monster(nearest_target))
                                marshal_discard.add(nearest_target.fighter.action_hand.deal(nearest_target.fighter.action_hand.size))

                posse_discard.add(active_card.deal(1))

                game_state = GameStates.MEDIATE_COMBAT_ROUNDS
                # if player_hand.size == 0:
                #     player_round_movement_budget = player_charactersheet.get_movement_budget()
                #     roll_new_round(player_hand, player_charactersheet, posse_deck, posse_discard, message_log)

        # FIXME: As currently written, this lets you move both before and after an action card.
        # First, the game lets you move a partial movement,
        #     then, you can use your single card to initate a "new" action and reset the
        #     tracking of movements per action,
        #       which lets you evade potential running penalties in some situations (penalty not implemented yet)
        if (move and (player_round_movement_budget > 0) and (active_card.size > 0) and (game_state ==GameStates.ROUNDS_PLAYERS_ACTION)):
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy
            if (0 <= destination_x < game_map.width) and (0 <= destination_y < game_map.height):
                if game_map.walkable[destination_y, destination_x]:
                    target = get_blocking_entities_at_location(entities, destination_x, destination_y)

                    if target:
                        message_log.add_message(Message('You kick the ' + target.name + ' in the shins, much to its annoyance!'))
                    else:
                        player.move(dx, dy)
                        player_round_movement_budget -= 1
                        # We track our movement taking place in this action card.
                        # We can move up to twice our pace the whole round spread across all our actions.
                        # We incur a running penalty on an action where we have also moved more than our pace;
                        # ie, more than half our full movement budget
                        # (which is calculated to a maximum with running in mind)
                        move_this_action += 1
                        #                       pace in yards.         yds->ft   ft->squares
                        if move_this_action > ((player_charactersheet.pace * 3) // 5):
                            message_log.add_message(Message("Running!!!", tcod.orange))
                        else:
                            message_log.add_message(Message("Walking...", tcod.yellow))
                        fov_recompute = True
示例#46
0
        vt_oh = lines[i]
        if vt_oh[0:1] != '~' and vt_oh[0:1] != '-' and vt_oh[0:2] != 'KD':
            vt_oh = "+" + vt_oh
        i += 1
        vt_ob = lines[i]
        if vt_ob[0:1] != '~' and vt_ob[0:1] != '-' and vt_ob[0:2] != 'KD':
            vt_ob = "+" + vt_ob
        i += 1

        if len(startup) > 0:
            move = Move(notation, startup, active, recovery, h, b, damage,
                        stun, knd, vt_oh, vt_ob)
            character.add_move(move)


abigail = Character("Abigail", 1100, 1050)
my_char.append(abigail.name)
char_dict[abigail.name] = abigail
file_reader(abigail, "abigail.txt")

alex = Character("Alex", 1050, 1075)
my_char.append(alex.name)
char_dict[alex.name] = alex
file_reader(alex, "alex.txt")

akuma = Character("Akuma", 900, 900)
my_char.append(akuma.name)
char_dict[akuma.name] = akuma
file_reader(akuma, "akuma.txt")

balrog = Character("Balrog", 1025, 1050)
示例#47
0
 def test_map_description_position_1_1(self, mock_stdout):
     test_character = Character('Jihyo', 10, [1, 1], 0)
     dialogue_and_scripts.map_description(test_character)
     expected_stdout = "You are at the northwest corner of the house. You feel weird facing a corner."
     self.assertIn(expected_stdout, mock_stdout.getvalue())
示例#48
0
knife = Item("knife")
ballroom.add_items(knife)

refrigerator = Container("refrigerator")
refrigerator.add_properties("too heavy")
refrigerator.add_contents(cheese, pizza)
refrigerator.key = knife

kitchen.add_items(refrigerator, cheese, pizza)

book = Item("book")
dining_hall.add_items(book)


# define characters and enemies
mike = Character("Mike", "a computer programmer")
mike.conversation = ["You never know when you could use some cheese.", "And you can't use cheese after you've eaten it."]
mike.QA = ({"what", "favorite", "language"}, "Python, of course!")
kitchen.inhabitants.add(mike)

dave = Enemy("Dave", "a smelly zombie")
dave.conversation = ["What's up, dude! I'm hungry.", "What do you call cheese that isn't yours?", "Nacho cheese!"]
dave.weakness = cheese
dining_hall.inhabitants.add(dave)

eddie = Enemy("Eddie", "another smelly zombie")
eddie.conversation = ["I'm not really hungry.", "Ok, I'm a zombie.  I'm always hungry.", "But for what?!"]
eddie.weakness = pizza
dining_hall.inhabitants.add(eddie)

tabitha = Enemy("Tabitha", "an enormous spider with countless eyes and furry legs.")
示例#49
0
#ssss these aren't real test
from character import Character
from character import Hero
from character import Monster

# Characters can be instantiated with avatar and name

arya = Character("Arya Stark", "arya.png")
jon = Character("Jon Stark", "jon.png")

print(arya.name, arya.avatar)
print(jon.name, jon.avatar)

# After adding stuff two inventory
# length of inventory should == 2

arya.inventory.append('Needle')
arya.inventory.append('Mask')

print(len(arya.inventory))

# aray should have a `greet` method
# and when called should return
# "hello, I am arya start?"
#when i call it with `arya.greet_charactor(jon)
# should return
# 'hello jon snow, i'm arya starK?`
print(arya.greet())
print(arya.greet_character(jon))
print(arya.greet_character())
示例#50
0
class ArenaEngine():
    """Accepts commands and executes game funtions"""
    def __init__(self, currentcharacter, roundnum):
        self.mainchar = currentcharacter
        self.round = roundnum
        self.gameover = False
        self.nextenemy = 0
        self.victories = 0
        self.COMMANDS = ("New Game", "Fight", "Next Round", "Stats",
                         "Inventory")
        self.COMMAND_PROMPT = ("(F)ight", "(N)ext Round", "(S)tats",
                               "(I)nventory")
        self.STATES = ("Startup", "Management", "Battle")
        self.currentstate = self.STATES[0]
        self.currentcommand = 0

    def accept_command(self, command):
        """Responds to user commands"""
        if self.currentstate == self.STATES[0]:
            self.execute_new_game()
        elif self.currentstate == self.STATES[1]:
            if command.lower() == self.COMMANDS[3].lower() or command.lower(
            ) == self.COMMANDS[3][0].lower():
                self.execute_stats()
            elif command.lower() == self.COMMANDS[4].lower() or command.lower(
            ) == self.COMMANDS[4][0].lower():
                self.execute_inventory()
            elif command.lower() == self.COMMANDS[2].lower() or command.lower(
            ) == self.COMMANDS[2][0].lower():
                self.execute_next_round()
            elif command.lower() == self.COMMANDS[1].lower() or command.lower(
            ) == self.COMMANDS[1][0].lower():
                self.execute_fight()
            #test for valid command input
        else:  #self.currentstate == self.STATES[2]:
            #test for valid command input
            if command.lower() == self.COMMANDS[1].lower() or command.lower(
            ) == self.COMMANDS[1][0].lower():
                self.execute_fight()

    def execute_new_game(self):
        """Sets up new game"""
        self.round = 1
        newname = raw_input("Name your character:")
        self.mainchar = Character(newname)
        self.mainchar.roll_character()
        defaultweapon = Weapon(1, traits[0])
        self.mainchar.equipment["Weapon"] = defaultweapon
        defaultarmor = Armor(1)
        self.mainchar.equipment["Armor"] = defaultarmor
        self.currentstate = self.STATES[1]
        print("Prepare to face 10 rounds of challengers.")
        print("You can face as many challengers in a round as you wish.")
        print("However, you mus defeat at least 5 before you can move on\n")

    def execute_next_round(self):
        """Moves to next round"""
        if self.victories >= 5:
            print("Round " + str(self.round) + " complete!!\n")
            self.round += 1
            if self.round < 11:
                print("Starting round " + str(self.round) + "\n")
                self.victories = 0
                self.mainchar.hp = self.mainchar.maxhp
                self.mainchar.sp = self.mainchar.maxsp
            else:
                print("You WIN!!")
                self.gameover = True
                self.currentState = self.STATES[0]
                #Consider adding output of chracter stats
        else:
            print("Not enough victories! Keep fighting.\n")

    def execute_stats(self):
        """Displays character stats"""
        print("********\n")
        print(self.mainchar.name + " Level " + str(self.mainchar.level) +
              " \n")
        for trait in traits:
            print(trait + ": " + str(self.mainchar.stats[trait]) + "\n")

        print("Total Experience: " + str(self.mainchar.experience))
        print("Next Level at: " + str((self.mainchar.level + 1)**2))
        print("Victories: " + str(self.victories))
        print("********\n")

        while self.mainchar.experience >= (self.mainchar.level + 1)**2:
            #if self.mainchar.experience >= (self.mainchar.level+1)**2: #self.mainchar.is_ready_to_level:
            print("You have gained a level\n What stat would you like to" +
                  " increase\n")
            choice = raw_input("Str, Speed, Con, Skill:")
            if choice.lower() == "str":
                self.mainchar.stats["Strength"] += 1
                print("Stat increased by one \n")
                self.mainchar.level += 1
            elif choice.lower() == "speed":
                self.mainchar.stats["Speed"] += 1
                print("Stat increased by one \n")
                self.mainchar.level += 1
            elif choice.lower() == "con":
                self.mainchar.stats["Constitution"] += 1
                self.mainchar.maxhp += 10
                self.mainchar.hp += 10
                print("Stat increased by one \n")
                self.mainchar.level += 1
            elif choice.lower() == "skill":
                self.mainchar.stats["Skill"] += 1
                self.mainchar.sp += 10
                self.mainchar.maxsp += 10
                print("Stat increased by one \n")
                self.mainchar.level += 1
            else:
                print("Not a valid request")
                break

    def execute_inventory(self):
        """Allows selection of inventory"""
        #display all items
        print("Equipment: ")
        for key, value in self.mainchar.equipment.items():
            print(value.get_description() + "\n")
        print("Inventory: ")
        for item in self.mainchar.inventory:
            print(item.get_description() + "\n")
        #prompt for action: equip, exit...consider adding drop
        options = ("(1) Equip,(2) Drop,(3) Exit \n")
        choice = raw_input(options)
        if choice == "1":
            whichone = raw_input("Name the Item you would like to wear \n")
            found = False
            for item in self.mainchar.inventory:
                if whichone.lower() == item.get_description().lower():
                    self.mainchar.equip(item)
                    print("You have equipped " + item.get_description())
                    found = True
            if not found:
                print("You don't have that in your inventory")
        elif choice == '2':
            whichone = raw_input("Name the Item you would like to drop \n")
            found = False
            for item in self.mainchar.inventory:
                if whichone.lower() == item.get_description().lower():
                    self.mainchar.inventory.remove(item)
                    print("You have dropped: " + item.get_description())
                    found = True
                    break
            if not found:
                print("You don't have that")

    def execute_fight(self):
        """Starts Battle state"""
        #create enemy and display
        self.generate_enemy()
        victorious = False
        print("You have encountered a " + self.nextenemy.name + "\n")
        #give choices of action
        options = "(1) Attack, (2) Flee \n"
        #action loop
        while self.nextenemy.hp > 0 and self.mainchar.hp > 0:
            choice = raw_input(options)
            maininit = self.mainchar.roll_initiative()
            foeinit = self.nextenemy.roll_initiative()
            #attack sequence with messages
            if choice == "1":
                #describe round of battle
                if maininit > foeinit:
                    damage = self.attack_attempt(self.mainchar, self.nextenemy)
                    hitdesc = " strikes "
                    if damage == 0:
                        hitdesc = " misses "
                    print(self.mainchar.name + hitdesc + self.nextenemy.name +
                          " for " + str(damage) + " damage")
                    if self.nextenemy.hp <= 0 and self.mainchar.hp > 0:
                        victorious = True
                        break
                    damage = self.attack_attempt(self.nextenemy, self.mainchar)
                    hitdesc = " strikes "
                    if damage == 0:
                        hitdesc = " misses "
                    print(self.nextenemy.name + hitdesc + self.mainchar.name +
                          " for " + str(damage) + " damage")
                else:
                    damage = self.attack_attempt(self.nextenemy, self.mainchar)
                    hitdesc = " strikes "
                    if damage == 0:
                        hitdesc = " misses "
                    print(self.nextenemy.name + hitdesc + self.mainchar.name +
                          " for " + str(damage) + " damage")
                    if self.nextenemy.hp <= 0 and self.mainchar.hp > 0:
                        victorious = True
                        break
                    damage = self.attack_attempt(self.mainchar, self.nextenemy)
                    hitdesc = " strikes "
                    if damage == 0:
                        hitdesc = " misses "
                    print(self.mainchar.name + hitdesc + self.nextenemy.name +
                          " for " + str(damage) + " damage")
            elif choice == "2":  #choice 2 flee
                if maininit > foeinit:
                    #successful flee
                    print("You flee the battle \n")
                    break
                else:
                    #failed fleeing
                    print("You failed to flee the battle \n")
            #special attack
            else:
                #invalid choice
                print("Not a valid option...it is time to do battle \n")
            #if battle not over show enemy stats  based on skill check
            if self.mainchar.skill_check() >= self.nextenemy.skill_check():
                print(self.nextenemy.name + " has " + str(self.nextenemy.hp) +
                      " hit points \n")
            else:
                print(self.nextenemy.name +
                      " is concealing the extent of his injuries... \n")
            #if battle not over show character vital prompt
            print(self.mainchar.get_prompt())

        if self.nextenemy.hp <= 0 and self.mainchar.hp > 0:
            #catch all to make sure victory conditions are properly met
            victorious = True

        if victorious == True:
            #if battle over,(win) - give exp and reward if enemy has something
            self.mainchar.experience += self.nextenemy.experience
            print("Victory. You earn " + str(self.nextenemy.experience) +
                  " exp\n")
            self.victories += 1
            if len(self.nextenemy.inventory) > 0:
                isnew = True
                newitem = self.nextenemy.inventory.pop()
                for item in self.mainchar.inventory:
                    if item.name == newitem.name:
                        isnew = False
                if isnew:
                    self.mainchar.inventory.append(newitem)
                    print("New item added to inventory!! " +
                          newitem.get_description())
                self.state = self.STATES[1]
            print(self.mainchar.get_prompt())
        elif self.mainchar.hp <= 0:
            #if battle over,(loss) - game over, go to start up state
            print("You lose. You will be remembered.. \n")
            self.gameover = True

            self.state = self.STATES[0]
        else:  #if fled
            self.state = self.STATES[1]
            print(self.mainchar.get_prompt())

    def generate_enemy(self):
        """Creates Enemy"""
        types = ("Spider", "Snake", "Wolf", "Bear", "Rhino", "Panther", "Lion",
                 "Griffin", "Dragon", "Legendary Hydra")

        die = Dice(self.round)
        enemynum = die.roll()
        self.nextenemy = Enemy(types[enemynum - 1], enemynum)
        for key, value in self.nextenemy.stats.items():
            self.nextenemy.stats[key] = enemynum
        #compensate for default armor
        self.nextenemy.stats[traits[0]] += 1
        self.nextenemy.level = enemynum
        self.nextenemy.experience = enemynum
        die = Dice(10)
        if die.roll() == 10:
            if die.roll() > 5:
                traitdie = Dice(4)
                self.nextenemy.inventory.append(
                    Weapon(enemynum, traits[traitdie.roll() - 1]))
            else:
                self.nextenemy.inventory.append(Armor(enemynum))

        hpmod = 5
        if enemynum > 4:
            hpmod = 10
        elif enemynum > 9:
            hpmod = 20  #end game bonus to enemy health
            self.nextenemy.stats[
                "Strength"] += 5  #end game damage output increased
        self.nextenemy.hp = hpmod * self.nextenemy.stats["Constitution"]

    def attack_attempt(self, attacker, defender):
        """Calculates hit success and applies damage if needed"""
        if attacker.to_hit() >= defender.calc_defense():
            armorvalue = 0
            if defender.equipment["Armor"] != 0:
                armorvalue = defender.equipment["Armor"].defense
            damage = attacker.calc_damage() - armorvalue
            if damage > 0:
                defender.hp -= damage
            return damage
        else:
            return 0
示例#51
0
# Contrib Modules - stuff we had to install
#Core Modules - stuff thats already part of python, that we need
import os #operating system 
from random import randint #get specifically the randint method from the random class

# Custom modules - python modules we made!
#from FILENAME.py import CLASS/member
#basics of inheritance in Python
from character import Character
from Goblin import Goblin 

heroName = raw_input("What is thy name, brace adventurer? ")
theHero = Character(heroName, 10, 5)
# print theHero.name

goblin = Goblin()
# print goblin.health

while goblin.is_alive() and theHero.is_alive():
	print "You have %d health and %d power." % (theHero.health, theHero.power)
	print "%s has %d health and %d power" % (goblin.name, goblin.health, goblin.power)
	user_input = raw_input()
	if user_input == "1"
		goblin.take_damage(theHero.power)
		theHero.take_damage(goblin.power)
示例#52
0
import pygame
import os
from world import World
from character import Character
from weapon import Weapons
from data import SCREEN_WIDTH, SCREEN_HEIGHT, FPS, BULLET_VEL, BLOCKS, BLOCKS_POS
import csv_handler

pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH + 100, SCREEN_HEIGHT))
pygame.display.set_caption('Factory Trick-Shot Level Editor')
clock = pygame.time.Clock()
world = World(screen)
character = Character(bottomleftpos=(200, 200))
weapons = Weapons()
delay = 20


def drawTiles():
    start_x = 1200
    block = 1
    for i in range(12):
        for j in range(2):
            try:
                if block <= 2:
                    screen.blit(BLOCKS[block], (start_x + j * 50, i * 50))
                elif block == 10 or block == 7:
                    screen.blit(BLOCKS[block], (start_x + j * 50, i * 50))
                elif block == 8:
                    screen.blit(BLOCKS[block][0],
                                (start_x + j * 50, i * 50 - 50))
示例#53
0
solids.append(plank)

movingPlank = MovingSolidX(color_palette.BROWN, startX, startY, plankLength,
                           plankThickness, xEnds, False)
solids.append(movingPlank)

goalWidth = 100
goalHeight = 150
goal = Goal(
    color_palette.WHITE,
    [(correctionTerm2 + plankThickness + 7 * plankLength + plankThickness * 2 +
      plankThickness * 3 + plankLength,
      waterLevel + plankThickness * 7 + goalHeight, goalWidth, goalHeight)])
solids.append(goal)

secretPlatform = Solid(
    color_palette.BROWN,
    [(STAGE_WIDTH - secretGapWidth, 110, secretGapWidth, 50)])
solids.append(secretPlatform)
solids.append(water)

startX = plankThickness + plankLength / 2
startY = int(HEIGHT / 2)
character = Character(screen, startX, startY, (255, 215, 0), 50)
isPeriodic = False
stage = Stage(screen, character, isPeriodic, STAGE_WIDTH, STAGE_HEIGHT, solids)

if __name__ == '__main__':
    stage.DrawStage(1200)
    input('press anything to exit')
 def __init__(self, name, tower, **kargs):
     self._tower = tower
     for key, value in kargs.items():
         exec('self._' + key + '=' + value)
     Character.__init__(self, self._i, self._j, name, tower.current)
示例#55
0
def main(genomes, config):
    running = True
    platforms = []
    bullets = []
    enemies = []

    platforms.append(Platform(0, 300, PLATFORM_WIDTH, PLATFORM_HEIGHT))
    platforms.append(Platform(300, 300, PLATFORM_WIDTH, PLATFORM_HEIGHT))
    platforms.append(Platform(600, 300, PLATFORM_WIDTH, PLATFORM_HEIGHT))
    #platforms.append(Platform(800, 300, PLATFORM_WIDTH, PLATFORM_HEIGHT))

    nets = []
    ge = []
    characters = []
    bullet_counter = 0

    for g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g[1], config)
        nets.append(net)
        char = Character(platforms, bullets)
        characters.append(char)
        g[1].fitness = 0
        ge.append(g[1])

    #loop vars
    counter = 0
    last_platform_height = 300
    new_platform_mod = 15
    score = 0
    clock = pygame.time.Clock()

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()

        if not len(characters):
            running = False
            break

        tick = clock.tick(30)
        for i in range(len(platforms)):
            try:
                if platforms[i].move(tick):
                    platforms.remove(platforms[i])
                    i -= 1
            except:
                pass
        for enemy in enemies:
            enemy.move(tick)
            if bullet_counter % 100 == 0:
                bullets.append(enemy.shoot())
        SCREEN.fill(sky)
        SCREEN.blit(further_background, (0, Y - 520))
        SCREEN.blit(background, (0, Y - 460))
        SCREEN.blit(ground_tiles, (0, Y - 400))

        #generate new platforms
        counter += 1
        bullet_counter += 1
        if (counter % new_platform_mod == 0):
            plat = GENERATOR.add_platform(last_platform_height)
            last_platform_height = plat.rect.y
            platforms.append(plat)
            new_platform_mod = random.randint(50, 100)
            counter = 0
            score += 1
            print(score)
            if random.randint(1, 3) == 1:
                print('new enemy')
                enemies.append(Enemy(plat.rect.x + 100, plat.rect.y - 50))

        #blit platforms
        for o in platforms:
            SCREEN.blit(o.image, o.rect)
        for enemy in enemies:
            SCREEN.blit(enemy.image, enemy.rect)
        for bullet in bullets:
            SCREEN.blit(bullet.image, bullet.rect)

        for i in range(len(bullets)):
            try:
                bullets[i].move()
                if bullets[i].rect.x > WIDTH or bullets[i].rect.x < 0:
                    bullets.remove(bullets[i])
                    i -= 1
            except:
                pass
        for enemy in enemies:
            enemy.move(tick)
            if bullet_counter % 100 == 0:
                bullets.append(enemy.shoot())

        for i, character in enumerate(characters):
            #ge[i].fitness += character.rect.x / 200
            p_index = 0
            for p in platforms:
                if character.rect.x > p.rect.left:
                    p_index += 1
                    #ge[i].fitness += 1
                else:
                    break

            ge[i].fitness += .01

            b_index = 0
            for b in bullets:
                if character.rect.x > b.rect.left:
                    b_index += 1
                    #ge[i].fitness += 1
                else:
                    break

            e_index = 0
            for e in enemies:
                if character.rect.x > e.rect.left:
                    e_index += 1
                    #ge[i].fitness += 1
                else:
                    break

            try:
                output = nets[i].activate(
                    (character.rect.x, character.rect.y,
                     platforms[p_index - 1].rect.left,
                     platforms[p_index - 1].rect.right, platforms[p_index -
                                                                  1].rect.y,
                     platforms[p_index].rect.left,
                     platforms[p_index].rect.right, platforms[p_index].rect.y,
                     bullets[b_index].rect.x, bullets[b_index].rect.x,
                     enemies[e_index].rect.x, enemies[e_index].rect.y,
                     875 - character.rect.x))
            except:
                try:
                    output = nets[i].activate(
                        (character.rect.x, character.rect.y,
                         platforms[p_index - 2].rect.left,
                         platforms[p_index - 2].rect.right,
                         platforms[p_index - 2].rect.y, platforms[p_index -
                                                                  1].rect.left,
                         platforms[p_index - 1].rect.right,
                         platforms[p_index - 1].rect.y, 0, 0,
                         enemies[e_index].rect.x, enemies[e_index].rect.y,
                         875 - character.rect.x))
                except:
                    output = nets[i].activate(
                        (character.rect.x, character.rect.y,
                         platforms[p_index - 2].rect.left,
                         platforms[p_index - 2].rect.right,
                         platforms[p_index - 2].rect.y,
                         platforms[p_index - 1].rect.left,
                         platforms[p_index - 1].rect.right,
                         platforms[p_index - 1].rect.y, 0, 0, 0, 0,
                         875 - character.rect.x))

            soft = neat.math_util.softmax(output)
            class_output = np.argmax(((soft / np.max(soft)) == 1).astype(int))

            #print(class_output)
            if not class_output:
                character.left_bool = False
                character.right_bool = True
                pass
            elif class_output == 1:
                character.move(10, 0)
                character.left_bool = False
                character.right_bool = True
                character.chillCount = 0
            elif class_output == 2:
                character.move(-10, 0)
                character.left_bool = True
                character.right_bool = False
                character.chillCount = 0
            else:
                if not character.jumping and character.can_jump:
                    character.jumping = True
                    character.chillCount = 0
                else:
                    character.left_bool = False
                    character.right_bool = False

            ge[i].fitness += character.update(tick)

            if character.rect.y > HEIGHT:
                ge[i].fitness -= 1
                char = characters.pop(i)
                nets.pop(i)
                ge.pop(i)
                continue

            if character.rect.x > 825:
                ge[i].fitness -= .1
                character.rect.x = 875 - character.width

            if character.rect.x == 0:
                ge[i].fitness -= 5
                char = characters.pop(i)
                nets.pop(i)
                ge.pop(i)
                continue
            if character.hit:
                ge[i].fitness -= 10
                char = characters.pop(i)
                nets.pop(i)
                ge.pop(i)
                continue

            character.redrawGameWindow()
            SCREEN.blit(character.image, character.rect)

        pygame.display.flip()
示例#56
0
def characterMenuHandler(gamespace, characterCreator, eventPosition):
    displaySurf = gamespace.viewscreen.displaySurf
    characterSpace = gamespace.characterSpace

    pressedButton = characterCreator.buttonList[
        characterCreator.getButtonCollision(eventPosition)].name

    global characterSize, newCharacterName

    # If 'Exit' is pressed close the menu and reset everything
    if pressedButton == 'Exit':
        return True

    #Size Handling
    #If Size is Increased or Decreased then change the size image and Draw it
    elif pressedButton == 'SizeDecrease' and characterSize > 1:
        characterSize -= 1
        characterCreator.imageList["Size"].update(characterSize, True)
    elif pressedButton == 'SizeIncrease' and characterSize < 4:
        characterSize += 1
        characterCreator.imageList["Size"].update(characterSize, True)

    #'CharacterName' is pressed
    elif pressedButton == 'CharacterName':
        result = characterCreator.buttonList['CharacterName'].getInput()
        if result != None:  #handles mouse clicks from inside getInput loop
            pygame.event.post(result)

    #'NewCharacter' is pressed
    #Create new character, add them to the character space and then exit
    elif pressedButton == "NewCharacter":
        characterName = characterCreator.buttonList['CharacterName'].text
        if len(characterName) > 0 and characterSpace.nameIsNotTaken(
                characterName):
            newChar = Character(
                characterName, displaySurf,
                toDisplayCoordinates(
                    characterCreator.buttonList['CharacterIcon'].rect.topleft,
                    characterCreator.rect.topleft), gamespace.characterColor,
                characterSize)
            newCharacterName = characterName
            characterSpace.addToSpace(newChar)
            characterCreator.buttonList['CharacterIcon'].update(
                newChar.images[1])
            characterCreator.buttonList['CharacterName'].reset()
            characterCreator.redraw()

    elif (pressedButton == "CharacterIcon" and newCharacterName != None
          and gamespace.zoomLevel == 1):
        pygame.draw.rect(characterCreator.surface, characterCreator.color,
                         characterCreator.buttonList['CharacterIcon'].rect)
        characterCreator.redraw()

        if characterMovement.moveCharacter(newCharacterName, eventPosition,
                                           gamespace, True):
            newCharacterName = None

        #If the character is not added to the board we need to keep the icon where it was
        #With the draw-rect above, we did not wipe out the character icon in the button,
        #so we just re-blit the button and the icon returns.
        else:
            characterCreator.reblit()
            characterCreator.redraw()

    return False
示例#57
0
 def insert(self, character):
     if not hasattr(character, 'character'):
         character = Character(character)
     self.characters.insert(self.cursor.position, character)
     self.cursor.forward()
示例#58
0
 def test_map_description_position_3_3(self, mock_stdout):
     test_character = Character('Jihyo', 10, [3, 3], 0)
     dialogue_and_scripts.map_description(test_character)
     expected_stdout = "You look around the house, to the south is the master bedroom."
     self.assertIn(expected_stdout, mock_stdout.getvalue())
示例#59
0
 def test_map_description_position_3_2(self, mock_stdout):
     test_character = Character('Jihyo', 10, [3, 2], 0)
     dialogue_and_scripts.map_description(test_character)
     expected_stdout = "You are between the living room and the kitchen. The living room is to your north"
     " and to the south is the kitchen."
     self.assertIn(expected_stdout, mock_stdout.getvalue())
示例#60
0
 def test_map_description_position_4_1(self, mock_stdout):
     test_character = Character('Jihyo', 10, [4, 1], 0)
     dialogue_and_scripts.map_description(test_character)
     expected_stdout = "You enter the kitchen and opened one of the cabinets, "
     "considering to choose another weapon.\nYou decided to stick with the kitchen knife."
     self.assertIn(expected_stdout, mock_stdout.getvalue())