Example #1
0
def create_green_dragon():
    monstertemplate = MonsterTemplate.objects.get(name='a green dragon')
    monster = Monster()
    monster.monster = monstertemplate
    monster.coins = random.randint(monstertemplate.mincoins, monstertemplate.maxcoins)
    monster.currenthp = random.randint(monstertemplate.minhp, monstertemplate.maxhp)
    return monster
Example #2
0
	def post(self):
		email = self.request.get('email')
		user = User.query(User.email == email).get()
		monsterlist = Monster.query(Monster.user == user.key).fetch()
		if user is not None and monsterlist is not None:
			playlist = []
			for monst in monsterlist:
				dbplay = Player.query(Player.monster == monst.key).get()
				if dbplay is not None:
					playlist.append(dbplay)
			pl = []
			logging.warning(playlist)
			for play in playlist:
				monster = Monster.query(Monster.key == play.monster).get()
				board = Board.get(play.board)
				if monster.properties is None:
					monster.properties = json.dumps({})
				pd = {'key': play.key.urlsafe(), 'monster': {'key': monster.key.urlsafe(), 'name': monster.name, 'properties': json.loads(monster.properties), 'date': str(monster.date)}, 'board': {'key': play.board.urlsafe()}}
				pl.append(pd)

			if user.gamelimit is None:
				user.gamelimit = 1
				user.put()
			logging.warning({'status': 1, 'games': pl, 'gamelimit': user.gamelimit})
			self.response.out.write(json.dumps({'status': 1, 'games': pl, 'gamelimit': user.gamelimit}))
		else:
			self.response.out.write(json.dumps({'status': -1, 'message': 'User not found.'}))
Example #3
0
    def remove_dungeons_monster(id):
        payload = request.get_json()
        monster_id = payload.get("monster_id", None)

        if not monster_id:
            abort(400)

        if dungeon := Dungeon.find(id):
            if monster := Monster.find(monster_id):
                dungeon.monsters.remove(monster)
                dungeon.update()
Example #4
0
 def update_monster(id):
     payload = request.get_json()
     if monster := Monster.find(id):
         if name := payload.get("name", None):
             if checker := Monster.find_by(name):
                 if monster.id != checker.id:
                     abort(
                         Response(
                             response=
                             f"Name: '{name}' belongs to another monster.",
                             status=405,
                         ))
Example #5
0
def main():

    # 创建人物
    print("[{0}] [GAME] 你好, 欢迎来到新心镇, 我姓王, 是你的新邻居, 也是口袋研究所的博士, 你叫什么名字? ")
    while True:
        name = input("输入你的名字: ")
        if len(name) > 0:
            break
    print("[{0}] [GAME] 啊, [{1}], 多么好听的名字, 那么, 请告诉你的性别?".format(NOW(), name))
    while True:
        gender = input("输入你的性别(0: 女孩, 1: 男孩): ")
        if gender == '0' or gender == '1':
            break
    print("[{0}] [GAME] 原来是个{1}孩子!".format(NOW(), GENDER_CN[int(gender)]))
    # 创建角色
    pid = createMaster(1, name, int(gender))
    print("pid: ", pid)
    player = Master(pid, name, int(gender))
    # 场景: 家
    print("[{0}] [家] 妈妈: [{1}], 这里就是你的新家了, 有空去镇子上跟大家打个招呼吧".format(
        NOW(), player.name))
    # 场景: 新心镇
    print("[{0}] [新心镇]".format(NOW()))
    # 场景: 野外
    print("[{0}] [野外]".format(NOW()))
    print("[{0}] [野外] 选择你的初始怪兽!".format(NOW()))
    print("[{0}] [野外] 1: 鼻涕狗; 2: 玩偶喵; 3: 囤囤鼠".format(NOW()))
    while True:
        try:
            choice = int(input("输入你的选择(1/2/3): "))
            if choice in [1, 2, 3]:
                break
        except:
            pass
    GIFT = {1: '哭哭狗', 2: '玩偶喵', 3: '囤囤鼠'}
    print("[{0}] [野外] [{1}]选择了[{2}]".format(NOW(), name, GIFT[choice]))
    # 生成实例
    race = {1: 1, 2: 4, 3: 7}
    raceC = race[choice]
    print("race: ", raceC)
    monster = Monster(raceC, 1, 5)
    print("[{0}] [野外] 你想给它取个名字吗?".format(NOW()))
    mName = input("输入名字: ")
    monster.nickname = mName if mName else EVOLUTION[raceC][-1]
    print("[{0}] [野外] [{1}]? 这名字真不错".format(NOW(), monster.nickname))
    # 存入数据库
    mid = createMonster(monster)
    # 收服怪兽
    player.getMonster(mid)
    def setUp(self):
        """Define test variables and initialize app."""
        # binds the app to the current context
        self.app = create_app()
        setup_db(self.app)
        self.client = self.app.test_client
        self.headers = {
            "Authorization": "bearer " + os.environ["VALID_TEST_TOKEN"]
        }

        Monster(
            name="monster_name",
            race="monster_race",
            health_points="100",
            armor_points="100",
            attack_damage="100",
            xp_drop="100",
        ).insert()

        Dungeon(
            level="1",
            rooms="1",
            treasures="1",
            traps="1",
            boss_level=False,
            xp_drop="1000",
        ).insert()
