Moved draw classes to the game files

This commit is contained in:
NikolajDanger
2021-04-13 18:46:57 +02:00
parent b2530f1b4b
commit ea9579a534
8 changed files with 791 additions and 799 deletions

View File

@ -1,13 +1,13 @@
import json, urllib, datetime, string, discord
import math, random
from .hangmanDraw import DrawHangman
apiUrl = "https://api.wordnik.com/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=5000&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=3&maxLength=11&limit=1&api_key="
from PIL import ImageDraw, Image, ImageFont
class Hangman():
def __init__(self,bot):
self.bot = bot
self.draw = DrawHangman(bot)
self.APIURL = "https://api.wordnik.com/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=5000&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=3&maxLength=11&limit=1&api_key="
async def start(self, ctx):
await self.bot.defer(ctx)
@ -21,7 +21,7 @@ class Hangman():
apiKey = self.bot.credentials.wordnikKey
word = "-"
while "-" in word or "." in word:
with urllib.request.urlopen(apiUrl+apiKey) as p:
with urllib.request.urlopen(self.APIURL+apiKey) as p:
word = list(json.load(p)[0]["word"].upper())
self.bot.log("Found the word \""+"".join(word)+"\"")
guessed = [False] * len(word)
@ -162,4 +162,246 @@ class Hangman():
emoji = chr(ord(letter)+127397)
await message.add_reaction(emoji)
class DrawHangman():
def __init__(self,bot):
self.bot = bot
self.CIRCLESIZE = 120
self.LINEWIDTH = 12
self.BODYSIZE =210
self.LIMBSIZE = 60
self.ARMPOSITION = 60
self.MANX = (self.LIMBSIZE*2)+self.LINEWIDTH*4
self.MANY = (self.CIRCLESIZE+self.BODYSIZE+self.LIMBSIZE)+self.LINEWIDTH*4
self.LETTERLINELENGTH = 90
self.LETTERLINEDISTANCE = 30
self.GALLOWX, self.GALLOWY = 360,600
self.GOLDENRATIO = 1-(1 / ((1 + 5 ** 0.5) / 2))
LETTERSIZE = 75
TEXTSIZE = 70
self.FONT = ImageFont.truetype('resources/fonts/comic-sans-bold.ttf', LETTERSIZE)
self.SMALLFONT = ImageFont.truetype('resources/fonts/comic-sans-bold.ttf', TEXTSIZE)
def calcDeviance(self,preDev,preDevAcc,posChange,maxmin,maxAcceleration):
devAcc = preDevAcc + random.uniform(-posChange,posChange)
if devAcc > maxmin * maxAcceleration: devAcc = maxmin * maxAcceleration
elif devAcc < -maxmin * maxAcceleration: devAcc = -maxmin * maxAcceleration
dev = preDev + devAcc
if dev > maxmin: dev = maxmin
elif dev < -maxmin: dev = -maxmin
return dev, devAcc
def badCircle(self):
background = Image.new("RGBA",(self.CIRCLESIZE+(self.LINEWIDTH*3),self.CIRCLESIZE+(self.LINEWIDTH*3)),color=(0,0,0,0))
d = ImageDraw.Draw(background,"RGBA")
middle = (self.CIRCLESIZE+(self.LINEWIDTH*3))/2
devx = 0
devy = 0
devAccx = 0
devAccy = 0
start = random.randint(-100,-80)
degreesAmount = 360 + random.randint(-10,30)
for degree in range(degreesAmount):
devx, devAccx = self.calcDeviance(devx,devAccx,self.LINEWIDTH/100,self.LINEWIDTH,0.03)
devy, devAccy = self.calcDeviance(devy,devAccy,self.LINEWIDTH/100,self.LINEWIDTH,0.03)
x = middle + (math.cos(math.radians(degree+start)) * (self.CIRCLESIZE/2)) - (self.LINEWIDTH/2) + devx
y = middle + (math.sin(math.radians(degree+start)) * (self.CIRCLESIZE/2)) - (self.LINEWIDTH/2) + devy
d.ellipse([(x,y),(x+self.LINEWIDTH,y+self.LINEWIDTH)],fill=(0,0,0,255))
return background
def badLine(self, length, rotated = False):
if rotated:
w, h = length+self.LINEWIDTH*3, self.LINEWIDTH*3
else:
w, h = self.LINEWIDTH*3,length+self.LINEWIDTH*3
background = Image.new("RGBA",(w,h),color=(0,0,0,0))
d = ImageDraw.Draw(background,"RGBA")
devx = random.randint(-int(self.LINEWIDTH/3),int(self.LINEWIDTH/3))
devy = 0
devAccx = 0
devAccy = 0
for pixel in range(length):
devx, devAccx = self.calcDeviance(devx,devAccx,self.LINEWIDTH/1000,self.LINEWIDTH,0.004)
devy, devAccy = self.calcDeviance(devy,devAccy,self.LINEWIDTH/1000,self.LINEWIDTH,0.004)
if rotated:
x = self.LINEWIDTH + pixel + devx
y = self.LINEWIDTH + devy
else:
x = self.LINEWIDTH + devx
y = self.LINEWIDTH + pixel + devy
d.ellipse([(x,y),(x+self.LINEWIDTH,y+self.LINEWIDTH)],fill=(0,0,0,255))
return background
def drawMan(self, misses):
background = Image.new("RGBA",(self.MANX,self.MANY),color=(0,0,0,0))
if misses >= 1:
head = self.badCircle()
background.paste(head,(int((self.MANX-(self.CIRCLESIZE+(self.LINEWIDTH*3)))/2),0),head)
if misses >= 2:
body = self.badLine(self.BODYSIZE)
background.paste(body,(int((self.MANX-(self.LINEWIDTH*3))/2),self.CIRCLESIZE),body)
if misses >= 3:
limbs = random.sample(["rl","ll","ra","la"],min(misses-2,4))
else: limbs = []
for limb in limbs:
if limb == "ra":
limbDrawing = self.badLine(self.LIMBSIZE,True)
rotation = random.randint(-45,45)
xpos = int((self.MANX-(self.LINEWIDTH*3))/2)
rotationCompensation = min(-int(math.sin(math.radians(rotation))*(self.LIMBSIZE+(self.LINEWIDTH*3))),0)
ypos = self.CIRCLESIZE+self.ARMPOSITION + rotationCompensation
limbDrawing = limbDrawing.rotate(rotation,expand=1)
background.paste(limbDrawing,(xpos,ypos),limbDrawing)
elif limb == "la":
limbDrawing = self.badLine(self.LIMBSIZE,True)
rotation = random.randint(-45,45)
xpos = int((self.MANX-(self.LINEWIDTH*3))/2)-self.LIMBSIZE
rotationCompensation = min(int(math.sin(math.radians(rotation))*(self.LIMBSIZE+(self.LINEWIDTH*3))),0)
ypos = self.CIRCLESIZE+self.ARMPOSITION + rotationCompensation
limbDrawing = limbDrawing.rotate(rotation,expand=1)
background.paste(limbDrawing,(xpos,ypos),limbDrawing)
elif limb == "rl":
limbDrawing = self.badLine(self.LIMBSIZE,True)
rotation = random.randint(-15,15)
xpos = int((self.MANX-(self.LINEWIDTH*3))/2)-self.LINEWIDTH
ypos = self.CIRCLESIZE+self.BODYSIZE-self.LINEWIDTH
limbDrawing = limbDrawing.rotate(rotation-45,expand=1)
background.paste(limbDrawing,(xpos,ypos),limbDrawing)
elif limb == "ll":
limbDrawing = self.badLine(self.LIMBSIZE,True)
rotation = random.randint(-15,15)
limbDrawing = limbDrawing.rotate(rotation+45,expand=1)
xpos = int((self.MANX-(self.LINEWIDTH*3))/2)-limbDrawing.size[0]+self.LINEWIDTH*3
ypos = self.CIRCLESIZE+self.BODYSIZE
background.paste(limbDrawing,(xpos,ypos),limbDrawing)
return background
def badText(self, text, big, color=(0,0,0,255)):
if big: font = self.FONT
else: font = self.SMALLFONT
w, h = font.getsize(text)
img = Image.new("RGBA",(w,h),color=(0,0,0,0))
d = ImageDraw.Draw(img,"RGBA")
d.text((0,0),text,font=font,fill=color)
return img
def drawGallows(self):
background = Image.new("RGBA",(self.GALLOWX,self.GALLOWY),color=(0,0,0,0))
bottomLine = self.badLine(int(self.GALLOWX*0.75),True)
background.paste(bottomLine,(int(self.GALLOWX*0.125),self.GALLOWY-(self.LINEWIDTH*4)),bottomLine)
lineTwo = self.badLine(self.GALLOWY-self.LINEWIDTH*6)
background.paste(lineTwo,(int(self.GALLOWX*(0.75*self.GOLDENRATIO)),self.LINEWIDTH*2),lineTwo)
topLine = self.badLine(int(self.GALLOWY*0.30),True)
background.paste(topLine,(int(self.GALLOWX*(0.75*self.GOLDENRATIO))-self.LINEWIDTH,self.LINEWIDTH*3),topLine)
lastLine = self.badLine(int(self.GALLOWY*0.125))
background.paste(lastLine,((int(self.GALLOWX*(0.75*self.GOLDENRATIO))+int(self.GALLOWY*0.30)-self.LINEWIDTH),self.LINEWIDTH*3),lastLine)
return background
def drawLetterLines(self, word,guessed,misses):
letterLines = Image.new("RGBA",((self.LETTERLINELENGTH+self.LETTERLINEDISTANCE)*len(word),self.LETTERLINELENGTH+self.LINEWIDTH*3),color=(0,0,0,0))
for x, letter in enumerate(word):
line = self.badLine(self.LETTERLINELENGTH,True)
letterLines.paste(line,(x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE),self.LETTERLINELENGTH),line)
if guessed[x]:
letterDrawing = self.badText(letter,True)
letterWidth = self.FONT.getsize(letter)[0]
letterx = int(x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE)-(letterWidth/2)+(self.LETTERLINELENGTH*0.5)+(self.LINEWIDTH*2))
letterLines.paste(letterDrawing,(letterx,0),letterDrawing)
elif misses == 6:
letterDrawing = self.badText(letter,True,(242,66,54))
letterWidth = self.FONT.getsize(letter)[0]
letterx = int(x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE)-(letterWidth/2)+(self.LETTERLINELENGTH*0.5)+(self.LINEWIDTH*2))
letterLines.paste(letterDrawing,(letterx,0),letterDrawing)
return letterLines
def shortestDist(self,positions,newPosition):
shortestDist = math.inf
x, y = newPosition
for i, j in positions:
xdist = abs(i-x)
ydist = abs(j-y)
dist = math.sqrt(xdist**2+ydist**2)
if shortestDist > dist: shortestDist = dist
return shortestDist
def drawMisses(self,guesses,word):
background = Image.new("RGBA",(600,400),color=(0,0,0,0))
pos = []
for guess in guesses:
if guess not in word:
placed = False
while placed == False:
letter = self.badText(guess,True)
w, h = self.FONT.getsize(guess)
x = random.randint(0,600-w)
y = random.randint(0,400-h)
if self.shortestDist(pos,(x,y)) > 70:
pos.append((x,y))
background.paste(letter,(x,y),letter)
placed = True
return background
def drawImage(self,channel):
self.bot.log("Drawing hangman image", channel)
game = self.bot.database["hangman games"].find_one({"_id":channel})
random.seed(game["game ID"])
background = Image.open("resources/paper.jpg")
try:
gallow = self.drawGallows()
except:
self.bot.log("Error drawing gallows (error code 1711)")
try:
man = self.drawMan(game["misses"])
except:
self.bot.log("Error drawing stick figure (error code 1712)")
random.seed(game["game ID"])
try:
letterLines = self.drawLetterLines(game["word"],game["guessed"],game["misses"])
except:
self.bot.log("error drawing letter lines (error code 1713)")
random.seed(game["game ID"])
try:
misses = self.drawMisses(game["guessed letters"],game["word"])
except:
self.bot.log("Error drawing misses (error code 1714)")
background.paste(gallow,(100,100),gallow)
background.paste(man,(300,210),man)
background.paste(letterLines,(120,840),letterLines)
background.paste(misses,(600,150),misses)
missesText = self.badText("MISSES",False)
missesTextWidth = missesText.size[0]
background.paste(missesText,(850-int(missesTextWidth/2),50),missesText)
background.save("resources/games/hangmanBoards/hangmanBoard"+channel+".png")