示例#1
0
    async def create(self, ctx):
        """Create a new player!
        You can't create one if you already have one.
        Use the "delete" command for that."""
        if ctx.author.id in self.is_creating:
            return
        player = self.get_player(ctx.author)
        if player:
            return await ctx.send("{} You already own \"{}\"!".format(blobs.BLOB_ANGERY, player))
        if await self.bot.db.fetchval("SELECT owner_id FROM players WHERE owner_id=$1;", ctx.author.id):
            return await ctx.send(f"You do have a player, just it has not been loaded.\n"
                                  f"Try using `{ctx.prefix}recover` to forcibly reload it.")
        self.is_creating.append(ctx.author.id)
        await ctx.send("{} What should the name be? (Name must be 32 characters or lower in length)".format(
            blobs.BLOB_O))

        def msgcheck(m):
            return len(m.content) < 33 and m.author == ctx.author

        try:
            msg = await self.bot.wait_for("message", check=msgcheck, timeout=60.0)
        except asyncio.TimeoutError:
            await ctx.send("Took too long...")
        else:
            msg = await commands.clean_content().convert(ctx, msg.content)
            log.info("Player \"%s\" was created by \"%s\".", msg, ctx.author)
            player = utils.Player(owner=ctx.author, name=msg, bot=self.bot, created_at=datetime.utcnow())
            await player.save()
            self.players.append(player)
            await ctx.send("{} Success! \"{}\" was sent to map #0 (Abel).".format(blobs.BLOB_PARTY, msg))
        finally:
            self.is_creating.remove(ctx.author.id)
示例#2
0
 async def on_ready(self):
     await self.bot.prepared.wait()
     if len(self.players) > 0:
         return
     # log.debug("INIT")
     self.ignored_channels = list(map(int, await self.bot.redis.smembers("channel_ignore")))
     self.ignored_guilds = list(map(int, await self.bot.redis.smembers("guild_ignore")))
     for data in await self.fetch_players():
         owner_id, name, map_id, created, explored, exp, compendium, gold, *_ = data
         # log.debug("DATA %s", data)
         user = self.bot.get_user(owner_id)
         if not user:
             log.warning("Unknown user id %s. Skipping initialization. (%s)", owner_id, len(self.bot.users))
             continue
         status = await self.bot.redis.get(f"status_{user.id}")
         if status:
             status = utils.Status(int(status))
         else:
             status = utils.Status.idle
         player = utils.Player(
             owner=user,
             bot=self.bot,
             name=name,
             created_at=created,
             explored=list(map(self.bot.map_manager.get_map, explored)),
             status=status,
             exp=exp,
             next_map=await self.bot.redis.get(f"next_map_{user.id}"),
             compendium=compendium,
             gold=gold
         )
         player.map = map_id
         self.players.append(player)
         log.info("Player \"%s\" (%s) initialized at map \"%s\".", player.name, str(player.owner), player.map)
示例#3
0
文件: actions.py 项目: StrikerIV/RPG
def move(args, world):
    # this is the function that actually moves the character around
    # it's quite simple, depending on where they move we edit the x / y values
    # negative or positive. to move forward, increase "x" by one, ect

    # we know args[0] is the command, so we initially start with [1]
    player = utils.Variables.playerPosition

    playerX = player.x
    playerY = player.y

    if (args[1] == ""):
        # nothing was supplied
        return False
    elif (args[1] == "forward" or args[1] == "up"):
        # input was to move "up" / "forward"
        if (playerX - 1 < 0):
            # out of bounds
            return True
        updatedPlayer = utils.Player((playerX - 1, playerY))
        utils.Variables.playerPosition = updatedPlayer
        #print(utils.Variables.playerPosition.x, utils.Variables.playerPosition.x)
        return True
    elif (args[1] == "back" or args[1] == "down"):
        # input was to move "back" / "down"
        if (playerX + 1 == 500):
            # out of bounds
            return True
        updatedPlayer = utils.Player((playerX + 1, playerY))
        utils.Variables.playerPosition = updatedPlayer
        return True
    elif (args[1] == "left"):
        # input was to move "left"
        if (playerY - 1 < 0):
            # out of bounds
            return True
        updatedPlayer = utils.Player((playerX, playerY - 1))
        utils.Variables.playerPosition = updatedPlayer
        return True
    elif (args[1] == "right"):
        # input was to move "right"
        if (playerY + 1 == 500):
            # out of bounds
            return True
        updatedPlayer = utils.Player((playerX, playerY + 1))
        utils.Variables.playerPosition = updatedPlayer
        return True
