Format with Black

This commit is contained in:
c0de 2022-10-24 20:00:39 -05:00
parent 7d684d8b9d
commit 07ecd2248c
4 changed files with 52 additions and 38 deletions

View File

@ -8,16 +8,18 @@ import datetime
from peewee import * from peewee import *
# User can provide path to database, or it will be put next to main.py # User can provide path to database, or it will be put next to main.py
DATABASE = os.environ.get('database_path', os.getcwd() + '/ghostball.db') DATABASE = os.environ.get("database_path", os.getcwd() + "/ghostball.db")
database = SqliteDatabase(DATABASE) database = SqliteDatabase(DATABASE)
class BaseModel(Model): class BaseModel(Model):
"""All of our models will inherit this class """All of our models will inherit this class
and use the same database connection""" and use the same database connection"""
class Meta: class Meta:
database = database database = database
class GameModel(BaseModel): class GameModel(BaseModel):
game_id = UUIDField(primary_key=True) game_id = UUIDField(primary_key=True)
@ -27,10 +29,11 @@ class GameModel(BaseModel):
date_created = DateTimeField(default=datetime.datetime.now) date_created = DateTimeField(default=datetime.datetime.now)
date_ended = DateTimeField(null=True) date_ended = DateTimeField(null=True)
class GuessModel(BaseModel): class GuessModel(BaseModel):
player_id = IntegerField(primary_key=True) player_id = IntegerField(primary_key=True)
game_id = ForeignKeyField(GameModel, backref="guesses") game_id = ForeignKeyField(GameModel, backref="guesses")
player_name = CharField() player_name = CharField()
guess = IntegerField() guess = IntegerField()

View File

@ -7,11 +7,11 @@ import sys
import discord import discord
# Import game functions # Import game functions
sys.path.append('..') sys.path.append("..")
import game import game
class GhostBallClient(discord.Client):
class GhostBallClient(discord.Client):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(GhostBallClient, self).__init__(*args, **kwargs) super(GhostBallClient, self).__init__(*args, **kwargs)
@ -31,7 +31,7 @@ class GhostBallClient(discord.Client):
await message.channel.send("pong") await message.channel.send("pong")
# Game commands # Game commands
if message.content.startswith('!'): if message.content.startswith("!"):
firstword = message.content[1:].split()[0] firstword = message.content[1:].split()[0]
# Determine if the first word is a command, and run it # Determine if the first word is a command, and run it

View File

