コード例 #1
0
    async def add(self, ctx, *args):
        """<amt> <card> to add cards to your deck."""
        if not (await is_invoker_registered(ctx)):
            return

        # Syntax
        try:
            card = ' '.join(args[1:])
            amt = int(args[0])
        except:
            await ctx.message.channel.send(
                "Incorrect syntax. =add <amount> <card name>")
            return

        collection = getPlyData(ctx.message.author)['collection']
        playerData = getPlyData(ctx.message.author)
        idx = playerData['selectedDeck']
        deckList = playerData['decks'][idx]

        # Make sure we have the card to add
        cardPair = None
        for item in collection.items():
            if card.lower() == item[0].lower():
                cardPair = item

        testers = [
            '135526460881502209',
            '128216983605870603',
        ]
        if cardPair == None and ctx.message.author.id not in testers:
            await ctx.message.channel.send(
                "This card isn't in your collection.")
            return
        if cardPair[1] < amt and ctx.message.author.id not in testers:
            await ctx.message.channel.send(
                "You don't have that many of that card in your collection.")
            return
        if Counter(deckList)[cardPair[0]] + amt > 3:
            await ctx.message.channel.send(
                "You can only have 3 of a card in your deck.")
            return

        # Add the card
        for _ in range(amt):
            deckList.append(cardPair[0])

        # Save
        with open('player_data/' + str(ctx.message.author.id) + '.txt',
                  'r') as json_file:
            fileContents = json.loads(json_file.read())
        fileContents['decks'][idx] = deckList
        with open('player_data/' + str(ctx.message.author.id) + '.txt',
                  'w') as outfile:
            json.dump(fileContents, outfile)

        await ctx.message.channel.send(
            "Successfully added card(s) to your current deck.")
コード例 #2
0
	def bulkadd( self, ctx, *args ):
		"""Add many cards to your deck at once."""
		#user interaction
		yield from ctx.message.channel.send( "On each line, write <number>x <cardname>. For example:\n2x Caltrops\n1x Ambush" )
		message = yield from self.bot.wait_for( 'message', check=lambda message: message.author == ctx.message.author, timeout=400 )
		
		#parsing
		messageList = message.content.split( '\n' )
		for idx,line in enumerate(messageList):
			messageList[idx] = line.split( 'x ' )
		
		#has data check + data retrieval
		try:
			collection = getPlyData( ctx.message.author )['collection']
			playerData = getPlyData(ctx.message.author)
			idx = playerData['selectedDeck']
			deckList = playerData['decks'][idx]
		except:
			yield from ctx.message.channel.send( "You aren't registered yet. Type =register" )
			return
			
		for cardEntry in messageList: #for each [2, "caltrops"], for example
			cardPair = None
			#formatting and data getting
			try:
				for item in collection.items():
					if cardEntry[1].lower() == item[0].lower():
						cardPair = item
			except:
				yield from ctx.message.channel.send( "Invalid format!" )
				return
			
			#checks
			if cardPair == None:
				yield from ctx.message.channel.send( cardEntry[1] + " isn't in your collection. Exiting bulkadd." )
				return
			if cardPair[1] < int(cardEntry[0]):
				yield from ctx.message.channel.send( "You don't have that many "+cardEntry[1]+" in your collection. Exiting bulkadd." )
				return
			if Counter(deckList)[cardPair[0]] + int(cardEntry[0]) > 3:
				yield from ctx.message.channel.send( "You can only have 3 of a card in your deck. ("+cardPair[0]+") Exiting bulkadd." )
				return
				
			#actually add it
			for _ in range( int(cardEntry[0]) ):
				deckList.append( cardPair[0] )
			
		#save
		with open('player_data/'+str(ctx.message.author.id)+'.txt', 'r') as json_file: 
			fileContents = json.loads(json_file.read())
		fileContents['decks'][idx] = deckList
		with open('player_data/'+str(ctx.message.author.id)+'.txt', 'w') as outfile:
			json.dump(fileContents, outfile)
			
		yield from ctx.message.channel.send( "Successfully added card(s) to your current deck." )