示例#4
0
    async def fetch_tribe_member(self, world, allys, name=False):
        if not isinstance(allys, (tuple, list)):
            allys = [allys]
        if name:
            tribes = await self.fetch_bulk(world, allys, table=1, name=True)
            allys = [tribe.id for tribe in tribes]

        query = f'SELECT * FROM player WHERE world = $1 AND tribe_id = ANY($2)'
        async with self.pool.acquire() as conn:
            res = await conn.fetch(query, world, allys)
            return [utils.Player(rec) for rec in res]
示例#5
0
    async def fetch_player(self, world, searchable, *, name=False, archive=''):
        table = f"player{archive}"

        if name:
            searchable = utils.converter(searchable, True)
            query = f'SELECT * FROM {table} WHERE world = $1 AND LOWER(name) = $2'
        else:
            query = f'SELECT * FROM {table} WHERE world = $1 AND id = $2'

        async with self.pool.acquire() as conn:
            result = await conn.fetchrow(query, world, searchable)
            return utils.Player(result) if result else None
示例#6
0
def load_game():
    saves = os.listdir("saves/")

    utils.clear_screen()
    if (not saves):
        # there are no saves, so we go back to main screen
        print("There are currently no saved games.")
    else:
        print("Load a save by name - \n")

        for index, save in enumerate(saves):
            print("    %s. %s" % (index + 1, save))

        saveChoice = str(input("\n\n"))

        if (not saveChoice in saves):
            # specified save is not a valid save, go back to load game
            return load_game()
        else:
            # now we load the variables from the save and head to the game terminal
            path = 'saves/%s' % saveChoice

            utils.Variables.world = np.genfromtxt("%s/world.txt" % path,
                                                  delimiter=" ",
                                                  dtype=str)

            with open("%s/variables.json" % path) as variablesFile:
                variables = json.loads(variablesFile.read())
                pPosTuple = tuple(
                    map(int, variables["playerPosition"].split(", ")))

                utils.Variables.playerPosition = utils.Player(
                    (pPosTuple[0], pPosTuple[1]))
                utils.Variables.currentlyTyping = variables['currentlyTyping']
                utils.Variables.playerName = saveChoice
                utils.Variables.inventory = variables['inventory']

                time.sleep(2)
                game_terminal(utils.Variables.world,
                              utils.Variables.playerPosition)
示例#7
0
 async def recover(self, ctx):
     """Attempts to re-cache your player, if it isn't.
     You will be alerted to use this if you do have a player, but it hasn't been loaded."""
     pm = self.bot.player_manager
     if pm.get_player(ctx.author):
         return await ctx.send(
             f"{blobs.BLOB_ANGERY} Your player is already cached!")
     data = await self.bot.db.fetchrow(
         "SELECT * FROM players WHERE owner_id=$1;", ctx.author.id)
     if not data:
         return await ctx.send(
             f"{blobs.BLOB_SAD} Couldn't find any data for you."
             f"\nIf you did have a player, then I'm afraid it's gone now.")
     owner_id, name, map_id, created, explored, exp, compendium, gold, *_ = data
     user = self.bot.get_user(owner_id)
     status = await self.bot.redis.get(f"status_{owner_id}")
     if status:
         status = utils.Status(int(status))
     else:
         status = utils.Status.idle
     player = utils.Player(owner=user,
                           bot=self.bot,
                           name=name,
                           created_at=created,
                           explored=list(
                               map(self.bot.map_manager.get_map, explored)),
                           status=status,
                           exp=exp,
                           next_map=await
                           self.bot.redis.get(f"next_map_{user.id}"),
                           compendium=compendium,
                           gold=gold)
     player.map = map_id
     pm.players.append(player)
     log.info("Recovered player %s (%s).", player.name, ctx.author)
     await ctx.send(
         f"{blobs.BLOB_PARTY} Success! {player.name} has been revived!")
示例#8
0
def redeem_player(update: Update, context: CallbackContext) -> None:
    try:
        valid_context = services.validate_context_for_player(context.args)
        player = utils.Player(*valid_context)
        result = services.start_asking_player(player)
        context.bot.send_message(chat_id=update.effective_chat.id, text=result)

    except utils.AuthError:
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text="Неверные данные пользователя",
        )

    except utils.ListLengthError:
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text="Неправильно введены данные",
        )

    except NetworkError:
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text="Ошибка соединения телеграмма",
        )
示例#9
0
import pygame

import os
import random
from constants import *
import gui
import utils
import biomes
from block import Block

player = utils.Player()


class GameState(utils.State):
    def __init__(self, state_data):
        super().__init__(state_data)

        self.buttons = dict()

        self.buttons["INVENTORY"] = gui.Button(
            x=0,
            y=HEIGHT - 60,
            text="Inventory",
            callback=(lambda: self.states.push(InventoryState(state_data))))

        self.current_biome = biomes.cave_level_1

        self.blocks = list()
        self.blocks.append(Block("dirt", 1))
        self.delay = 20
