Пример #1
0
 def dropItem(self):
     rand = random.randint(0, 1)
     if rand == 0:
         weapon = Weapon(random.choice(list(WeaponType)), self.getX(),
                         self.getY())
         print(weapon)
         return weapon
Пример #2
0
    def get_weapon(weapon_id):
        conn = None
        try:
            conn = psycopg2.connect(host="localhost",
                                    database="roleplay",
                                    user="******",
                                    password="******")
            cur = conn.cursor()
            sql = 'SELECT weapon.id, weapon.name, weapon.rang_id, weapon.power, player_has_weapon.id FROM weapon ' \
                  'JOIN player_has_weapon ON weapon.id = player_has_weapon.weapon_id ' \
                  'WHERE player_has_weapon.id = %s'
            cur.execute(sql, (weapon_id, ))
            if cur.rowcount == 0:
                return None
            record = cur.fetchone()
            weapon = Weapon(name=record[1],
                            rang=record[2],
                            power=record[3],
                            item_id=record[4])
            cur.close()
            return weapon

        except (Exception, psycopg2.DatabaseError) as error:
            print(error)

        finally:
            if conn is not None:
                conn.close()
Пример #3
0
 def __init__(self, mapFile, enemies=[Enemy(10, 10, 1), Enemy(11, 10, 1)]):
     self.player = Player()
     self.enemies = enemies
     self.prevLoc = (self.player.getX(), self.player.getY())
     self.map = [[]]
     self.items = [Weapon(WeaponType.SWORD, 3, 3)]
     with open(mapFile, "r") as mapTxt:
         for line in mapTxt.readlines():
             self.map.append(self.split(line.rstrip()))
         self.updatePlayer()
Пример #4
0
 def __init__(self, x=2, y=33, health=10, level=1, xp=0):
     super(Player, self).__init__(False, True, Location(x, y), level)
     self.health = health
     self.inventory = [Weapon()]
     self.direction = Direction.UP
     self.selectedWeapon = self.inventory[0]
     self.xp = xp
     self.levelxp = []
     for val in range(1, 11):
         self.levelxp.append(2**val)
     self.updateDamage()
Пример #5
0
 def get_inventory(player_id):
     conn = None
     try:
         conn = psycopg2.connect(host="localhost",
                                 database="roleplay",
                                 user="******",
                                 password="******")
         cur = conn.cursor()
         sql = 'SELECT weapon.id, weapon.name, weapon.rang_id, weapon.power, player_has_weapon.id FROM ' \
               'player_has_weapon JOIN weapon ON player_has_weapon.weapon_id = weapon.id ' \
               'where player_has_weapon.player_id = %s '
         cur.execute(sql, (player_id, ))
         records = cur.fetchall()
         items = []
         for record in records:
             item = Weapon(name=record[1],
                           rang=record[2],
                           power=record[3],
                           item_id=record[4])
             items.append(item)
         sql = 'SELECT armor.id, armor.armor_type, armor.name, armor.rang_id, armor.defense, player_has_armor.id FROM ' \
               'player_has_armor JOIN armor ON player_has_armor.armor_id = armor.id ' \
               'where player_has_armor.player_id = %s '
         cur.execute(sql, (player_id, ))
         records = cur.fetchall()
         for record in records:
             item = Armor.armor_from_db(armor_type_name=record[1],
                                        name=record[2],
                                        rang=record[3],
                                        defense=record[4],
                                        item_id=record[5])
             items.append(item)
         sql = 'SELECT potion.id, potion.name, rang.meaning, potion.effect_type_id, ' \
               ' potion_effect.meaning, ' \
               'potion.value FROM potion ' \
               'JOIN player_has_potion ON potion.id = player_has_potion.potion_id ' \
               'JOIN potion_effect ON potion_effect.id = potion.effect_type_id ' \
               'JOIN rang ON potion.rang_id = rang.id ' \
               'WHERE player_id = %s AND player_has_potion.used = false'
         cur.execute(sql, (player_id, ))
         records = cur.fetchall()
         for record in records:
             item = Potion.potion_from_db(name=record[1],
                                          rang=record[2],
                                          effect_name=record[4],
                                          effect_value=record[5])
             items.append(item)
         cur.close()
         return Inventory(items)
     except (Exception, psycopg2.DatabaseError) as error:
         print(error)
     finally:
         if conn is not None:
             conn.close()
Пример #6
0
    def dungeon_restart(self, reset, name="Bob"):
        """
        @summary Regenere un dongeon en remettant toutes nos variables necessaire a 0
        @param reset: (si True on remet le personnage a nu et le donjon a 1)
        @param name: nom du personnage, et de la sauvegarde
        """
        if reset:
            self.character = Character(name)
            self.actual_level = 0
            # === TEST ===
            self.character.inventory.weapon = Weapon("weapon")
            self.character.inventory.append(Armor())
            self.character.inventory.append(Weapon())
            self.character.inventory.append(SpellBook())
            # === FIN  ===time.sleep(2

        self.map = MapDungeon(15)
        self.actual_level += 1
        self.character.set_pos(0, 0)
        self.map_surf = self.map.disp_map(player=self.character)
        self.character.inventory.append(Consumables())
Пример #7
0
 def spawnItems(self):
     #Spawn items in the case that you jsut killed a zombie!
     if self.monsterSlayer == True:
         oboy = random.randint(1, 30)
         if oboy > 10:
             rf = Snacks("Rotten Flesh",
                         "It's a little slimey. Not good for eating.", .5,
                         -8)
             rf.putInRoom(self.location)
         else:
             c = Snacks("Candy",
                        "You really should try to eat healthier...", .5, 8)
             c.putInRoom(self.location)
             if oboy < 5:
                 rf = Snacks("Rotten Flesh",
                             "It's a little slimey. Not good for eating.",
                             .5, -8)
                 rf.putInRoom(self.location)
                 w = Weapon("Shotgun", "Pow pow!", 4, 3.25)
                 w.putInRoom(self.location)
         self.monsterSlayer = False
Пример #8
0
    def __init__(self):
        self.health = 100

        # Object Definitions
        self.inventory = Inventory(capacity=100)
        self.equippedWeapon = Weapon(
            damage=5,
            durability=1,
            name="Shiv",
            description="A toothbrush with a razor blade attached.",
            size=2)
        self.currentRoom = None