@ -8,29 +8,30 @@ import dateparser
from database.models import database, GameModel, GuessModel from database.models import database, GameModel, GuessModel
class Game: class Game:
""" """
The game state class The game state class
This represents a game that exists in a channel This represents a game that exists in a channel
""" """
def __enter__(self): def __enter__(self):
""" """
Allows use of `with Game as game` for try/except statements Allows use of `with Game as game` for try/except statements
We are using this instead of __init__, they work very similar We are using this instead of __init__, they work very similar
to each other (https://peps.python.org/pep-0343/) to each other (https://peps.python.org/pep-0343/)
""" """
# Only one game should run at at time # Only one game should run at at time
self.is_running = False self.is_running = False
self.commands = { self.commands = {
'ghostball': self.start, "ghostball": self.start,
'resolve': self.stop, "resolve": self.stop,
'guess': self.guess, "guess": self.guess,
'points': self.points, "points": self.points,
'help': self.help, "help": self.help,
} }
self.game = GameModel self.game = GameModel
@ -46,21 +47,24 @@ class Game:
def __exit__(self, exception_type, exception_value, exception_traceback): def __exit__(self, exception_type, exception_value, exception_traceback):
""" """
Automagically close the database Automagically close the database
when this class has ended execution when this class has ended execution
""" """
database.close() database.close()
async def check_is_running(method, start_new_game=True): async def check_is_running(method, start_new_game=True):
""" """
Decorator that determines if the game is running or not Decorator that determines if the game is running or not
""" """
async def wrapper(self): async def wrapper(self):
if self.is_running and start_new_game: if self.is_running and start_new_game:
return await self.message.channel.send("A game is already running") return await self.message.channel.send("A game is already running")
elif not self.is_running and not start_new_game: elif not self.is_running and not start_new_game:
return await self.message.channel.send("There is no game running to add guesses to") return await self.message.channel.send(
"There is no game running to add guesses to"
)
await method(self) await method(self)
@ -72,11 +76,12 @@ class Game:
# game.pitch_value is unknown at the start of the game # game.pitch_value is unknown at the start of the game
self.game = GameModel.create( self.game = GameModel.create(
game_id = uuid.uuid4(), game_id=uuid.uuid4(), server_id=self.message.guild.id
server_id = self.message.guild.id
) )
await self.message.send("@flappy ball, pitch is in! Send me your guesses with !guess <number>") await self.message.send(
"@flappy ball, pitch is in! Send me your guesses with !guess <number>"
)
def __stopArgs__(self): def __stopArgs__(self):
pieces = self.message.content.split() pieces = self.message.content.split()
@ -93,23 +98,27 @@ class Game:
# Determine arguments # Determine arguments
pitch_value, has_batter, batter_id, batter_guess = self.__stopArgs__() pitch_value, has_batter, batter_id, batter_guess = self.__stopArgs__()
if not pitch_value: if not pitch_value:
return await self.message.channel.send(f"Invalid command <@{ str(self.message.author.id) }>!") return await self.message.channel.send(
f"Invalid command <@{ str(self.message.author.id) }>!"
)
if has_batter: if has_batter:
player_id = batter_id[3:] player_id = batter_id[3:]
GuessModel.create( GuessModel.create(
game_id = self.game.game_id, game_id=self.game.game_id,
player_id = player_id, player_id=player_id,
player_name = self.discord.get_user(int(player_id).name), player_name=self.discord.get_user(int(player_id).name),
guess = int(batter_guess) guess=int(batter_guess),
) )
# Save the pitch value # Save the pitch value
self.game.update({'pitch_value': pitch_value}) self.game.update({"pitch_value": pitch_value})
# TODO: Determine differences # TODO: Determine differences
await self.message.channel.send("Difference calculation is not currently available") await self.message.channel.send(
"Difference calculation is not currently available"
)
# stop and discard game # stop and discard game
self.is_running = False self.is_running = False
@ -119,13 +128,15 @@ class Game:
async def guess(self): async def guess(self):
value = int(self.message.content.split()[1]) value = int(self.message.content.split()[1])
if value < 1 or value > 1000: if value < 1 or value > 1000:
return await self.message.channel.send(f"Invalid value. It must be between 1 and 1000 inclusive") return await self.message.channel.send(
f"Invalid value. It must be between 1 and 1000 inclusive"
)
GuessModel.create( GuessModel.create(
game_id = self.game.game_id, game_id=self.game.game_id,
player_id = self.message.author.id, player_id=self.message.author.id,
player_name = self.message.author.name, player_name=self.message.author.name,
guess = value guess=value,
) )
return await self.message.add_reaction(emoji="\N{THUMBS UP SIGN}") return await self.message.add_reaction(emoji="\N{THUMBS UP SIGN}")

View File

@ -8,9 +8,9 @@ from pathlib import Path
from discord_client.client import GhostBallClient from discord_client.client import GhostBallClient
from database.models import DATABASE, database, create_models from database.models import DATABASE, database, create_models
if __name__ == '__main__': if __name__ == "__main__":
client = GhostBallClient(intents=None) client = GhostBallClient(intents=None)
client.run(os.environ.get('discord_token')) client.run(os.environ.get("discord_token"))
# Set up the database if we haven't already # Set up the database if we haven't already
if not os.path.exists(DATABASE): if not os.path.exists(DATABASE):