コード例 #3
0
    async def remove(self, ctx, *args):
        """<amt> <card> to remove cards from your deck."""

        if not (await is_invoker_registered(ctx)):
            return

        # Syntax
        try:
            card = ' '.join(args[1:])
            amt = int(args[0])
        except:
            await ctx.message.channel.send(
                "Incorrect syntax. =remove <amount> <cardname>")
            return

        playerData = getPlyData(ctx.message.author)
        idx = playerData['selectedDeck']
        deckList = playerData['decks'][idx]
        deck = Counter(deckList)

        # Make sure we have the card to remove
        cardPair = None
        for item in deck.items():
            if card.lower() == item[0].lower():
                cardPair = item

        if cardPair == None:
            await ctx.message.channel.send("This card isn't in your deck.")
            return
        if cardPair[1] < amt:
            await ctx.message.channel.send(
                "You don't have that many of that card in your deck.")
            return

        # Remove the card
        for _ in range(amt):
            deckList.remove(cardPair[0])

        # Save
        with open('player_data/' + str(ctx.message.author.id) + '.txt',
                  'r') as json_file:
            fileContents = json.loads(json_file.read())
        fileContents['decks'][idx] = deckList
        with open('player_data/' + str(ctx.message.author.id) + '.txt',
                  'w') as outfile:
            json.dump(fileContents, outfile)

        await ctx.message.channel.send(
            "Successfully removed card(s) from your current deck.")
コード例 #4
0
	def clear( self, ctx, *args ):
		"""Removes all cards from your current deck."""
		try:
			playerData = getPlyData(ctx.message.author)
			idx = playerData['selectedDeck']
			selectedDeck = playerData['decks'][idx]
		except:
			yield from ctx.message.channel.send( "You aren't registered yet. Type =register" )
			return
			
		deckList = []
		with open('player_data/'+str(ctx.message.author.id)+'.txt', 'r') as json_file: 
			fileContents = json.loads(json_file.read())
		fileContents['decks'][idx] = deckList
		with open('player_data/'+str(ctx.message.author.id)+'.txt', 'w') as outfile:
			json.dump(fileContents, outfile)
			
		yield from ctx.message.channel.send( "Successfully cleared your current decklist." )
コード例 #5
0
	def collection( self, ctx, *args ):
		"""Gets your collection. Try doing this in DMs."""
		stringToPrint = ""
		i=0
		try:
			for key,val in getPlyData( ctx.message.author )['collection'].items():
				stringToPrint = stringToPrint + ( str(val) + "x " + str(cardList[key.lower()]) + "\n" )
				i+=1
				if i>=10:
					i=0
					yield from ctx.message.author.send( stringToPrint )
					stringToPrint = ""
			if not stringToPrint == "":
				yield from ctx.message.author.send( stringToPrint )
		except Exception as e:
			print(e)
			yield from ctx.message.channel.send( "You aren't registered yet! Use =register." )
			return
コード例 #6
0
    async def collection(self, ctx, *args):
        """Gets your collection. Try doing this in DMs."""

        if not (await is_invoker_registered(ctx)):
            return

        stringToPrint = ""
        i = 0

        for key, val in getPlyData(ctx.message.author)['collection'].items():
            stringToPrint = stringToPrint + (str(val) + "x " +
                                             str(cardList[key.lower()]) + "\n")
            i += 1
            if i >= 10:
                i = 0
                await ctx.message.author.send(stringToPrint)
                stringToPrint = ""
        if not stringToPrint == "":
            await ctx.message.author.send(stringToPrint)
コード例 #7
0
    async def clear(self, ctx, *args):
        """Removes all cards from your current deck."""

        if not (await is_invoker_registered(ctx)):
            return

        playerData = getPlyData(ctx.message.author)
        idx = playerData['selectedDeck']
        selectedDeck = playerData['decks'][idx]

        deckList = []
        with open('player_data/' + str(ctx.message.author.id) + '.txt',
                  'r') as json_file:
            fileContents = json.loads(json_file.read())
        fileContents['decks'][idx] = deckList
        with open('player_data/' + str(ctx.message.author.id) + '.txt',
                  'w') as outfile:
            json.dump(fileContents, outfile)

        await ctx.message.channel.send(
            "Successfully cleared your current decklist.")