Example #7
0
def create_random_monster(maxlevel = 20):
    number = random.randint(1,10)
    monsters = list()
    if number < 7:
        monsters = MonsterTemplate.objects.filter(rarity=0, level__lte=maxlevel)
    elif number < 10:
        monsters = MonsterTemplate.objects.filter(rarity=1, level__lte=maxlevel)
    else:
        monsters = MonsterTemplate.objects.filter(rarity=2, level__lte=maxlevel)
    total = len(monsters)
    number = random.randint(0, total-1)
    monstertemplate = monsters[number]
    monster = Monster()
    monster.monster = monstertemplate
    monster.coins = random.randint(monstertemplate.mincoins, monstertemplate.maxcoins)
    monster.currenthp = random.randint(monstertemplate.minhp, monstertemplate.maxhp)
    return monster
 def test_ok_found_monster(self):
     monster = Monster.find_by("monster_name")
     id = monster.id
     response = self.client().get(
         f"/monsters/{id}",
         headers=self.headers,
     )
     self.assertEqual(response.status_code, 200)
Example #9
0
async def create_monster(*, monster: Monster):
    """
    Endpoint to handle Monster creation
    """
    query = None

    weaknesses = str(
        [
            Weakness(
                element=weakness.element,
                stars=weakness.stars,
                condition=getattr(weakness, "condition", ""),
            ).dict()
            for weakness in monster.weaknesses
            if monster.weaknesses
        ]
    )
    resistances = str(
        [
            Resistance(
                element=resistance.element,
                condition=getattr(resistance, "condition", ""),
            ).dict()
            for resistance in monster.resistances
            if monster.resistances
        ]
    )
    images = str(
        [
            Image(name=image.name, url=image.url).dict()
            for image in monster.images
            if monster.images
        ]
    )
    ailments = str(
        [
            Ailment(name=ailment.name, actions=ailment.actions).dict()
            for ailment in monster.ailments
            if monster.ailments
        ]
    )
    elements = str([element for element in monster.elements if monster.elements])
    query = monsters_db.insert().values(
        name=monster.name,
        species=monster.species,
        size=monster.size.name,
        weaknesses=weaknesses,
        resistances=resistances,
        images=images,
        ailments=ailments,
        elements=elements,
    )

    last_record_id = await database.execute(query)
    return {**monster.dict(), "id": last_record_id}
 def test_ok_add_monster_to_dungeon(self):
     monster = Monster.find_by("monster_name")
     monster_id = monster.id
     dungeon = Dungeon.find_by(1)
     dungeon_id = dungeon.id
     response = self.client().post(
         f"/dungeons/{dungeon_id}/monsters",
         headers=self.headers,
         json={"monster_id": monster_id},
     )
     self.assertEqual(response.status_code, 200)
