This commit is contained in:
jona605a
2020-08-07 01:20:08 +02:00
10 changed files with 138 additions and 17 deletions

View File

@ -1,10 +1,10 @@
"""A collection of all Gwendolyn functions."""
__all__ = ["helloFunc", "cap", "imageFunc", "logThis", "findWikiPage", "makeFiles", "emojiToCommand", "fiarReactionTest", "deleteGame", "stopServer", "checkBalance", "giveMoney", "addMoney", "triviaCountPoints", "triviaStart", "triviaAnswer", "blackjackShuffle", "blackjackStart", "blackjackPlayerDrawHand", "blackjackContinue", "blackjackFinish", "blackjackHit", "blackjackStand", "blackjackDouble", "blackjackSplit", "parseFourInARow", "fourInARowAI", "spellFunc", "monsterFunc", "nameGen", "tavernGen", "movieFunc", "roll_dice", "parseChar", "parseRoll", "critRoll", "parseDestiny", "parseHex", "addToDict", "getName", "getID", "replaceMultiple", "hexAI", "parseMonopoly", "monopolyContinue", "monopolyReactionTest","parseInvest"]
__all__ = ["helloFunc", "cap", "imageFunc", "logThis", "findWikiPage", "makeFiles", "emojiToCommand", "fiarReactionTest", "deleteGame", "stopServer", "checkBalance", "giveMoney", "addMoney", "triviaCountPoints", "triviaStart", "triviaAnswer", "blackjackShuffle", "blackjackStart", "blackjackPlayerDrawHand", "blackjackContinue", "blackjackFinish", "blackjackHit", "blackjackStand", "blackjackDouble", "blackjackSplit", "spellFunc", "monsterFunc", "nameGen", "tavernGen", "movieFunc", "roll_dice", "parseChar", "parseRoll", "critRoll", "parseDestiny", "addToDict", "getName", "getID", "replaceMultiple", "monopolyReactionTest","parseInvest", "blackjackLoop", "fiar", "runMonopoly", "runHex"]
from .miscFuncs import helloFunc, cap, imageFunc, logThis, findWikiPage, makeFiles, replaceMultiple, emojiToCommand, fiarReactionTest, deleteGame, stopServer, addToDict, getName, getID, monopolyReactionTest
from .games import checkBalance, giveMoney, addMoney, triviaCountPoints, triviaStart, triviaAnswer, blackjackShuffle, blackjackStart, blackjackPlayerDrawHand, blackjackContinue, blackjackFinish, blackjackHit, blackjackStand, blackjackDouble, blackjackSplit, parseFourInARow, fourInARowAI, parseHex, hexAI, parseMonopoly, monopolyContinue, parseInvest
from .games import checkBalance, giveMoney, addMoney, triviaCountPoints, triviaStart, triviaAnswer, blackjackShuffle, blackjackStart, blackjackPlayerDrawHand, blackjackContinue, blackjackFinish, blackjackHit, blackjackStand, blackjackDouble, blackjackSplit, parseInvest, blackjackLoop, fiar, runMonopoly, runHex
from .lookup import spellFunc, monsterFunc

View File

@ -1,11 +1,9 @@
"""Functions for games Gwendolyn can play."""
__all__ = ["checkBalance", "giveMoney", "addMoney","triviaCountPoints", "triviaStart", "triviaAnswer", "blackjackShuffle", "blackjackStart", "blackjackPlayerDrawHand", "blackjackContinue", "blackjackFinish", "blackjackHit", "blackjackStand", "blackjackDouble", "blackjackSplit", "parseFourInARow", "fourInARowAI", "parseHex", "hexAI", "parseMonopoly", "monopolyContinue","parseInvest"]
__all__ = ["checkBalance", "giveMoney", "addMoney","triviaCountPoints", "triviaStart", "triviaAnswer", "blackjackShuffle", "blackjackStart", "blackjackPlayerDrawHand", "blackjackContinue", "blackjackFinish", "blackjackHit", "blackjackStand", "blackjackDouble", "blackjackSplit", "parseInvest", "blackjackLoop", "fiar", "runMonopoly", "runHex"]
from .money import checkBalance, giveMoney, addMoney
from .trivia import triviaCountPoints, triviaStart, triviaAnswer
from .blackjack import blackjackShuffle, blackjackStart, blackjackPlayerDrawHand, blackjackContinue, blackjackFinish, blackjackHit, blackjackStand, blackjackDouble, blackjackSplit
from .fourInARow import parseFourInARow, fourInARowAI
from .hex import parseHex, hexAI
from .monopoly import parseMonopoly, monopolyContinue
from .invest import parseInvest
from .gameLoops import blackjackLoop, fiar, runMonopoly, runHex