示例#10
0
import utils

print("game is started...")
player_Frank = utils.Player("Frank")
player_David = utils.Player("David")
player_Mariam = utils.Player("Mariam")
player_Sara = utils.Player("Sara")
print("All players have 10 cards...........")
more_card = True
i = 0
while more_card:
    i += 1
    print(i, ". turn------------------------")
    if len(player_Mariam.cards) == 0:
        more_card = False
    else:
        player_Mariam.play()
    if len(player_David.cards) == 0:
        more_card = False
    else:
        player_David.play()
    if len(player_Frank.cards) == 0:
        more_card = False
    else:
        player_Frank.play()
    if len(player_Sara.cards) == 0:
        more_card = False
    else:
        player_Sara.play()
    if more_card == False:
        break
示例#11
0
	def setUp(self):
		self.test_player = utils.Player('X')
示例#12
0
async def tutorial(ctx: utils.EpicContext):
    bot = ctx.bot
    if bot.player_manager.get_player(ctx.author):
        return await ctx.send("You already have a player! No need to run the tutorial!")
    if ctx.author.id in bot.in_tutorial:
        return
    bot.in_tutorial.append(ctx.author.id)

    await ctx.send("Hiya! I'm gonna run you through a tutorial on how to use this bot!")
    await asyncio.sleep(2)
    await ctx.send(f"First off, you'll need a player. You can achieve this by using `{ctx.prefix}create`.")
    await ctx.bot.wait_for("message", check=first_check(ctx))
    await ctx.send(f"{blobs.BLOB_O} What should the name be? (Name must be 32 characters or lower in length)")
    msg = await ctx.bot.wait_for("message", check=second_check(ctx))
    await ctx.send(f"{blobs.BLOB_PARTY} Success! \"{msg.clean_content}\" was sent to map #0 (Abel)")
    player = utils.Player(
        bot=bot,
        owner=ctx.author,
        name=msg.clean_content,
        created_at=msg.created_at
    )
    await asyncio.sleep(2)
    await ctx.send("Great! Now you have a player. Lets run through some basic commands.")
    await asyncio.sleep(2)
    await ctx.send(f"You aren't gonna get far without knowing where you can go. Try using `{ctx.prefix}maps` to view"
                   f" the current available maps.")
    await bot.wait_for("message", check=third_check(ctx))
    msg = await maps_(ctx, player)
    await ctx.send("Click \N{BLACK SQUARE FOR STOP} when you are done.")
    await bot.wait_for("reaction_add", check=fourth_check(ctx, msg))
    await ctx.send("Good. Now you know where you are, it's time to do some exploring.")
    await asyncio.sleep(2)
    await ctx.send(f"Let's head on over to the beach. We can explore around there.\nUse `{ctx.prefix}travel abel beach`"
                   f" to head over there.")
    await bot.wait_for("message", check=fifth_check(ctx))
    _map = bot.map_manager.resolve_map("abel beach")
    time = _map.calculate_travel_to(player)
    await ctx.send(f"{blobs.BLOB_SALUTE} {player.name} is now travelling to Abel Beach and "
                   f"will arrive in {time*60:.0f} minutes.")
    await asyncio.sleep(2)
    await ctx.send(f"Since this is a tutorial, you don't actually have to wait {time*60:.0f} minutes."
                   f" I'll speed you up.")
    await asyncio.sleep(2)
    player.map = _map
    await ctx.send(f"{blobs.BLOB_PARTY} {player.name} has arrived at Abel Beach!")
    await asyncio.sleep(2)
    await ctx.send(f"Now that we have arrived, it's time to explore the area. Use `{ctx.prefix}explore` to begin.")
    await bot.wait_for("message", check=sixth_check(ctx))
    time = _map.calculate_explore()
    await ctx.send(f"{blobs.BLOB_SALUTE} {player.name} is now exploring Abel Beach and"
                   f" will finish in {time*60:.0f} minutes.")
    await asyncio.sleep(2)
    await ctx.send("Exploring tends to take a lot longer than travelling."
                   " I'll speed you up again for the sake of this tutorial.")
    player.explored_maps.append(player.map)
    await asyncio.sleep(2)
    await ctx.send(f"{blobs.BLOB_PARTY} {player.name} has finished exploring Abel Beach!")
    await asyncio.sleep(2)
    await ctx.send(f"Side note, you can use `{ctx.prefix}profile` to view your current profile.")
    await bot.wait_for("message", check=seventh_check(ctx))
    await ctx.trigger_typing()
    async with bot.session.get(str(ctx.author.avatar_url_as(format="png", size=256))) as get:
        avy = io.BytesIO(await get.read())
    profile = await bot.player_manager.profile_for(avy, player)
    file = discord.File(profile, "profile.png")
    await ctx.send(file=file)
    await asyncio.sleep(2)
    await ctx.send("Hmm, you seem a little low on exp there. Outside the tutorial,"
                   " travelling / exploring gives you quite a lot of experience. "
                   "I'll give you a little exp buff for now.")
    await asyncio.sleep(2)
    player.exp += 1729
    await ctx.send(f"{blobs.BLOB_PARTY} {player.name} has levelled to tier 12!")
    await asyncio.sleep(2)
    await ctx.send("Now that you are buffed up, it's time to fight some enemies!")
    await asyncio.sleep(2)
    await ctx.send(f"Let's search for something! Use `{ctx.prefix}encounter` to search for an enemy.")
    await bot.wait_for("message", check=eigth_check(ctx))
    await encounter(ctx, player)
    await asyncio.sleep(2)
    await ctx.send("Good job! After defeating an enemy, you'll be awarded with Experience and Coins.")
    await asyncio.sleep(2)
    await ctx.send("As you get more exp, the enemies you are able to defeat increases.")
    await asyncio.sleep(2)
    await ctx.send("There is one more mechanic I can show you, which is the `capturing` mechanic.")
    await asyncio.sleep(2)
    await ctx.send("The `capturing` mechanic is vital, as filling the `compendium` is the goal of your adventure.")
    await asyncio.sleep(2)
    await ctx.send(f"Try using `{ctx.prefix}encounter` again, this time you'll be prompted to capture the enemy.")
    await bot.wait_for("message", check=eigth_check(ctx))
    enemy = await capture(ctx)
    await asyncio.sleep(2)
    await ctx.send(f"Sweet, you captured the {enemy.name}. Now if you use the command `{ctx.prefix}compendium`, "
                   f"it'll show it's name in a table.")
    await bot.wait_for("message", check=ninth_check(ctx))
    comp = player.compendium
    comp.bits[enemy.id-1] = 1
    render = comp.format()
    await ctx.send(f"```\n{render}\n```")
    await asyncio.sleep(2)
    await ctx.send("And that's pretty much everything! Since your player is a tutorial player, I'll have to delete it.")
    await asyncio.sleep(2)
    await ctx.send("Try to remember everything that happened in this tutorial, and you should be fine.")
    await asyncio.sleep(2)
    await ctx.send("Good luck on your Adventure!")
    bot.in_tutorial.remove(ctx.author.id)
    del player