def create_monster(monster_data, db_session):
    """Create new monster object."""
    monster = Monster(name=monster_data['name'],
                      diet=monster_data['diet'],
                      enjoys=monster_data['enjoys'],
                      creator=monster_data['creator'],
                      picture=monster_data['picture'],
                      intentions=monster_data['intentions'],
                      created_date=datetime.datetime.now())
    create_response = insert_update_monster(monster, db_session, 'insert')
    return create_response
 def test_ok_remove_monster_to_dungeon(self):
     monster = Monster.find_by("monster_name")
     monster_id = monster.id
     dungeon = Dungeon.find_by(1)
     dungeon_id = dungeon.id
     dungeon.monsters.append(monster)
     response = self.client().delete(
         f"/dungeons/{dungeon_id}/monsters",
         headers=self.headers,
         json={"monster_id": monster_id},
     )
     self.assertEqual(response.status_code, 200)
Example #13
0
	def post(self):
		email = self.request.get('email')
		user = User.query(User.email == email).get()
		monster = self.request.get('monster')
		name = self.request.get('name')
		if user is not None:
			if monster == '':
				monsterlist = Monster.query(Monster.user == user.key).fetch()
				if len(monsterlist) < user.gamelimit:
					newmonster = True
					m = Monster()
					m.user = user.key
				else:
					newmonster = False
					self.response.out.write(json.dumps({'status': 0, 'message': 'Monster limit reached.'}))
			else:
				m = ndb.Key(urlsafe=monster).get()
				if m is not None and m.user == user.key:
					newmonster = True
				else:
					newmonster = False
					self.response.out.write(json.dumps({'status': -2, 'message': 'Monster not found.'}))
			if newmonster:
				m.name = name
				m.put()
				self.response.out.write(json.dumps({'status': 1, 'message': 'Monster ' + name + ' created/updated for user ' + user.email + '.'}))
		else:
			self.response.out.write(json.dumps({'status': -1, 'message': 'User not found.'}))
Example #14
0
    def add_monster():
        payload = request.get_json()
        if not payload:
            abort(400)

        name = payload.get("name", None)

        if Monster.find_by(name):
            abort(
                Response(
                    response=f"Monster '{name}' already created.",
                    status=405,
                ))

        race = payload.get("race", None)
        health_points = payload.get("health_points", None)
        armor_points = payload.get("armor_points", None)
        attack_damage = payload.get("attack_damage", None)
        xp_drop = payload.get("xp_drop", None)

        monster = Monster(
            name=name,
            race=race,
            health_points=health_points,
            armor_points=armor_points,
            attack_damage=attack_damage,
            xp_drop=xp_drop,
        )
        monster.insert()
        return jsonify(monster.short())
 def test_ok_create_monster(self):
     payload = {
         "name": "new_name",
         "race": "monster_race",
     }
     response = self.client().post(
         "/monsters",
         headers=self.headers,
         json=payload,
     )
     self.assertEqual(response.status_code, 200)
     monster = Monster.find_by("new_name")
     monster.delete()
 def test_ok_update_monster(self):
     monster = Monster.find_by("monster_name")
     id = monster.id
     payload = {
         "name": "monster_name",
         "attack_damage": "3",
         "xp_drop": "100",
     }
     response = self.client().patch(
         f"/monsters/{id}",
         headers=self.headers,
         json=payload,
     )
     self.assertEqual(response.status_code, 200)