236
funcs/games/gameLoops.py Normal file
View File

@ -0,0 +1,236 @@
import asyncio
import discord
import json
from funcs import logThis, deleteGame
from .money import addMoney
from .fourInARow import parseFourInARow, fourInARowAI
from .blackjack import blackjackContinue, blackjackFinish
from .hex import parseHex, hexAI
from .monopoly import parseMonopoly, monopolyContinue
# Deletes a message
async def deleteMessage(imageLocation,channel):
try:
logThis("Finding old image")
with open("resources/games/oldImages/"+imageLocation, "r") as f:
oldImage = await channel.fetch_message(int(f.read()))
logThis("Deleting old image")
await oldImage.delete()
except:
oldImage = ""
return oldImage
# Runs Hex
async def runHex(channel,command,user):
try:
response, showImage, deleteImage, gameDone, gwendoTurn = parseHex(command,str(channel.id),user)
except:
logThis("Error parsing command (error code 1510)")
await channel.send(response)
logThis(response,str(channel.id))
if showImage:
if deleteImage:
try:
oldImage = await deleteMessage("hex"+str(channel.id),channel)
except:
logThis("Error deleting old image (error code 1501)")
oldImage = await channel.send(file = discord.File("resources/games/hexBoards/board"+str(channel.id)+".png"))
if not gameDone:
if gwendoTurn:
try:
response, showImage, deleteImage, gameDone, gwendoTurn = hexAI(str(channel.id))
except:
logThis("AI error (error code 1520)")
await channel.send(response)
logThis(response,str(channel.id))
if showImage:
if deleteImage:
await oldImage.delete()
oldImage = await channel.send(file = discord.File("resources/games/hexBoards/board"+str(channel.id)+".png"))
else:
with open("resources/games/oldImages/hex"+str(channel.id), "w") as f:
f.write(str(oldImage.id))
if gameDone:
with open("resources/games/games.json", "r") as f:
data = json.load(f)
try:
with open("resources/games/oldImages/hex"+str(channel.id), "r") as f:
oldImage = await channel.fetch_message(int(f.read()))
await oldImage.delete()
except:
logThis("The old image was already deleted")
winner = data["hex games"][str(channel.id)]["winner"]
if winner != 0:
addMoney(data["hex games"][str(channel.id)]["players"][winner-1].lower(),20)
deleteGame("hex games",str(channel.id))
# Runs Four in a Row
async def fiar(channel,command,user):
try:
response, showImage, deleteImage, gameDone, gwendoTurn = parseFourInARow(command,str(channel.id),user)
except:
logThis("Error parsing command (error code 1410)")
await channel.send(response)
logThis(response,str(channel.id))
if showImage:
if deleteImage:
try:
oldImage = await deleteMessage("fourInARow"+str(channel.id),channel)
except:
logThis("Error deleting message (error code 1401)")
oldImage = await channel.send(file = discord.File("resources/games/4InARowBoards/board"+str(channel.id)+".png"))
if gameDone == False:
if gwendoTurn:
try:
response, showImage, deleteImage, gameDone, gwendoTurn = fourInARowAI(str(channel.id))
except:
logThis("AI error (error code 1420)")
await channel.send(response)
logThis(response,str(channel.id))
if showImage:
if deleteImage:
await oldImage.delete()
oldImage = await channel.send(file = discord.File("resources/games/4InARowBoards/board"+str(channel.id)+".png"))
if gameDone == False:
with open("resources/games/oldImages/fourInARow"+str(channel.id), "w") as f:
f.write(str(oldImage.id))
try:
reactions = ["1","2","3","4","5","6","7"]
for reaction in reactions:
await oldImage.add_reaction(reaction)
except:
logThis("Image deleted before I could react to all of them")
else:
with open("resources/games/oldImages/fourInARow"+str(channel.id), "w") as f:
f.write(str(oldImage.id))
try:
reactions = ["1","2","3","4","5","6","7"]
for reaction in reactions:
await oldImage.add_reaction(reaction)
except:
logThis("Image deleted before I could react to all of them")
if gameDone:
with open("resources/games/games.json", "r") as f:
data = json.load(f)
try:
with open("resources/games/oldImages/fourInARow"+str(channel.id), "r") as f:
oldImage = await channel.fetch_message(int(f.read()))
await oldImage.delete()
except:
logThis("The old image was already deleted")
winner = data["4 in a row games"][str(channel.id)]["winner"]
difficulty = int(data["4 in a row games"][str(channel.id)]["difficulty"])
reward = difficulty**2 + 5
if winner != 0:
if data["4 in a row games"][str(channel.id)]["players"][winner-1].lower() != "gwendolyn":
addMoney(data["4 in a row games"][str(channel.id)]["players"][winner-1].lower(),reward)
with open("resources/games/games.json", "r") as f:
data = json.load(f) #why is this here?
deleteGame("4 in a row games",str(channel.id))
# Loop of blackjack game rounds
async def blackjackLoop(channel,gameRound,gameID):
logThis("Loop "+str(gameRound),str(channel.id))
with open("resources/games/oldImages/blackjack"+str(channel.id), "r") as f:
oldImage = await channel.fetch_message(int(f.read()))
new_message, allStanding, gamedone = blackjackContinue(str(channel.id))
if new_message != "":
logThis(new_message,str(channel.id))
await channel.send(new_message)
if gamedone == False:
await oldImage.delete()
oldImage = await channel.send(file = discord.File("resources/games/blackjackTables/blackjackTable"+str(channel.id)+".png"))
with open("resources/games/oldImages/blackjack"+str(channel.id), "w") as f:
f.write(str(oldImage.id))
try:
if allStanding:
await asyncio.sleep(5)
else:
await asyncio.sleep(120)
except:
logThis("Loop "+str(gameRound)+" interrupted (error code 1321)")
with open("resources/games/games.json", "r") as f:
data = json.load(f)
if str(channel.id) in data["blackjack games"]:
realRound = data["blackjack games"][str(channel.id)]["round"]
realGameID = data["blackjack games"][str(channel.id)]["id"]
if gameRound == realRound and realGameID == gameID:
if gamedone == False:
logThis("Loop "+str(gameRound)+" calling blackjackLoop()",str(channel.id))
await blackjackLoop(channel,gameRound+1,gameID)
else:
try:
new_message = blackjackFinish(str(channel.id))
except:
logThis("Something fucked up (error code 1310)")
await channel.send(new_message)
else:
logThis("Ending loop on round "+str(gameRound),str(channel.id))
else:
logThis("Ending loop on round "+str(gameRound),str(channel.id))
async def runMonopoly(channel, command, user):
try:
response, showImage, deleteImage, gameStarted, gameContinue = parseMonopoly(command,str(channel.id),user)
except:
logThis("Error parsing command (error code 1610)")
if response != "":
await channel.send(response)
logThis(response,str(channel.id))
if showImage:
if deleteImage:
try:
oldImage = await deleteMessage("monopoly"+str(channel.id),channel)
except:
logThis("Error deleting message (error code 1601)")
oldImage = await channel.send(file = discord.File("resources/games/monopolyBoards/monopolyBoard"+str(channel.id)+".png"))
with open("resources/games/oldImages/monopoly"+str(channel.id), "w") as f:
f.write(str(oldImage.id))
if gameContinue:
if gameStarted:
await asyncio.sleep(60)
else:
await asyncio.sleep(3)
response, showImage, deleteImage, gameDone = monopolyContinue(str(channel.id))
em = discord.Embed(description=response,colour = 0x59f442)
await channel.send(embed=em)
if showImage:
if deleteImage:
try:
oldImage = await deleteMessage("monopoly"+str(channel.id),channel)
except:
logThis("Error deleting message (error code 1601)")
oldImage = await channel.send(file = discord.File("resources/games/monopolyBoards/monopolyBoard"+str(channel.id)+".png"))
with open("resources/games/oldImages/monopoly"+str(channel.id), "w") as f:
f.write(str(oldImage.id))
if gameDone == False:
try:
await oldImage.add_reaction("🎲")
except:
logThis("Image deleted before I could react to all of them")