Пример #9
0
room['hall'].e_to = room['larder']
room['hall'].s_to = room['fountain']
room['hall'].w_to = room['indev']
room['hall'].n_to = room['indev']
room['larder'].w_to = room['hall']

# Populate rooms

room['outside'].items.append(
    LightSource('Lamp', 'A small metal lamp with glass windows'))
room['outside'].items.append(
    Item('Rope', 'Twisted hemp forms a long, flexible rope'))
room['treasure'].items.append(
    Item('Grappling Hook', 'A metal hook, with three prongs'))
room['armory'].items.append(
    Weapon('Rusty Sword', 'A metal sword, rusty from long neglect', 6,
           "Slashing"))
room['larder'].items.append(
    Item('Tasty Cake', 'A tasty old cake. Fills you up!'))

#
# Main
#

# Make a new player object that is currently in the 'outside' room.

from player import Player

player_1 = Player(room["outside"])

last_item = None
Пример #10
0
class Player(Mob):
    fist = Weapon(1, "hand", "empty fist", "", 0, 1)

    def __init__(self, name, current_room, health, experience=0, gold=0):
        super().__init__(name, health, experience)
        self.current_room = current_room
        self.gold = gold
        self.inventory = []
        self.leftHandItem = self.fist
        self.rightHandItem = self.fist

    def attack_damage(self):
        return self.leftHandItem.attack + self.rightHandItem.attack

    def has_light(self):
        return isinstance(self.leftHandItem, LightSource) or isinstance(
            self.rightHandItem, LightSource)

    def equipItem(self, item):
        hand = input(
            "Which hand would you like to equip this item to? ").lower()

        if isinstance(item, Weapon) or isinstance(item, LightSource):

            #store the current attack value before equipping a new item (used in output)
            old_attack = self.attack_damage()

            had_light = self.has_light()
            if hand == "l" or hand == "r":
                #remove the item from the current room or inventory
                if item in self.current_room.items:
                    self.current_room.items.remove(item)
                elif item in self.inventory:
                    self.inventory.remove(item)
                #equip it
                if hand == "l" or hand == "left":
                    if self.leftHandItem != self.fist:
                        self.inventory.append(self.leftHandItem)
                        self.leftHandItem.to_inventory()
                    self.leftHandItem = item
                elif hand == "r" or hand == "right":
                    if self.rightHandItem != self.fist:
                        self.inventory.append(self.rightHandItem)
                        self.rightHandItem.to_inventory()
                    self.rightHandItem = item
            else:
                sys_print(
                    f"`{hand}` isn't a hand you can equip to. Please choose `l` for left or `r` for right"
                )
                return

        #Inner-Mark: Output

        #Attack value changed:
            if old_attack != self.attack_damage():
                sys_print(
                    f"your attack was {old_attack} and after equipping {item.name} it is now {self.attack_damage()}"
                )

            #light changed:
            if had_light == False and self.has_light() == True:
                sys_print("You can see again!")
        else:
            sys_print(
                f"You can only equip weapons and light sources at this time. {item} isn't a weapon or light source."
            )
            return

        if hand == "l" or hand == "left":
            hand_description = "Left Hand"
        elif hand == "r" or hand == "right":
            hand_description = "Right Hand"

        #empty line
        print()

        sys_print(f"You've equipped {item} to your {hand_description}")

    def __str__(self):
        return f"{self.name} has {self.health} health, {self.gold} gold, and {self.experience} experience"

    def get_from_inventory(self, item):
        for i in self.inventory:
            if item == i.name:
                return i
        if item == self.leftHandItem.name:
            return self.leftHandItem
        elif item == self.rightHandItem.name:
            return self.rightHandItem
        sys_print(f"Item not found: {item}")

    def take(self, item_name):
        item = self.find(item_name)
        if isinstance(item, Item):
            if item.name == "golden_sword" and not hasattr(self, 'arthur'):
                sys_print(
                    "Did you think you could just take that? It's obviously buried to the hilt!"
                )
                return

            if isinstance(item, LightSource) or isinstance(item, Weapon):
                self.equipItem(item)
            elif item.id != 1:
                item.to_inventory()
                self.inventory.append(item)
            else:
                sys_print(
                    f"You aren't able to equip {item}. Try inspecting it")

    def pull(self, item_name):
        item = self.find(item_name)
        if isinstance(item, Item):
            if item.name == "golden_sword":
                self.equipItem(item)
            else:
                print(f"""
You pull {item_name} with all your might, but nothing happens.
Did you mean to pull your finger?
                """)
        elif item_name == "finger":
            sys_print("You're disgusting!")
        else:
            sys_print("Invalid item to pull. What were you thinking?")

    def letter_to_int(self, letter):
        alphabet = list('abcdefghijklmnopqrstuvwxyz')
        if letter in alphabet:
            return alphabet.index(letter)

    def int_to_letter(self, index):
        alphabet = list('abcdefghijklmnopqrstuvwxyz')
        if len(alphabet) >= index + 1:
            return alphabet[index]

    def list_inventory(self):
        if self.leftHandItem.name == "hand":
            print(f"Left Hand: fist")
        else:
            print(f"Left Hand: {self.leftHandItem}")

        if self.rightHandItem.name == "hand":
            print(f"Right Hand: fist")
        else:
            print(f"Right Hand: {self.rightHandItem}")

        for item in self.inventory:
            #output
            print(f"{item.name}")
            #increment to the next byte (this will convert to the next character)

        equippables = [
            i.name for i in self.inventory
            if isinstance(i, Weapon) or isinstance(i, LightSource)
        ]

        if len(equippables) > 0:
            sys_print("Items you can equip:")
            #empty line
            print()

            #decode to string and make uppercase
            letter_i = self.letter_to_int('a')
            for item in equippables:
                letter_s = self.int_to_letter(letter_i)
                upper_str = letter_s.upper()

                print(f"{upper_str}: {item}")
                letter_i += 1

            loot = input("select a letter to loot an item: ").lower()
            index = self.letter_to_int(loot)

            equip_item = self.get_from_inventory(equippables[index])

            if len(equippables) >= index + 1:
                self.equipItem(equip_item)

    def find(self, item_name):
        for i in self.current_room.items:
            if item_name == i.name:
                return i
        return item_name

    def dropItem(self, item_name):
        old_attack = self.attack_damage()
        had_light = self.has_light()

        this_item = self.get_from_inventory(item_name)
        if this_item:
            if this_item != self.fist:
                if this_item in self.inventory:
                    self.inventory.remove(this_item)
                elif this_item == self.leftHandItem:
                    self.leftHandItem = self.fist
                elif this_item == self.rightHandItem:
                    self.rightHandItem = self.fist
                self.current_room.items.append(this_item)
                this_item.to_floor()

                #Attack value changed:
                if old_attack != self.attack_damage():
                    sys_print(
                        f"your attack was {old_attack} and after dropping {this_item.name} it is now {self.attack_damage()}"
                    )

                #light changed:
                if had_light == True and self.has_light() == False:
                    sys_print("You can't see anything!")
            else:
                if hasattr(self, "hand_drop"):
                    hand = input(f"Which hand would you like to drop? ")
                    print("""
                    You pull and pull with all your might, finally loosening
                    the connection between your wrist and forearm.
                    """)
                    sys_print(
                        f"You drop your {hand} hand for {self.health} damage")
                    sys_print(f"{self.name} died of a not listening overdose.")
                    exit(0)
                else:
                    sys_print(
                        "Please, don't try to drop your hands. That would be fatal."
                    )
                    self.hand_drop = True

    def fight(self, monster_name):
        monster = self.find_monster(monster_name)

        if isinstance(monster, Monster):
            sys_print(
                f"{self.name} is fighting {monster.name}. {self.name} has {self.health} health and {monster} has {monster.health} health"
            )
            while monster.health > 0 and self.health > 0:
                if monster.health > 0:
                    self.health -= monster.attack
                    sys_print(
                        f"{monster.name} hits {self.name} for {monster.attack} damage. {self.name} has {self.health} health remaining"
                    )

                if self.health > 0:
                    damage = self.attack_damage()
                    if self.has_light():
                        sys_print(
                            f"{self.name} hits {monster.name} for {damage} damage. {monster.name} has {monster.health} health remaining"
                        )
                        monster.health -= damage
                    else:
                        self.health -= damage
                        print(
                            f"You try your best to hit {monster.name} but you can't see anything!"
                        )
                        sys_print(
                            f"You hit yourself for {damage} damage! You have {self.health} health remaining"
                        )

            if monster.health <= 0:
                self.current_room.monsters.remove(monster)
                print(f"{monster.name} died!")
            else:
                print(
                    f"{self.name} met their demise by {monster.name}. Thanks for playing!"
                )
                exit(0)
        else:
            sys_print(
                f"If you really thought you could fight a {monster}, you probably also believe in \"the rock\"!"
            )

    def find_monster(self, monster_name):
        for monster in self.current_room.monsters:
            if monster.name == monster_name:
                return monster
            else:
                return monster_name