Example #17
0
class MonsterWindow(arcade.Window):
    def __init__(self, width, height):
        super().__init__(width, height, "Monster Keeper")
        self.background = arcade.load_texture("images/homeee.png")  
        self.Snoopy = Snoopy("images/snoopy.png",0.75)
        self.Monster = Monster("images/cookiemon.png", 0.5, self.Snoopy)
        
    def on_key_release(self, key, modifiers):
        self.Snoopy.on_key_release(key, modifiers)
    
    def on_key_press(self, key, modifiers):
        self.Snoopy.on_key_press(key, modifiers)
        if key == arcade.key.R:
            if self.Monster.score < 0:
                self.Snoopy = Snoopy("images/snoopy.png",0.75)
                self.Monster = Monster("images/cookiemon.png", 0.5, self.Snoopy)

    def on_draw(self):
        arcade.start_render()
        arcade.draw_texture_rectangle(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2,
                                      SCREEN_WIDTH, SCREEN_HEIGHT, self.background)
        self.Monster.on_draw()
        self.Snoopy.draw()
        if self.Monster.score < 0 :
            arcade.draw_text("GAME OVER", 200, 300, arcade.color.BLACK, 50)
            arcade.draw_text("Press R to restart", 222, 250 , arcade.color.BLACK, 30)
        else :
            arcade.draw_text("Score : "+str(self.Monster.score), 10, 650, arcade.color.WHITE, 30)

    def update(self, delta):
        self.Monster.update()
        self.Snoopy.update()
        if self.Monster.score < 0 :
            arcade.draw_text("GAME OVER", SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, arcade.color.BLACK, 50)
            arcade.draw_text("Press R to restart", SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2+200 , arcade.color.BLACK, 30)
        else :
            arcade.draw_text("Score : "+str(self.Monster.score), 600, 600, arcade.color.WHITE, 30)
Example #18
0
    def load(self, monster_name, count=1):
        # TODO: hey maybe make this more efficient, yeah?

        monster_files = self.get_available_monster_files()
        monsters = []

        for filename in monster_files:
            monster = toml.load(open(filename, 'r'))

            if monster['name'] != monster_name:
                continue

            for i in range(count):
                monsters.append(Monster(**monster))
            break

        return monsters
Example #19
0
	def post(self):
		email = self.request.get('email')
		user = User.query(User.email == email).get()
		if user is not None:
			monsterlist = Monster.query(Monster.user == user.key).fetch()
			ml = []
			for monster in monsterlist:
				if monster.properties is None:
					monster.properties = json.dumps({})
				md = {'key': monster.key.urlsafe(), 'user': monster.user.urlsafe(), 'name': monster.name, 'properties': json.loads(monster.properties), 'date': str(monster.date)}
				ml.append(md)

			if user.gamelimit is None:
				user.gamelimit = 1
				user.put()
			self.response.out.write(json.dumps({'status': 1, 'monsters': ml, 'gamelimit': user.gamelimit}))
		else:
			self.response.out.write(json.dumps({'status': -1, 'message': 'User not found.'}))
Example #20
0
def create_all():
    with open('data_monsters.json', 'r') as f:
        monsters = json.loads(f.read())

    for monster in monsters:
        if not monster.get('name'):
            continue

        session.merge(
            Monster(
                str=monster.get('strength', None),
                con=monster.get('constitution', None),
                int=monster.get('intelligence', None),
                wis=monster.get('wisdom', None),
                cha=monster.get('charisma', None),
                dex=monster.get('dexterity', None),
                HP=monster.get('hit_points', None),
                AC=monster.get('armor_class', None),
                speed=monster.get('speed', None),
                name=monster.get('name', None),
                size=monster.get('size', None),
                type=monster.get('type', None),
                subtype=monster.get('subtype', None),
                alignment=monster.get('alignment', None),
                hit_dice=monster.get('hit_dice', None),
                stealth=monster.get('stealth', None),
                damage_vulnerabilities=monster.get('damage_vulnerabilities',
                                                   None),
                damage_resistances=monster.get('damage_resistances', None),
                damage_immunities=monster.get('damage_immunities', None),
                condition_immunities=monster.get('condition_immunities', None),
                senses=monster.get('senses', None),
                languages=monster.get('languages', None),
                challenge_rating=monster.get('challenge_rating', None),
                special_abilities=dict_to_rst(
                    monster.get('special_abilities', [])),
                actions=dict_to_rst(monster.get('actions', [])),
            ))

    session.commit()