示例#13
0
    async def graveyard_(self,
                         ctx,
                         village: CoordinateConverter,
                         *,
                         options=None):
        args = utils.keyword(options,
                             **self.base_options,
                             since=[1, 3, 14],
                             tribe=None)
        radius, points, inactive_since, tribe = args

        all_villages = await self.fetch_in_radius(ctx.server,
                                                  village,
                                                  radius=radius)
        player_ids = set([vil.player_id for vil in all_villages])

        base = []
        for num in range(inactive_since.value + 1):
            table = f"player{num or ''}"
            query_part = f'SELECT * FROM {table} ' \
                         f'WHERE {table}.world = $1 ' \
                         f'AND {table}.id = ANY($2)'

            if tribe.value in [True, False]:
                state = '!=' if tribe.value else '='
                query_part += f' AND {table}.tribe_id {state} 0'

            base.append(query_part)

        query = ' UNION ALL '.join(base)
        async with self.bot.pool.acquire() as conn:
            cache = await conn.fetch(query, ctx.server, player_ids)
            result = [utils.Player(rec) for rec in cache]

        player_cache = {}
        day_counter = Counter()
        for player in result:

            last = player_cache.get(player.id)
            if last is None:

                if not points.compare(player.points):
                    player_cache[player.id] = False
                else:
                    player_cache[player.id] = player

            elif last is False:
                continue

            elif last.points <= player.points and last.att_bash == player.att_bash:
                player_cache[player.id] = player
                day_counter[player.id] += 1

            else:
                player_cache[player.id] = False

        result = []
        for player_id, player in player_cache.items():
            if day_counter[player_id] != inactive_since.value:
                continue
            else:
                result.append(player)

        await self.send_result(ctx, result, "inaktiven Spieler")
示例#14
0
import pygame, utils, Col2D

pygame.init()
screen = pygame.display.set_mode((500, 500))

player = utils.Player((0, 200), (0, 255, 0))
objects = [
    utils.Rectangle((0, 450), (500, 50), (255, 255, 0)),
    utils.Rectangle((0, 300), (500, 5), (255, 255, 0))
]
lasttick = 0
while True:
    curtick = pygame.time.get_ticks()
    dt = (curtick - lasttick) / 1000

    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            player.jump(objects)

    player.update(dt, objects)

    player.draw(screen)
    for obj in objects:
        obj.draw(screen)

    lasttick = curtick