コード例 #8
0
	def deck( self, ctx, *args ):
		"""Gets your decklist. Use this to save and modify lists. Try doing this in DMs."""
		stringToPrint = ""
		i=0
		try:
			playerData = getPlyData(ctx.message.author)
			idx = playerData['selectedDeck']
		except:
			yield from ctx.message.channel.send( "You aren't registered! Use =register" )
			return
		selectedDeck = playerData['decks'][idx]
		for key,val in Counter(selectedDeck).items():
			stringToPrint = stringToPrint + ( str(val) + "x " + key + "\n" )
			i+=1
			if i>=10:
				i=0
				yield from ctx.message.channel.send( stringToPrint )
				stringToPrint = ""
		if not stringToPrint == "":
			yield from ctx.message.channel.send( stringToPrint )
		yield from ctx.message.channel.send( str(len(selectedDeck)) + " cards in deck." )
コード例 #9
0
    async def deck(self, ctx, *args):
        """Gets your decklist. Use this to save and modify lists. Try doing this in DMs."""
        if not (await is_invoker_registered(ctx)):
            return

        stringToPrint = ""
        i = 0

        playerData = getPlyData(ctx.message.author)
        idx = playerData['selectedDeck']

        selectedDeck = playerData['decks'][idx]
        for key, val in Counter(selectedDeck).items():
            stringToPrint = stringToPrint + (str(val) + "x " + key + "\n")
            i += 1
            if i >= 10:
                i = 0
                await ctx.message.channel.send(stringToPrint)
                stringToPrint = ""
        if not stringToPrint == "":
            await ctx.message.channel.send(stringToPrint)
        await ctx.message.channel.send(
            str(len(selectedDeck)) + " cards in deck.")
コード例 #10
0
    async def showoff(self, ctx, *args):
        """Show off a card. And don't try to lie!"""

        if not (await is_invoker_registered(ctx)):
            return

        try:
            card = ' '.join(args)
            cardLower = card.lower()
        except:
            await ctx.message.channel.send(
                "Incorrect syntax. =showoff <cardname>")

        if cardLower in [
                x.lower()
                for x in getPlyData(ctx.message.author)['collection'].keys()
        ]:
            await ctx.message.channel.send(ctx.message.author.name +
                                           " has a shiny " + card + "!")
        else:
            await ctx.message.channel.send(ctx.message.author.name +
                                           " doesn't even have a " + card +
                                           ". What a loser!")
コード例 #11
0
    def showoff(self, ctx, *args):
        """Show off a card. And don't try to lie!"""
        try:
            card = ' '.join(args)
            cardLower = card.lower()
        except:
            yield from ctx.message.channel.send(
                "Incorrect syntax. =showoff <cardname>")

        try:
            if cardLower in [
                    x.lower() for x in getPlyData(ctx.message.author)
                ['collection'].keys()
            ]:
                yield from ctx.message.channel.send(ctx.message.author.name +
                                                    " has a shiny " + card +
                                                    "!")
            else:
                yield from ctx.message.channel.send(ctx.message.author.name +
                                                    " doesn't even have a " +
                                                    card + ". What a loser!")
        except:
            yield from ctx.message.channel.send(
                "You need to be registered to show stuff off. =register")