Example #21
0
def main():
    hero = Monster(0, "Hero")
    darkhero = Monster(2, "DarkHero")
    zhero = Monster(3, "Z-Hero")
    enemy = Monster(1, "Shadow")

    hero.attack(enemy)
    hero.itemEquip("圣剑")

    player1 = Master(0, "Zy")
    player2 = Master(1, "Shadow")

    # player1.showMyEquipments()
    # player1.showMyMainBag()
    # player1.showMyPower()

    # npc1 = NPC(0, "Magerita")
    # npc1.Talkto(player1)
    # npc1.Buyfrom(player1)
    # npc1.Sellto(player1)
    # npc1.QuitSession()
    # npc1.Fightto(player1)

    hero.showSkills()
    hero.learnSkill("死从天降")
    hero.showSkills()

    player1.showMyTeam()
    player1.addTeamMember(hero)
    player1.addTeamMember(darkhero)
    player1.addTeamMember(darkhero)
    player1.addTeamMember(darkhero)
    player1.addTeamMember(darkhero)
    player1.addTeamMember(darkhero)
    player1.addTeamMember(zhero)
    player1.showMyTeam()
    player1.showMonsterRepo()
    player1.showItemRepo()
Example #22
0
 def createMonster(self):
     monster = Monster('Rabid Gnome')
     characterLeveler(monster, self.players[0].lvl)
     self.monsters.append(monster)
     messageDirect('A new monster joins the fray!\n', monster)
Example #23
0
    party = toml.load(fin)

characters = [Character(**x) for x in party.values()]

with open('encounters/lmop1.1.1.toml', 'r') as fin:
    encounter = Encounter(**toml.load(fin))
    print(encounter)

for group in encounter.groups.values():
    available_monster_files = glob.glob('monsters/*.toml')
    monsters = []
    for filename in available_monster_files:
        monster = toml.load(open(filename, 'r'))
        if monster['name'] == group['monster']:
            for i in range(group['count']):
                monsters.append(Monster(**monster))
            break
    for i in range(len(monsters)):
        if 'max_hp' in group and len(group['max_hp']) == len(monsters):
            monsters[i].max_hp = group['max_hp'][i]
            monsters[i].cur_hp = group['max_hp'][i]
        else:
            monsters[i].max_hp = monsters[i]._max_hp
            monsters[i].cur_hp = monsters[i].max_hp
    for monster in monsters:
        tm.add_combatant(monster,
                         roll_dice(1, 20, modifier=monster.initiative_mod))

for character in characters:
    tm.add_combatant(character,
                     roll_dice(1, 20, modifier=character.initiative_mod))
Example #24
0
 def on_key_press(self, key, modifiers):
     self.Snoopy.on_key_press(key, modifiers)
     if key == arcade.key.R:
         if self.Monster.score < 0:
             self.Snoopy = Snoopy("images/snoopy.png",0.75)
             self.Monster = Monster("images/cookiemon.png", 0.5, self.Snoopy)
Example #25
0
 def __init__(self, width, height):
     super().__init__(width, height, "Monster Keeper")
     self.background = arcade.load_texture("images/homeee.png")  
     self.Snoopy = Snoopy("images/snoopy.png",0.75)
     self.Monster = Monster("images/cookiemon.png", 0.5, self.Snoopy)
Example #26
0
 def get_monsters():
     if monsters := Monster.all():
         result = {"success": True, "Monsters": monsters}
         return jsonify(result)
Example #27
0
 def get_monster(id):
     if monster := Monster.find(id):
         result = {"success": True, "Monster": monster.long()}
         return jsonify(result)
Example #28
0
 def remove_monster(id):
     if monster := Monster.find(id):
         name = monster.name
         monster.delete()
         result = {"success": True, "deleted": name}
         return jsonify(result)
Example #29
0
 def new_monster(self, name):
     self.add_monster(Monster(name=name))
 def tearDown(cls):
     if monster := Monster.find_by("monster_name"):
         monster.delete()