View File

@ -1,4 +1,7 @@
import finnhub
import finnhub, json
from funcs import getName
from .money import checkBalance, addMoney
finnhubClient = finnhub.Client(api_key = "bsm16nvrh5rdb4ara3j0")
@ -7,11 +10,95 @@ def getPrice(symbol : str):
if res == {}:
return 0
else:
print(res)
return int(res["c"] * 100)
def getPortfolio(user : str):
return None
with open("resources/games/investments.json") as f:
data = json.load(f)
if user not in data or data[user] == {}:
return f"{getName(user)} does not have a stock portfolio."
else:
portfolio = f"**Stock portfolio for {getName(user)}**"
for key, value in list(data[user].items()):
purchaseValue = value["purchased for"]
currentValue = int((getPrice(key) / value["value at purchase"]) * value["purchased"])
if purchaseValue == "?":
portfolio += f"\n**{key}**: ___{str(currentValue)} GwendoBucks___"
else:
portfolio += f"\n**{key}**: ___{str(currentValue)} GwendoBucks___ (purchased for {str(purchaseValue)})"
return portfolio
def buyStock(user : str, stock : str, buyAmount : int):
if buyAmount >= 100:
if checkBalance(user) >= buyAmount:
stockPrice = getPrice(stock)
if stockPrice > 0:
with open("resources/games/investments.json", "r") as f:
data = json.load(f)
addMoney(user,-1*buyAmount)
stock = stock.upper()
if user in data:
if stock in data[user]:
value = data[user][stock]
newAmount = int((stockPrice / value["value at purchase"]) * value["purchased"]) + buyAmount
data[user][stock]["value at purchase"] = stockPrice
data[user][stock]["purchased"] = newAmount
if value["purchased for"] != "?":
data[user][stock]["purchased for"] += buyAmount
else:
data[user][stock] = {"purchased" : buyAmount, "value at purchase" : stockPrice, "purchased for" : buyAmount}
else:
data[user] = {stock : {"purchased" : buyAmount, "value at purchase" : stockPrice, "purchased for" : buyAmount}}
with open("resources/games/investments.json", "w") as f:
json.dump(data,f,indent=4)
return f"{getName(user)} bought {buyAmount} GwendoBucks worth of {stock} stock"
else:
return f"{stock} is not traded on the american market."
else:
return "You don't have enough money for that"
else:
return "You cannot buy stocks for less than 100 GwendoBucks"
def sellStock(user : str, stock : str, sellAmount : int):
if sellAmount > 0:
with open("resources/games/investments.json", "r") as f:
data = json.load(f)
stock = stock.upper()
if user in data and stock in data[user]:
value = data[user][stock]
stockPrice = getPrice(stock)
data[user][stock]["purchased"] = int((stockPrice / value["value at purchase"]) * value["purchased"])
data[user][stock]["value at purchase"] = stockPrice
if value["purchased"] >= sellAmount:
addMoney(user,sellAmount)
if sellAmount < value["purchased"]:
data[user][stock]["purchased"] -= sellAmount
data[user][stock]["purchased for"] = "?"
else:
del data[user][stock]
with open("resources/games/investments.json", "w") as f:
json.dump(data,f,indent=4)
return f"{getName(user)} sold {sellAmount} GwendoBucks worth of {stock} stock"
else:
return f"You don't have enough {stock} stocks to do that"
else:
return f"You don't have any {stock} stock"
else:
return "no"
def parseInvest(content: str, user : str):
if content.startswith("check"):
@ -23,4 +110,25 @@ def parseInvest(content: str, user : str):
if price == 0:
return f"{commands[1].upper()} is not traded on the american market."
else:
return "The current "+commands[1].upper()+" stock is valued at **"+str(price)+"** GwendoBucks"
price = f"{price:,}".replace(",",".")
return f"The current {commands[1].upper()} stock is valued at **{price}** GwendoBucks"
elif content.startswith("buy"):
commands = content.split(" ")
if len(commands) == 3:
try:
return buyStock(user,commands[1],int(commands[2]))
except:
return "The command must be given as \"!invest buy [stock] [amount of GwendoBucks to purchase with]\""
else:
return "You must give both a stock name and an amount of gwendobucks you wish to spend."
elif content.startswith("sell"):
commands = content.split(" ")
if len(commands) == 3:
try:
return sellStock(user,commands[1],int(commands[2]))
except:
return "The command must be given as \"!invest sell [stock] [amount of GwendoBucks to sell stocks for]\""
else:
return "You must give both a stock name and an amount of GwendoBucks you wish to sell stocks for."