コード例 #12
0
ファイル: collecting.py プロジェクト: timswyzen/discordTCG
    async def trade(self, ctx, target: discord.Member = None, *args):
        """Trade with another user. =trade <@ user>"""

        if not (await is_invoker_registered(ctx)):
            return

        if target == None:
            await ctx.message.channel.send(
                "You must pick someone to trade with! Syntax: =trade <@ user>")
            return
        if ctx.message.author == target:
            await ctx.message.channel.send(
                "Why would you trade with yourself? :confounded:")
            return
        trader, tradee = [], []
        await ctx.message.channel.send(
            "Type 'quit' at any time to quit the trade menu.")
        await ctx.message.channel.send(
            "What are you offering? Syntax: <amount>x <card> or $<money amount>. For example:\n2x Voracity\n$20"
        )

        try:
            message = await self.bot.wait_for(
                'message',
                check=lambda message: message.author == ctx.message.author,
                timeout=90)
        except asyncio.exceptions.TimeoutError:
            ctx.message.channel.send(
                "Timed out waiting for response. Cancelling trade.")
            return

        if message.content.lower().startswith('quit'):
            await ctx.message.channel.send("Quit the trade menu.")
            return

        # Setting up data for trader's offerings
        messageList = message.content.split('\n')
        for idx, line in enumerate(messageList):
            messageList[idx] = line.split('x ')

        playerData = getPlyData(ctx.message.author)

        # Go through the cards and validate, then add to trade
        for cardEntry in messageList:  # for each [2, "caltrops"], for example
            cardPair = None
            # formatting and data getting
            if cardEntry[0][0] == '$':
                with open('player_data/' + str(ctx.message.author.id) + '.txt',
                          'r') as json_file:
                    traderMoney = json.loads(json_file.read())['money']
                if traderMoney < int(cardEntry[0][1:]) or int(
                        cardEntry[0][1:]) < 0:
                    await ctx.message.channel.send(
                        "You don't have enough money.")
                    return
                trader.append(cardEntry[0][1:])
            else:
                try:
                    for item in playerData['collection'].items():
                        if cardEntry[1].lower() == item[0].lower():
                            cardPair = item
                except:
                    await ctx.message.channel.send("Invalid format!")
                    return

                if cardPair == None:
                    await ctx.message.channel.send(
                        cardEntry[1] + " isn't in your collection.")
                    return
                if cardPair[1] < int(cardEntry[0]):
                    await ctx.message.channel.send(
                        "You don't have that many " + cardEntry[1] +
                        " in your collection.")
                    return

                trader.append(cardEntry)

        await ctx.message.channel.send(
            "What do you want in return? (same syntax)")

        try:
            message = await self.bot.wait_for(
                'message',
                check=lambda message: message.author == ctx.message.author,
                timeout=90)
        except asyncio.exceptions.TimeoutError:
            ctx.message.channel.send(
                "Timed out waiting for response. Cancelling trade.")
            return

        if message.content.lower().startswith('quit'):
            await ctx.message.channel.send("Quit the trade menu.")
            return

        # Setting up data for trader's offerings
        messageList = message.content.split('\n')
        for idx, line in enumerate(messageList):
            messageList[idx] = line.split('x ')

        # has data check + data retrieval
        try:
            playerData = getPlyData(target)
        except:
            await ctx.message.channel.send("Target isn't registered yet.")
            return

        # Go through cards and validate, then add to trade
        for cardEntry in messageList:  # for each [2, "caltrops"], for example
            cardPair = None
            # formatting and data getting
            if cardEntry[0][0] == '$':
                with open('player_data/' + str(target.id) + '.txt',
                          'r') as json_file:
                    tradeeMoney = json.loads(json_file.read())['money']
                if tradeeMoney < int(cardEntry[0][1:]) or int(
                        cardEntry[0][1:]) < 0:
                    await ctx.message.channel.send(
                        "He or she doesn't have enough money.")
                    return
                tradee.append(cardEntry[0][1:])
            else:
                try:
                    for item in playerData['collection'].items():
                        if cardEntry[1].lower() == item[0].lower():
                            cardPair = item
                except:
                    await ctx.message.channel.send("Invalid format!")
                    return

                if cardPair == None:
                    await ctx.message.channel.send(
                        cardEntry[1] + " isn't in your collection.")
                    return
                if cardPair[1] < int(cardEntry[0]):
                    await ctx.message.channel.send(
                        "You don't have that many " + cardEntry[1] +
                        " in your collection.")
                    return

                tradee.append(cardEntry)
        # wow that was a lot. let's get the other user's approval then do the trade now.
        print(str(trader) + " | " + str(tradee))

        def check(author):
            def inner_check(msg):
                return (msg.content.lower().startswith('yes')
                        or msg.content.lower().startswith('no')
                        ) and msg.author == author

        await ctx.message.channel.send(
            target.name + ": Do you accept the above trade? ('yes' or 'no')")
        try:
            message = await self.bot.wait_for('message',
                                              check=check(ctx.message.author),
                                              timeout=30)
        except asyncio.exceptions.TimeoutError:
            ctx.message.channel.send(
                "Timed out waiting for response. Cancelling trade.")
            return

        if message.content.lower().startswith('no'):
            await ctx.message.channel.send("Trade request denied.")
            return
        # Complete the trade
        elif message.content.lower().startswith('yes'):
            # give trader the tradee's stuff
            for item in tradee:
                if isinstance(item, str):
                    grantMoney(ctx.message.author.id, int(item))
                    grantMoney(target.id, -1 * int(item))
                else:
                    grantCard(target.id, item[1], -1 * int(item[0]))
                    grantCard(ctx.message.author.id, item[1], item[0])
            # give tradee the trader's stuff
            for item in trader:
                if isinstance(item, str):
                    grantMoney(ctx.message.author.id, -1 * int(item))
                    grantMoney(target.id, int(item))
                else:
                    grantCard(target.id, item[1], item[0])
                    grantCard(ctx.message.author.id, item[1],
                              -1 * int(item[0]))
            await ctx.message.channel.send("Trade complete!")