Пример #11
0
from equipment import Equipment
from inventory import Inventory
from item import Weapon, ArmorType, Armor, Potion, PotionEffect, AccessoriesEffectType, PotionEffectType
from player import *
from skill import *
from fighter import *
from move import *

armor = Armor('shield', 'F', 100, ArmorType.shield.value)
equipment1 = Equipment(shield=armor)
equipment2 = Equipment(weapon=Weapon('sword', 'F', 120))
player1 = Player(10, 'Ivan', 63, 63, 20, 15, 40, 40, 10, [
    ActiveSkill('knife', 'F', 'first skill', 5,
                ActiveSkillEffect(15, ActiveSkillEffectType.damage.value))
], [
    PassiveSkill(
        'power increase', 'F', 'first passive skill',
        PassiveSkillEffect(5, PassiveSkillEffectType.increase_power.value))
], equipment1, Inventory([]), [
    Potion('power buff', 'F', PotionEffect(500, PotionEffectType.power.value))
])
player2 = Player(12, 'Igor', 60, 60, 21, 16, 45, 45, 11, [
    ActiveSkill('knife', 'F', 'first skill', 5,
                ActiveSkillEffect(15, ActiveSkillEffectType.damage.value))
], [
    PassiveSkill(
        'defense increase', 'F', 'increases your defense',
        PassiveSkillEffect(6, PassiveSkillEffectType.increase_defense.value))
], equipment2, Inventory([]), [
    Potion('defense buff', 'F',
           PotionEffect(600, PotionEffectType.defense.value))
Пример #12
0
 def starting_weapon():
     return Weapon()
Пример #13
0
        'Near half-hundred policemen point their guns on you. You have no way to run.\n\
[police captain]: Do you think that this is just a game!? Than your game is over!'
    ))
bully1.set_description(
    'A tall, thin man with a cigarret in his mouth and a bottle of beer in hand.\
\nHP:{}\nDamage:{}'.format(bully1.health, bully1.attack))
bully2.set_description(
    'About 6 feet tall... lots of jailhouse tats.\nHP:{}\nDamage:{}'.format(
        bully2.health, bully2.attack))
bully3.set_description(
    'Drunk student with the metal knuckles and without front teeth.\nHP:{}\n\
Damage:{}'.format(bully3.health, bully3.attack))
policeman.set_description('Young stinking pig.\nHP:{}\nDamage:{}'.format(
    policeman.health, policeman.attack))

weapon1 = Weapon('TEC-9', 40)
weapon2 = Weapon('Shotgun', 80)
sig = Item('Cigarette')
beer = Item('Opillia')
ammo = Item('Ammo')

mate.set_gift(ammo)
w***e.set_gift(w***e)
mate.set_answer(
    sig, 'You lit a cigar. Slowly smoking, you gazed down at your friend.\n\
[Matthew]: You will need this.')
w***e.set_answer(
    beer, 'You get out beer.\n[w***e]: Let`S do tHiS in anOtheR plAce.')