コード例 #13
0
def challenge(ctx, target: discord.Member = None, *args):
    """Challenge a friend to discordTCG! =challenge <@user> <wager>"""

    challengerID = ctx.message.author.id

    #Make sure neither player is in a game currently
    if challengerID in config.matches or target.id in config.matches:
        yield from bot.say("A player is already in a match.")
        return

    #Dont challenge yourself man
    if ctx.message.author == target:
        yield from bot.say("You can't challenge yourself, silly!")
        return

    #Have challenged guy accept
    yield from bot.say(
        target.name +
        ", you've been challenged to a discordTCG match! Type 'accept' to accept."
    )
    message = yield from bot.wait_for_message(author=target,
                                              content='accept',
                                              timeout=config.CHALLENGE_TIMEOUT)
    if message is None:
        yield from bot.say(ctx.message.author.name +
                           ", your challenge was not accepted :(")
        return

    #check again here for duplicate accepts
    if challengerID in config.matches or target.id in config.matches:
        yield from bot.say("A player is already in a match.")
        return

    #Get player data
    challengerDeck = mechanics.getPlyData(ctx.message.author)
    defenderDeck = mechanics.getPlyData(target)
    if defenderDeck is None or challengerDeck is None:
        yield from bot.say("Both players aren't registered! Use =register.")
        return
    challengerDeck = challengerDeck['decks'][challengerDeck['selectedDeck']]
    defenderDeck = defenderDeck['decks'][defenderDeck['selectedDeck']]
    if len(challengerDeck) < config.DECK_SIZE_MINIMUM or len(
            defenderDeck) < config.DECK_SIZE_MINIMUM:
        yield from bot.say("A player doesn't have at least " +
                           str(config.DECK_SIZE_MINIMUM) +
                           " cards in his or her deck.")
        return

    #Wager stuff
    try:
        wager = int(args[0])
        if mechanics.getBal(ctx.message.author.id) < wager or mechanics.getBal(
                target.id) < wager:
            yield from bot.say(
                "A player doesn't have enough money for this wager!")
            return
        yield from bot.say("Wager set to $" + args[0] + "!")
    except:
        wager = 0

    #Initialize game
    #TODO: [challenger] -> [ctx.message.author.id]
    config.matches[challengerID] = gamebase.TCGame(challengerID, target.id,
                                                   wager)
    config.matches[challengerID].chalObj = playerbase.Player(
        ctx.message.author.name, challengerDeck, [], bot, ctx)
    config.matches[challengerID].defObj = playerbase.Player(
        target.name, defenderDeck, [], bot, ctx)
    config.matches[challengerID].chalObj.shuffle()
    config.matches[challengerID].defObj.shuffle()
    for i in range(config.STARTING_HAND_SIZE):
        config.matches[challengerID].chalObj.drawCard()
        config.matches[challengerID].defObj.drawCard()
    config.matches[challengerID].chalObj.opponent = config.matches[
        challengerID].defObj
    config.matches[challengerID].defObj.opponent = config.matches[
        challengerID].chalObj
    print('A match has started. ' + str(ctx.message.author.name) + ' vs ' +
          str(target.name) + '!')

    #Start round
    if random.randint(0, 1) == 0:
        config.matches[challengerID].chalObj.active = True
        config.matches[challengerID].defObj.energy += 1
        yield from startRound(config.matches[challengerID], ctx.message.author,
                              config.matches[challengerID].chalObj, target,
                              config.matches[challengerID].defObj, ctx)
    else:
        config.matches[challengerID].defObj.active = True
        config.matches[challengerID].chalObj.energy += 1
        yield from startRound(config.matches[challengerID], target,
                              config.matches[challengerID].defObj,
                              ctx.message.author,
                              config.matches[challengerID].chalObj, ctx)