boss.set_answer(
    w***e, 'You put the girl in front of you.\n[police captain]: Daughter!?\n\
[w***e]: Dad! Help me!\nYou slap a w***e.\n[police captain]: Don`t you dare touching her!\n\
Пример #14
0
class Room:
    def __init__(self, door, info_text):
        self.exit = door
        self.items = []
        self.creatures = []
        self.info_text = info_text

    def inspect_items(self):
        return ', '.join(x.name for x in self.items)

    def inspect_creatures(self):
        return ', '.join(['a ' + x.species for x in self.creatures if not x.is_player])

    def describe(self):
        return 'You are standing in {}. {}.'.format(self.info_text, self.exit)


if __name__ == '__main__':
    start = Room('a door', 'a dark room')
    player = Creature('Li', 'human')
    monster = Creature('Klarg', 'hugbear')
    p = Potion()
    w = Weapon()
    start.creatures.append(player)
    start.creatures.append(monster)
    start.items.append(p)
    start.items.append(w)
    print(start.describe())
    print(start.inspect_creatures())
    print(start.inspect_items())
Пример #15
0
 def __init__(self):
     self.items = []
     self.main_hand = Weapon(pygame.image.load("Image_Assets\\meter_1.png"),
                             0, 0, 0)
     self.off_hand = Weapon(pygame.image.load("Image_Assets\\meter_1.png"),
                            0, 0, 0)
Пример #16
0
from item import Item, Weapon, Treasure, Armor, Food, LightSource

excaliber = Weapon(
    "Excaliber",
    "The Lady of the Lake, her arm clad in the purest shimmering samite, held aloft Excalibur from the bosom of the water signifying by Divine Providence that you, Arthur, were to carry Excalibur.",
    10)
grenade = Weapon(
    "Holy Hand Grenade of Antioch",
    "And Saint Attila raised the hand grenade up on high, saying, ‘O Lord, bless this thy hand grenade, that with it thou mayst blow thine enemies to tiny bits, in thy mercy.’ And the Lord did grin. And the people did feast upon the lambs and sloths, and carp and anchovies, and orangutans and breakfast cereals, and fruit-bats. And the Lord spake, saying, ‘First shalt thou take out the Holy Pin. Then shalt thou count to three, no more, no less. Three shall be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, neither count thou two, excepting that thou then proceed to three. Five is right out. Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards thy foe, who, being naughty in my sight, shall snuff it.'  Amen.",
    50)
rock = Item(
    "Rock",
    "The solid mineral material forming part of the surface of the earth and other similar planets, exposed on the surface or underlying the soil or oceans."
)
stick = Item("Stick",
             "A thin piece of wood that has fallen or been cut from a tree.")
coin = Treasure("Coin", "A single coin.", 1)
duck = Treasure(
    'Duck', "If something weighs as much as a duck, it must be made of wood.",
    10)
ninePence = Treasure("Pence", "Nine pence.  Enough to pay a mortician.", 9)
shrubbery = Treasure("Shrubbery", "It's...  a shrubbery!", 10)
elderberries = Treasure(
    "Elderberries",
    "A very... *cough* manly... *cough* perfume...  *snicker snicker*", 10)
deed = Treasure("Deed", "A deed for HUGE...  tracts of land!", 10)
hamster = Item("Hamster", "This is your Mother.  Do not lose her.")
coconuts = Item("Coconuts", "A mighty steed!")
shield = Armor("Shield", "A worn, wooden shield.", 10)
spam1 = Food("Spam", "I would like some Spam.", 1)
spam2 = Food("SpamSpam", "I would like some Spam and Spam.", 2)
Пример #17
0
# Add Items to Rooms

room['outside'].add_item(Item('leaf', 'It is a dazzling emerald color.'))
room['outside'].add_item(
    LightSource(
        'lamp',
        'The light from the lamp brightens your spirit in this dark world.'))
room['foyer'].add_item(
    Item('candle', 'It is currently out. The wax is warm to the touch.'))
room['overlook'].add_item(
    Item('rock', 'It is a round brown rock. Nothing special.'))
room['treasure'].add_item(
    Item('gold', 'The golden color inspires visions of wealth.'))
room['treasure'].add_item(
    Item('ruby', 'It is a starling red gem. It might be worth something.'))
room['foyer'].add_item(Weapon('sword', 'The edge hungers for blood.', 5))

# Add Monsters

goblin = Monster(
    'Goblin',
    'A short green deadly creature. Eyes filled with hunger, it stalks toward you',
    room['overlook'], 10, 2, 'Fury Claws')

#
# Main
#

# Make a new player object that is currently in the 'outside' room.
player = Player(input('Enter Player Name: '), room['outside'])
print(
Пример #18
0
from os import system, name
import random

from room import Room
from item import Item
from item import Weapon
from item import LightSource
from item import Food
from player import Player

validDirections = ["n", "s", "e", "w"]

items = {
    'sword':
    Weapon("Sword", "A rusty but useful sword", 15),
    'refined_sword':
    Weapon(
        "Sharpened Sword",
        "A big, brutish sword that has a red tint reflecting off the blade",
        50),
    'torch':
    LightSource("Torch", "A torch that has been lit recently...", 20),
    'bread':
    Food("Bread", "A half eaten loaf", 2, 20),
}

room = {
    'outside':
    Room("Outside Cave Entrance", "North of you, the cave mount beckons",
         None),
    'foyer':
Пример #19
0
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']

# Initialize items
ammo9mm = Item("ammo9mm", "ammunition for 9mm guns")

# Food
ramen = Food("ramen", "a cup of instant noodles", 250)
pizza = Food("pizza", "a box of left over pizza", 300)

# Weapon
knife = Weapon("knife", "a hand knife", 20)
pistol = Weapon("pistol", "9mm pistol", 40)

# Add room items
room['outside'].addItems(ammo9mm, ammo9mm, ammo9mm, ammo9mm, ammo9mm)
room['foyer'].addItems(knife, ramen)
room['overlook'].addItems(ramen, pistol)
room['narrow'].addItems(ammo9mm, ammo9mm, ramen)
room['treasure'].addItems(pizza, pizza, ramen)

#
# Main
#

username = input("What is your name? ")
Пример #20
0
item = {
    'lever':
    Item(
        'lever', """It looks as though it was broken off at the base.
Possibly part of a larger contraption."""),
    'small potion':
    Consumable('small potion', 'Heals user for 1-3 hp.', 'potion', 5),
    'medium potion':
    Consumable('medium potion', 'Heals user for 2-6 hp.', 'potion', 5),
    'large potion':
    Consumable('large potion', 'Heals user for 2-6 hp.', 'potion', 5)
}

weapon = {
    'steel sword':
    Weapon('steel sword', 'Tried and true with a keen edge.', 2),
    'iron hammer':
    Weapon('iron hammer', 'You could not ask for a more sturdy companion.', 3)
}

# Create all the beings
npc = {
    'Orc:Vesh': NPC(room['arena'], 'Vesh', 'Orc', 40, [item['small potion']])
}

player = Player(room['arena'], 'Devon', 'Human', 20,
                [weapon['iron hammer'], item['medium potion']])

# Equip any weapons
npc['Orc:Vesh'].equip_slots['weapon'] = weapon['steel sword']
player.equip_slots['weapon'] = weapon['iron hammer']
Пример #21
0
    def examineRoom(self):
        print(self.description)
        i = 1
        if (len(self.itemList) != 0):
            sys.stdout.write("There is also ")
            for item in self.itemList:
                if (i < len(self.itemList)):
                    sys.stdout.write("a " + item.name + ", ")
                elif (i == len(self.itemList)):
                    if (i != 1):
                        sys.stdout.write("and ")
                    sys.stdout.write("a " + item.name)
                i += 1
            print(" in the " + self.name + ".")


openingRoom = Room(
    name="shack",
    description=
    "A dingy shack with glass windows leading out the back. A ladder leads up to the attic.",
    possibleDirections=["east", "west", "up"],
    itemList=[
        Weapon(damage=20,
               durability=10,
               name="Long Sword",
               description=
               "A sharp and heavy sword. Only for the experienced fighter.",
               size=20)
    ])

openingRoom.examineRoom()
Пример #22
0
 def dropItem(self):
     rand = random.randint(0, 1)
     if rand == 0:
         return Weapon(random.choice(list(WeaponType)),
                       self.getX() // 2 + 1, self.getY())
Пример #23
0
room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']

# Add items
room['foyer'].items = [
    Item("Torch", "A burning torch made of wood and cloth."),
    Item("Rock", "Just a rock.")
]
room['treasure'].items = [
    Weapon("Sword", "An iron sword in surprisingly good condition.", 4)
]

# Add monsters
room['overlook'].monsters = [Monster("Ogre", 25, 100)]

#
# Main
#

# Make a new player object that is currently in the 'outside' room.
player = Player(room['outside'])
# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
Пример #24
0
from item import Item
from item import Weapon
from item import Shield
from item import Armor
from item import HealthPotion
# DECLARATIONS

# ITEMS
items = {
    'health_potion':
    HealthPotion('Greater Health Potion',
                 'Consumption of this potion will increase player hp by 60hp',
                 60),
    'sword':
    Weapon(
        'Elven Blade',
        'Power eminates from this weapon. Equipping this weapon will increase your attack power by 20',
        20),
    'shield':
    Shield(
        'Elven Steel Shield',
        'The shield is covered in scrapes and is dented from battle. Equpping it will increase your defense by 20',
        20),
    'helm':
    Armor(
        'Elven Helmet',
        'This helmet has been through many battles. Equipping it will increase defense by 5',
        5, 'helm'),
    'chest':
    Armor(
        'Elven Chest Plate',
        'The battle worn steel should still provide protection from direct attacks. Equipping this will increase your defense by 12',
Пример #25
0
    -1,
    "a pile of 1000 gold pieces is piled high in a treasure chest near something.",
    10)

torch = LightSource(
    0, "torch", "a crude stick with an oil soaked rag at its tip",
    "a torch lies on the floor next to the chest, hastily discarded.", 0, 0, 4)

chest = Container(
    1, "chest",
    "its lock was clearly broken, but there appears to be something inside.",
    "a battered wooden chest sits in the corner", [ten_gold])

rusty_sword = Weapon(
    2, "rusty_sword",
    "rusting, it could probably do better if it were sharpened",
    "a rusty sword lies nearby under a drip somewhere on the cavern's ceiling",
    2, 4)

golden_sword = Weapon(
    3, "golden_sword",
    "This brilliant blade has clearly been well taken care of",
    "a golden sword lies buried to the hilt in a large stone just before the mouth of the chasm",
    2000, 200)

items = [
    ten_gold.name, torch.name, chest.name, rusty_sword.name, golden_sword.name
]

#Monster list
small_spider = Monster(
Пример #26
0
from location import Location
from item import Item, Weapon
from door import Door
import pygame as pg

# todo Add a way to win.
# todo implement door's and keys
# todo Come up with more stretch goals! Scoring? Monsters?

# create items
lantern = Item(name="lantern",
               description="a gas powered lantern, looks old.",
               value=2)
sword = Weapon(
    name="Short Sword",
    description="a single handed sword, it looks like it has seen battle.",
    dps=25,
    value=100)
key = Item(
    name="key",
    description="a blue key, i wonder if it fits in any of these doors.",
    value=10)
door = Door(key=key, status=False)

# create locations.
loc_one = Location(name="Outside Cave Entrance",
                   description="North of you, \n\tthe cave mouth beckons")
sub_room = Location(
    name="a small hole in the face of a rock.",
    description="seems like someone has been living here recently.")
loc_two = Location(
Пример #27
0
        handle_input()
    elif lc_command == 'q':
        print(colored('\n     **You have ended the game.**\n',
                      'red', attrs=['bold']))
        input("\n     press 'Enter' to continue")
    else:
        print(colored('\n     what command is this!?', 'red', attrs=['bold']))
        input("\n     press 'Enter' to continue")


# instantiate/initialize player, room items, and command
player = Player(room['outside'])
room['outside'].list.append(
    Item('HealthGlobe', 'Glowey Globe of Shiny Red Stuffs'))
room['outside'].list.append(Item('Sign', 'Danger, Keep out!'))
room['outside'].list.append(LightSource(
    'WillowWisp', 'A globe of shiny lights'))
room['traproom'].list.append(LightSource(
    'Torch', 'Fire strikes fear in the hearts of shadows'))
room['traproom'].list.append(Treasure('FineGemstone', 500))
room['traproom'].list.append(
    Weapon('Sword', 'A basic but effective looking blade.', 5))

command = ''  # anything other than 'q' to start main loop

# Main
while command.lower() != 'q':
    start_turn(player)
    get_input()
    handle_input()
def create():
    """
    Sets game objects at initial state and returns them.
    """
    # Declare the player
    state["player"] = Player()

    # Declare the actions
    state["action"] = {
        "attack":
        Action(name="attack",
               grammar={
                   "d_obj_required": True,
                   "preps_accepted": ("with", "using"),
               },
               run=run["attack"]),
        "die":
        Action(name="die",
               grammar={
                   "d_obj_prohibited": True,
                   "i_obj_prohibited": True,
               },
               run=run["die"]),
        "drop":
        Action(name="drop",
               grammar={
                   "d_obj_required": True,
                   "i_obj_prohibited": True,
               },
               run=run["drop"]),
        "eat":
        Action(name="eat",
               grammar={
                   "d_obj_required": True,
                   "i_obj_prohibited": True,
               },
               run=run["eat"]),
        "get":
        Action(name="get",
               grammar={
                   "d_obj_required": True,
                   "i_obj_prohibited": True,
               },
               run=run["get"]),
        "go":
        Action(name="go", grammar={
            "adv_required": True,
        }, run=run["go"]),
        "help":
        Action(name="help",
               grammar={
                   "d_obj_prohibited": True,
                   "i_obj_prohibited": True,
               },
               run=run["help"]),
        "inventory":
        Action(name="inventory",
               grammar={
                   "d_obj_prohibited": True,
                   "i_obj_prohibited": True,
               },
               run=run["inventory"]),
        "load":
        Action(name="load",
               grammar={
                   "d_obj_prohibited": True,
                   "i_obj_prohibited": True,
               },
               run=run["load"]),
        "look":
        Action(name="look",
               grammar={
                   "d_obj_prohibited":
                   True,
                   "preps_accepted": (
                       "at",
                       "in",
                       "into",
                       "inside",
                       "beneath",
                       "underneath",
                       "under",
                       "below",
                   )
               },
               run=run["look"]),
        "quit":
        Action(name="quit",
               grammar={
                   "d_obj_prohibited": True,
                   "i_obj_prohibited": True,
               },
               run=run["quit"]),
        "save":
        Action(name="save",
               grammar={
                   "d_obj_prohibited": True,
                   "i_obj_prohibited": True,
               },
               run=run["save"]),
        "talk":
        Action(name="talk",
               grammar={
                   "d_obj_prohibited": True,
                   "i_obj_required": True,
                   "preps_accepted": (
                       "to",
                       "with",
                       "at",
                   )
               },
               run=run["talk"]),
        "use":
        Action(name="use",
               grammar={
                   "d_obj_required": True,
                   "preps_accepted": (
                       "with",
                       "on",
                   )
               },
               run=run["use"]),
        "wait":
        Action(name="wait", grammar={}, run=run["wait"]),
    }

    # Declare the items
    state["item"] = {
        "fists":
        Weapon(
            slug="fists",
            name=text_style['item']("fists"),
            long_name=f"your {text_style['item']('fists')}",
            desc=None,
            stats={
                "damage": 1,
                "accuracy": 0.9
            },
            attack_text=
            (f"You pretend you're a boxer and attempt a left hook with your {text_style['item']('fists')}.",
             f"You leap forward, putting your {text_style['item']('fists')} in front of you in the hope that they "
             f"do some damage.",
             f"You swing your {text_style['item']('fists')} around in your best imitation of a helicopter."
             ),
            tags=["obtainable"]),
        "knife":
        Weapon(
            slug="knife",
            name=text_style['item']("knife"),
            long_name=f"a {text_style['item']('knife')}",
            desc=text_style['desc']
            ("It's a knife. Like for cutting your steak with, except designed for steak that is actively trying to "
             "kill you. "),
            weight=2,
            stats={
                "damage": 2,
                "accuracy": 0.95
            },
            attack_text=(
                f"Gripping your {text_style['item']('knife')} in a {text_style['item']('knife')}-like manner, you "
                f"stab with the stabby part.",
                f"You slash forward with your {text_style['item']('knife')}, praying for a hit.",
            ),
            tags=["obtainable"]),
        "sword":
        Weapon(
            slug="sword",
            name=text_style['item']("sword"),
            long_name=f"a {text_style['item']('sword')}",
            desc=text_style['desc']
            ("This sword has seen better days, but it's probably got one or two good swings left in it."
             ),
            weight=3,
            stats={
                "damage": 3,
                "accuracy": 0.8
            },
            attack_text=(
                f"You swing wildly with your {text_style['item']('sword')}.",
            ),
            tags=["obtainable"]),
        "lantern":
        LightSource(
            slug="lantern",
            name=text_style['item']("lantern"),
            long_name=f"an extinguished {text_style['item']('lantern')}",
            desc=text_style['desc']
            ("The lantern is unlit. It has fuel though; you imagine you could get it lit if you had some matches."
             ),
            weight=1,
            tags=["obtainable"]),
        "amulet_of_yendor":
        Item(slug="amulet_of_yendor",
             name=text_style['item']("Amulet of Yendor"),
             long_name=f"the {text_style['item']('Amulet of Yendor')}",
             desc=text_style['desc'](
                 "This amulet is said to contain unimaginable power."),
             weight=0.5,
             tags=["obtainable"]),
        "cheese":
        Item(slug="cheese",
             name=text_style['item']("cheese"),
             long_name=f"a hunk of {text_style['item']('cheese')}",
             desc=text_style['desc'](
                 "It is a hunk of cheese. Looks all right."),
             weight=0.25,
             tags=["obtainable", "food"]),
        "goblin_corpse":
        Item(
            slug="goblin_corpse",
            name=text_style['item']("goblin corpse"),
            long_name=f"a {text_style['item']('goblin corpse')}",
            desc=text_style['desc']
            (f"It's a dead goblin. You turn it over, looking for valuables, but all you can find is "
             f"a\\crumpled {text_style['item_in_desc']('matchbook')}, which falls to the floor next to the corpse. "
             ),
            tags=["corpse"]),
        "lever":
        Item(
            slug="lever",
            name=text_style['item']("lever"),
            long_name=
            f"a {text_style['item']('lever')} jutting from the cliff side",
            desc=text_style['desc']
            ("It looks close enough to reach. Your fingers twitch. You never could resist a good lever."
             )),
        "matchbook":
        Item(
            slug="matchbook",
            name=text_style['item']("matchbook"),
            long_name=f"a {text_style['item']('matchbook')}",
            desc=text_style['desc']
            ("At first glance, the crumpled matchbook appears to be empty, but looking closer,\\you see it still "
             "has a few matches inside. "),
            weight=0.1,
            tags=["obtainable"]),
        "rope":
        Item(slug="rope",
             name=text_style['item']("rope"),
             long_name=f"some {text_style['item']('rope')}",
             desc=text_style['desc']("Good, sturdy rope, about 50 feet long."),
             weight=2,
             tags=["obtainable"]),
    }

    # Declare the rooms
    state["room"] = {
        "outside":
        Room(
            slug="outside",
            name="Outside Cave Entrance",
            desc=text_style['desc']
            (f"{text_style['dir_in_desc']('North')} of you, the cave mouth beckons."
             ),
            no_mobs=True,
        ),
        "foyer":
        Room(
            slug="foyer",
            name="Foyer",
            desc=text_style['desc']
            (f"Dim light filters in from the {text_style['dir_in_desc']('south')}. Dusty passages "
             f"run {text_style['dir_in_desc']('north')} and {text_style['dir_in_desc']('east')}."
             ),
            init_items=[state["item"]["sword"]],
        ),
        "overlook":
        Room(
            slug="overlook",
            name="Grand Overlook",
            desc=text_style['desc']
            (f"A steep cliff appears before you, falling into the darkness. Ahead to the "
             f"{text_style['dir_in_desc']('north')}, a lightflickers in the distance, but there is no way across "
             f"the chasm. A passage leads {text_style['dir_in_desc']('south')},away from the cliff."
             ),
            init_items=[state["item"]["rope"]],
        ),
        "narrow":
        Room(
            slug="narrow",
            name="Narrow Passage",
            desc=text_style['desc']
            (f"The narrow passage bends here from {text_style['dir_in_desc']('west')} to "
             f"{text_style['dir_in_desc']('north')}. The smell of gold permeates the air."
             ),
        ),
        "treasure":
        Room(
            slug="treasure",
            name="Treasure Chamber",
            desc=text_style['desc']
            (f"You've found the long-lost treasure chamber! Sadly, it has already been completely emptied "
             f"byearlier adventurers. The only exit is to the {text_style['dir_in_desc']('south')}."
             ),
            init_items=[state["item"]["lantern"]],
        ),
        "chasm":
        Room(
            slug="chasm",
            name="Over The Edge",
            desc=text_style['desc']
            (f"You find yourself suspended over a dark chasm, at the end of a rope that was clearly notlong "
             f"enough for this job. Glancing about, you see a {text_style['item_in_desc']('lever')} jutting out "
             f"from the wall, half hidden.The rope leads back {text_style['dir_in_desc']('up')}."
             ),
            dark=True,
            dark_desc=text_style['desc']
            (f"You find yourself suspended over a dark chasm, at the end of a rope that was clearly notlong "
             f"enough for this job. It is dark. You can't see a thing. You are likely to be eaten by a grue.The "
             f"rope leads back {text_style['dir_in_desc']('up')}."),
            no_mobs=True,
            no_drop=True,
            init_items=[state["item"]["lever"]]),
        "final":
        Room(
            slug="final",
            name="Across the Chasm",
            desc=text_style['desc']
            (f"You find a small, elaborately decorated room. Sunlight streams down a hole in the ceiling "
             f"highabove you, illuminating an altar upon which sits the fabled "
             f"{text_style['item_in_desc']('Amulet of Yendor')}.To the {text_style['dir_in_desc']('south')}, a "
             f"bridge leads back the way you came."),
            init_items=[state["item"]["amulet_of_yendor"]]),
    }

    # Declare the mobs
    mob_types = {
        "goblin":
        lambda mob_id:
        Mob(mob_id=mob_id,
            name=text_style['mob']("goblin"),
            long_name=f"a {text_style['mob']('goblin')}",
            desc=text_style['desc']
            (f"The {text_style['mob_in_desc']('goblin')} is eyeing you warily and shuffling his weight from one "
             f"foot to the other.A crude knife dangles from his belt."),
            text={
                "enter":
                (f"A {text_style['mob']('goblin')} shuffles into the room. At the sight of you, he gives a squeal "
                 f"of surprise and bares his teeth.", ),
                "exit":
                (f"The {text_style['mob']('goblin')} skitters out of the room, heading ",
                 ),
                "idle": (
                    f"The {text_style['mob']('goblin')} grumbles nervously about how crowded the cave has "
                    f"gotten lately.",
                    f"The {text_style['mob']('goblin')} pulls out a knife, then thinks better of it and puts "
                    f"the knife back.",
                    f"The {text_style['mob']('goblin')} is momentarily transfixed by a rash on his elbow.",
                ),
                "dodge_success":
                (f"The {text_style['mob']('goblin')} leaps back, emotionally scarred by your violent outburst "
                 f"but physically unharmed.", ),
                "dodge_fail":
                (f"The {text_style['mob']('goblin')} staggers back, wounded physically (and emotionally).",
                 ),
                "dead":
                (f"The {text_style['mob']('goblin')} cries out in shock as your attack connects. He gives you a "
                 f"baleful glare that fades intoa look of weary resignation as he slumps to the ground, dead.",
                 ),
                "attack_success":
                (f"The {text_style['mob']('goblin')} whips its knife out towards you in a desperate arc. It carves "
                 f"into you.", ),
                "attack_fail":
                (f"The {text_style['mob']('goblin')} whips its knife out towards you in a desperate arc. You dodge "
                 f"nimbly out of the way.", ),
                "kill_player":
                (f"The {text_style['mob']('goblin')} screams at you and flies forward, plunging its knife into "
                 f"your chest. You final thought,improbably, is a silent prayer that the "
                 f"{text_style['mob']('goblin')}'s filthy knife doesn't give you an infection.",
                 )
            },
            stats={
                "health": 10,
                "damage": 2,
                "accuracy": .75,
                "evasion": .15
            },
            init_loc=state["room"]["foyer"],
            init_att="neutral",
            items=([state["item"]["goblin_corpse"]]))
    }
    state["mobs"] = [mob_types["goblin"](1)]

    # Link rooms together
    state["room"]["outside"].n_to = (state["room"]["foyer"],
                                     "You step into the mouth of the cave.")
    state["room"]["foyer"].s_to = (
        state["room"]["outside"],
        "You head south, and find yourself outside the cave.")
    state["room"]["foyer"].n_to = (
        state["room"]["overlook"],
        "You make your way north, and the cave opens up suddenly, revealing a vast chasm before you."
    )
    state["room"]["foyer"].e_to = (
        state["room"]["narrow"],
        "You take the eastern passage. It grows narrower until you have a hard time standing straight."
    )
    state["room"]["overlook"].s_to = (
        state["room"]["foyer"],
        "You step back from the cliff's edge and head south.")
    state["room"]["overlook"].n_to = (
        state["room"]["overlook"],
        "You take a step back, and get ready to jump over the gap. Then you realize that is "
        f"an incredibly stupid idea, and decide you would rather live.")
    state["room"]["narrow"].w_to = (
        state["room"]["foyer"],
        "You move west through the cramped passage until it opens up a bit.")
    state["room"]["narrow"].n_to = (state["room"]["treasure"],
                                    "You follow your nose and head north.")
    state["room"]["treasure"].s_to = (
        state["room"]["narrow"], "You head south into the narrow passage.")
    state["room"]["chasm"].u_to = (
        state["room"]["overlook"],
        "You climb slowly back up the rope, and pull yourself back onto the overlook, panting."
    )
    state["room"]["final"].s_to = (
        state["room"]["overlook"],
        "You go back across the bridge, resisting the pull of the amulet.")

    # Set initial room
    state["player"].loc = state["room"]["outside"]

    # Add functionality to items
    state["item"]["sword"].use = use_sword
    state["item"]["rope"].use = use_rope
    state["item"]["lantern"].use = use_lantern
    state["item"]["matchbook"].use = use_matchbook
    state["item"]["goblin_corpse"].on_look = on_look_goblin_corpse
    state["item"]["lever"].use_from_env = use_from_env_lever

    return state
Пример #29
0
room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']

#
# Main
#

# Make a new player object that is currently in the 'outside' room.
player = Player('Randy BoBandy', room['outside'])
weapon = Weapon(10, "prison shank", "good for stabbin")
# weapon.name = "Prison Shank"
# weapon.about = "good for stabbin"
personality_complex = Item(
    'Existential Dread',
    """so much angst and dread that it has manifested itself as a physical object"""
)

room['overlook'].add_item(weapon)
room['foyer'].add_item(weapon)
# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
# * Waits for user input and decides what to do.
#
Пример #30
0
def spawnItems():
        ls = []
        #if the # of days is greater than 2 and the room has no items (Starting condition)
        if roomslist[12].items==[] and player.items==[] and player.timeAlive<2:

            i = Item("Rock", "This is just a rock.",9)
            w = Weapon("Pencil","A bit dull but still useful for stabbing.",.5,1.5)
            ww = Weapon("Nerf Gun","You remember the chant of an old movie...\n'You'll shoot you're eye out.'",3,2)
            vv = Bags("Plastic Bag", "A torn plastic bag", 0, 4)
            aa = Armor("Blanket","Stylish AND protective!",3,0.15)
            cc=Snacks("Candy","You really should try to eat healthier...",.5,8)
            ccc=Snacks("Candy","You really should try to eat healthier...",.5,8)
            dd=Snacks("Rotten Flesh","It's a little slimey. Not good for eating.",.5,-8)
            ls = [i, w, ww, vv, aa, cc, ccc, dd]
            for n in ls:
                n.putInRoom(random.choice(roomslist))
            start=Weapon("Pencil","A bit dull but still useful for stabbing.",1,1.5)
            start.putInRoom(roomslist[12])
        #Did the player JUST kill a monster, game spawns items based on luck. Rotten flesh mostly for end goal
        elif player.monsterSlayer==True:
            oboy=giveRandom()
            if oboy>10:
                rf=Snacks("Rotten Flesh","It's a little slimey. Not good for eating.",.5,-8)
                rf.putInRoom(player.location)
            else:
                c=Snacks("Candy","You really should try to eat healthier...",.5,8)
                c.putInRoom(player.location)
                if oboy<5:
                    rf=Snacks("Rotten Flesh","It's a little slimey. Not good for eating.",.5,-8)
                    rf.putInRoom(player.location)
                    w=Weapon("Shotgun","Pow pow!",4,3.25)
                    w.putInRoom(player.location)
            player.monsterSlayer=False
        #When time passes, random items sometimes spawn on random places around the map
        else:
            r=giveRandom()
            if r>3:
                ls=[]
                if r>28:
                    cc=Snacks("Doughnuts","One big bucket of doughnuts.",2.5,25)
                    aa = Armor("Coat","It protects from rain. What about zombies?",4,0.25)
                    ls.append(cc)
                    ls.append(aa)
                elif r==28:
                    cc=Bags("Backpack","Stuff it full of candy and flesh then call it a night.", 0, 8)
                    aa=Snacks("Noodles","The nutrition label says it has at least 4 grams of fiber!",1.5,14)
                    ls.append(cc)
                    ls.append(aa)
                elif r<28 and r>6:
                    cc=Snacks("Candy","You really should try to eat healthier...",.5,8)
                    ls.append(cc)
                elif r<7:
                    cc=Snacks("Rotten Flesh","It's a little slimey. Not good for eating.",.5,-8)
                    ls.append(cc)
                for n in ls:
                    n.putInRoom(random.choice(roomslist))