Compare commits

...

23 Commits

Author SHA1 Message Date
51092e52a2 Add extra whitespace 2022-11-10 22:44:24 -06:00
b067a6ca07 Use the new game manager 2022-11-10 22:43:49 -06:00
bcbb74a3e1 Create composit class of available commands 2022-11-10 22:43:40 -06:00
0ed4ca4034 Add process_guess (this is the old guess.py) 2022-11-10 22:43:19 -06:00
2d8dc471f5 Add help manager 2022-11-10 22:42:45 -06:00
1b53d230cb Add points manager 2022-11-10 22:42:38 -06:00
13eab14f17 Add guess manager 2022-11-10 22:42:30 -06:00
3e98b025c7 Add end game manager 2022-11-10 22:42:20 -06:00
f9a5a8023d Add new game manager 2022-11-10 22:42:08 -06:00
98de64b7aa Add new game manager 2022-11-10 22:41:42 -06:00
353f858bac Delete GameManager 2022-11-10 22:40:33 -06:00
e05f023c4e Update docstrings 2022-11-10 22:13:07 -06:00
7818109a9c Fix database query 2022-11-10 22:10:58 -06:00
49f2630e38 Save to database seperately from getting points 2022-11-10 22:10:31 -06:00
175b02536c Refactor init to what is passed and defaults 2022-11-10 22:09:36 -06:00
5cf6b30eb2 Remove check_is_running decorator since it didn't work 2022-11-10 21:59:49 -06:00
7cf006cd4f Add help command 2022-11-10 21:58:55 -06:00
5131c4a3c1 linting 2022-11-10 21:46:42 -06:00
fbf588a85e Show table of points 2022-11-10 21:46:18 -06:00
bf8819fb46 Show total difference 2022-11-10 21:45:45 -06:00
946d826dc4 Only update the guess for the current game 2022-11-10 21:05:21 -06:00
83b6bda124 Linting changes 2022-11-10 21:03:38 -06:00
e68ef52292 Add calculation for the difference score 2022-11-10 21:02:20 -06:00
9 changed files with 471 additions and 355 deletions

View File

@ -18,7 +18,7 @@ import discord
# Import game functions
sys.path.append("..")
from game.game import GameManager
from game.manager import GameManager
class GhostBallClient(discord.Client):

View File

@ -0,0 +1,110 @@
#!/usr/bin/env python3
# Copyright 2022 - c0de <c0de@c0de.dev>
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
# pylint: disable=missing-module-docstring
import datetime
from database.models import GameModel as Game, GuessModel as Guess
from game.manager import BaseGameManager
from game.process_guess import ProcessGuess
class EndGameManager(BaseGameManager):
"""Commands that run at the end of a game"""
def __init__(self):
self.commands.append(("resolve", self.stop))
super().__init__()
def __stop_args__(self):
pieces = self.message.content.split()
if len(pieces) == 2:
return pieces[1], False, None, None
if len(pieces) == 4:
return pieces[1], True, pieces[2], pieces[3]
return None, False, None, None
async def update_pitch_value(self):
"""Update game state database for closing arguments"""
# Determine arguments
pitch_value, has_batter, batter_id, batter_guess = self.__stop_args__()
if not pitch_value:
return await self.message.channel.send(
f"Invalid command <@{ str(self.message.author.id) }>!"
)
if has_batter:
player_id = batter_id[3:]
Guess.create(
game_id=self.game.game_id,
player_id=player_id,
player_name=self.discord.get_user(int(player_id).name),
guess=int(batter_guess),
).save()
# Save the pitch value
Game.update(
{
Game.pitch_value: pitch_value,
Game.date_ended: datetime.datetime.now(),
}
).where(Game.game_id == self.game.game_id).execute()
return int(pitch_value)
async def stop(self):
"""
Stop command - Stops the game if it is currently running,
saves the pitch value, and displays differences
"""
if not self.is_running:
return await self.message.channel.send("There is no game running")
# How many valid guesses got placed?
guess_count = (
Guess.select()
.join(Game)
.where((Guess.game.game_id == self.game.game_id) & (Guess.guess > 0))
.count()
)
# Discard the game if there weren't enough players
if guess_count < 3:
self.game = None
self.is_running = False
return await self.message.channel.send(
("Play closed!\n" + "However, there were not enough participants.")
)
message = (
"Closed this play! Here are the results\n"
+ "PLAYER | GUESS | DIFFERENCE | POINTS GAINED | TOTAL POINTS\n"
)
pitch_value = await self.update_pitch_value()
guess_processor = ProcessGuess(
game=self, pitch_value=pitch_value, message=message
)
(
message,
closest_player_id,
furthest_player_id,
) = guess_processor.process_guesses()
message += (
f"\nCongrats <@{closest_player_id}>! You were the closest!\n"
+ f"Sorry <@{furthest_player_id}>, you were way off"
)
await self.message.channel.send(message)
# stop and discard game
self.is_running = False
self.game = None

View File

@ -1,250 +0,0 @@
#!/usr/bin/env python3
# Copyright 2022 - c0de <c0de@c0de.dev>
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
# pylint: disable=no-member,unnecessary-lambda
"""
A Context Manager / State Machine that keeps track of
a single game instance (there should only be one) in a
Discord channel
"""
import pdb
import math
import uuid
import datetime
# import dateparser
from database.models import (
database,
GameModel as Game,
GuessModel as Guess,
PlayerModel as Player,
)
from game.guess import ProcessGuess
def check_is_running(method):
"""
Decorator that determines if the game is running or not
"""
async def wrapper(self):
if self.is_running and self.new_game:
return await self.message.channel.send("A game is already running")
if not self.is_running and not self.new_game:
return await self.message.channel.send("There is no game running")
await method(self)
return wrapper
class GameManager:
"""
The game state class
This represents a game that exists in a channel
"""
def __init__(self):
# Only one game should run at at time
self.is_running = False
self.new_game = True
self.commands = [
("braveball", self.start),
("resolve", self.stop),
("guess", self.guess),
("points", self.points),
("help", self.help),
]
self.game = Game
# Discord message
self.message = None
# Discord client instance
self.discord = None
def __enter__(self):
"""
Allows use of `with Game() as game` for try/except statements
(https://peps.python.org/pep-0343/)
"""
database.connect()
return self
def __exit__(self, exception_type, exception_value, exception_traceback):
"""
Automagically close the database
when this class has ended execution
"""
database.close()
# @check_is_running
async def start(self):
"""
Start command - Starts a new game if there isn't already one running
"""
# print(dir(self.message))
self.is_running = True
self.new_game = False
# game.pitch_value is unknown at the start of the game
self.game = Game.create(game_id=uuid.uuid4(), server_id=self.message.channel.id)
await self.message.channel.send("Send me your guesses with !guess <number>")
def __stop_args__(self):
pieces = self.message.content.split()
if len(pieces) == 2:
return pieces[1], False, None, None
if len(pieces) == 4:
return pieces[1], True, pieces[2], pieces[3]
return None, False, None, None
async def update_pitch_value(self):
"""Update game state database for closing arguments"""
# Determine arguments
pitch_value, has_batter, batter_id, batter_guess = self.__stop_args__()
if not pitch_value:
return await self.message.channel.send(
f"Invalid command <@{ str(self.message.author.id) }>!"
)
if has_batter:
player_id = batter_id[3:]
Guess.create(
game_id=self.game.game_id,
player_id=player_id,
player_name=self.discord.get_user(int(player_id).name),
guess=int(batter_guess),
).save()
# Save the pitch value
Game.update(
{
Game.pitch_value: pitch_value,
Game.date_ended: datetime.datetime.now(),
}
).where(Game.game_id == self.game.game_id).execute()
return int(pitch_value)
# @check_is_running
async def stop(self):
"""
Stop command - Stops the game if it is currently running,
saves the pitch value, and displays differences
"""
# How many valid guesses got placed?
guess_count = (
Guess.select().join(Game)
.where((Guess.game.game_id == self.game.game_id) & (Guess.guess > 0))
.count()
)
# Discard the game if there weren't enough players
if guess_count < 3:
self.game = None
self.is_running = False
await self.message.channel.send(
("Play closed!\n" + "However, there were not enough participants.")
)
message = (
"Closed this play! Here are the results\n"
+ "PLAYER | GUESS | DIFFERENCE | POINTS GAINED | TOTAL POINTS\n"
)
pitch_value = await self.update_pitch_value()
guess_processor = ProcessGuess(game=self, pitch_value=pitch_value, message=message)
(
message,
closest_player_id,
furthest_player_id,
) = guess_processor.process_guesses()
message += (
f"\nCongrats <@{closest_player_id}>! You were the closest!\n"
+ f"Sorry <@{furthest_player_id}>, you were way off"
)
await self.message.channel.send(message)
# stop and discard game
self.is_running = False
self.game = None
# @check_is_running
async def guess(self):
"""
Guess command - Allows the player to add a guess to the current
running game
"""
value = int(self.message.content.split()[1])
if value < 1 or value > 1000:
return await self.message.channel.send(
"Invalid value. It must be between 1 and 1000 inclusive"
)
# Create player if they don't exist
player, _ = Player.get_or_create(
player_id=self.message.author.id, player_name=self.message.author.name
)
# Create the guess (or allow us to say update successful)
_, created = Guess.get_or_create(
guess_id=uuid.uuid4(), game_id=self.game.game_id, player_id=player.player_id
)
Guess.update({"guess": value}).where(
# (Guess.game_id == self.game.game_id)
# &
(Guess.player_id == self.message.author.id)
).execute()
if created:
return await self.message.add_reaction("\N{THUMBS UP SIGN}")
return await self.message.channel.send(
f"<@{ str(self.message.author.id) }> your guess has been updated"
)
async def points(self):
"""
Points command - returns a table ordered from highest to lowest
of the players and their points
"""
# TODO
# value = self.message.content.split()
# try:
# if len(value) > 1:
# timestamp = dateparser.parse(value[1])
# except:
# return await self.message.channel.send("Invalid timestamp. Try again")
return await self.message.channel.send("Sorry, not implemented yet")
async def help(self):
"""help command"""
# TODO: Add help message
help_message = "help"
recipient = await self.discord.fetch_user(self.message.author.id)
await recipient.send(help_message)

View File

@ -1,115 +1,54 @@
import math
#!/usr/bin/env python3
# Copyright 2022 - c0de <c0de@c0de.dev>
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
# Import game functions
from database.models import (
GameModel as Game,
GuessModel as Guess,
PlayerModel as Player,
)
# pylint: disable=missing-module-docstring
import uuid
from database.models import PlayerModel as Player, GuessModel as Guess
from game.manager import BaseGameManager
class ProcessGuess:
def __init__(self, game, **kwargs):
self.game_manager = game
class GuessManager(BaseGameManager):
"""Commands that run when a player makes a guess"""
self.message = kwargs.get("message")
self.pitch_value = kwargs.get("pitch_value")
self.difference = kwargs.get("difference")
self.difference_score = kwargs.get("difference_score")
self.guesses = kwargs.get("guesses")
self.guess = kwargs.get("guess")
def __init__(self):
self.commands.append(("guess", self.guess))
super().__init__()
def get_guesses(self):
# Get all guesses for this game as a list of combo Guess + Player models,
# excluding invalid results, from lowest to highest
# http://docs.peewee-orm.com/en/latest/peewee/query_examples.html#joins-and-subqueries
self.guesses = (
Guess.select(
Guess.guess,
Player.player_id,
Player.player_name,
Player.total_points,
async def guess(self):
"""
Guess command - Allows the player to add a guess to the current
running game
"""
if not self.is_running:
return await self.message.channel.send("There is no game running")
value = int(self.message.content.split()[1])
if value < 1 or value > 1000:
return await self.message.channel.send(
"Invalid value. It must be between 1 and 1000 inclusive"
)
.join(Player)
.where(
(Guess.game == self.game_manager.game.game_id)
& (Guess.guess > 0)
& (Guess.player.player_id == Player.player_id)
)
.order_by(Guess.guess)
# Create player if they don't exist
player, _ = Player.get_or_create(
player_id=self.message.author.id, player_name=self.message.author.name
)
return self.guesses
def update_difference_value(self):
# Update player's difference in guessed value
Guess.update({"difference": self.difference}).where(
(Guess.game.game_id == self.game_manager.game.game_id)
& (Guess.player.player_id == self.guess.player.player_id)
& (Guess.guess_id == self.guess.guess_id)
# Create the guess (or allow us to say update successful)
_, created = Guess.get_or_create(
guess_id=uuid.uuid4(), game_id=self.game.game_id, player_id=player.player_id
)
Guess.update({"guess": value}).where(
(Guess.game == self.game.game_id) & (Guess.player == self.message.author.id)
).execute()
def update_player_total_points(self):
# Update player's total score
Player.update(
{
"total_points": math.floor(
self.guess.player.total_points + self.difference_score
)
}
).where(Player.player_id == self.guess.player.player_id).execute()
if created:
return await self.message.add_reaction("\N{THUMBS UP SIGN}")
def get_difference(self, guess=None):
"""Difference calculation, includes "loop over" effect"""
if not guess:
guess = self.guess.guess
difference = abs(guess - self.pitch_value)
if difference > 500:
return 1000 - difference
self.difference = difference
self.update_difference_value()
return self.difference
def get_difference_score(self):
self.difference_score = 0
self.update_player_total_points()
return self.difference_score
def get_winner_loser(self):
# Determine which guesses are closest and furthest from the pitch_value
guess_values = [record.guess for record in self.get_guesses()]
# Closest to the pitch_value
winner = min(guess_values, key=lambda guess: self.get_difference(guess))
# Furthest from the pitch_value
loser = max(guess_values, key=lambda guess: self.get_difference(guess))
return winner, loser
def process_guesses(self):
"""
Iterates through the guesses for this game, and appends to the message string
the results of how well that player performed this round.
Uses the pitch_value to determine the difference from their guess to the correct score
"""
winner, loser = self.get_winner_loser()
for guess in self.get_guesses():
self.guess = guess
difference = self.get_difference()
difference_score = self.get_difference_score()
self.message += f"{guess.player.player_name} | {guess.guess} | {difference} | {difference_score} | {guess.player.total_points}\n"
if guess.guess == winner:
closest_player_id = guess.player.player_id
if guess.guess == loser:
furthest_player_id = guess.player.player_id
return self.message, closest_player_id, furthest_player_id
return await self.message.channel.send(
f"<@{ str(self.message.author.id) }> your guess has been updated"
)

33
GhostBallBot/game/help.py Normal file
View File

@ -0,0 +1,33 @@
#!/usr/bin/env python3
# Copyright 2022 - c0de <c0de@c0de.dev>
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
# pylint: disable=missing-module-docstring
from game.manager import BaseGameManager
class HelpManager(BaseGameManager):
"""Commands that run when a player asks for help"""
def __init__(self):
self.commands.append(("help", self.help))
super().__init__()
async def help(self):
"""help command - Sends a DM to the requesting user with available commands"""
help_message = (
"Braveball commands\n"
+ "!braveball - Start new game\n"
+ "!guess - While a game is running, add a guess"
+ " (or update an existing one) from 1-1000\n"
+ "!resolve <value> - 1-1000 to resolve the game\n"
+ " You can also add a batter's guess with: "
+ "!resolve <value> <discord id #> <guess>\n"
+ "!points - Shows a table of the most recent players, and their scores\n"
+ "!help - Shows this message"
)
recipient = await self.discord.fetch_user(self.message.author.id)
await recipient.send(help_message)

View File

@ -0,0 +1,61 @@
#!/usr/bin/env python3
# Copyright 2022 - c0de <c0de@c0de.dev>
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
# pylint: disable=no-member
"""
A Context Manager / State Machine that keeps track of
a single game instance (there should only be one) in a
Discord channel
"""
from database.models import database, GameModel as Game
from game.new_game import NewGameManager
from game.end_game import EndGameManager
from game.guess import GuessManager
from game.points import PointsManager
from game.help import HelpManager
class BaseGameManager:
"""Base Game Manager for each Game Manager class to inherit"""
def __init__(self):
# Only one game should run at at time
self.is_running = False
self.commands = []
self.game = Game
# Discord message
self.message = None
# Discord client instance
self.discord = None
def __enter__(self):
"""
Allows use of `with Game() as game` for try/except statements
(https://peps.python.org/pep-0343/)
"""
database.connect()
return self
def __exit__(self, exception_type, exception_value, exception_traceback):
"""
Automagically close the database
when this class has ended execution
"""
database.close()
class GameManager(
NewGameManager, EndGameManager, GuessManager, PointsManager, HelpManager
):
"""
Represents what this bot is able to do on a channel (or DMs)
"""

View File

@ -0,0 +1,33 @@
#!/usr/bin/env python3
# Copyright 2022 - c0de <c0de@c0de.dev>
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
# pylint: disable=missing-module-docstring
import uuid
from database.models import GameModel as Game
from game.manager import BaseGameManager
class NewGameManager(BaseGameManager):
"""Commands that run at the start of a new game"""
def __init__(self):
self.commands.append(("braveball", self.start))
super().__init__()
async def start(self):
"""
Start command - Starts a new game if there isn't already one running
"""
if self.is_running:
return await self.message.channel.send("A game is already running")
self.is_running = True
# game.pitch_value is unknown at the start of the game
self.game = Game.create(game_id=uuid.uuid4(), server_id=self.message.channel.id)
await self.message.channel.send("Send me your guesses with !guess <number>")

View File

@ -0,0 +1,44 @@
#!/usr/bin/env python3
# Copyright 2022 - c0de <c0de@c0de.dev>
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
# pylint: disable=not-an-iterable,missing-module-docstring
from database.models import PlayerModel as Player
from game.manager import BaseGameManager
class PointsManager(BaseGameManager):
"""Commands that run when a player makes a guess"""
def __init__(self):
self.commands.append(("points", self.points))
super().__init__()
async def points(self):
"""
Points command - returns a table ordered from highest to lowest
of the players and their points
"""
message = (
"\nPlayers, who played recently, with their points highest to lowest\n\n"
)
message += "Player | Total Points | Last Played\n"
players = Player.select(
Player.player_name, Player.total_points, Player.last_update
).order_by(Player.last_update.desc(), Player.total_points.desc())
for player in players:
message += (
" | ".join(
[
player.player_name,
str(player.total_points),
str(player.last_update)[:-10],
]
)
+ "\n"
)
return await self.message.channel.send(message)

View File

@ -0,0 +1,146 @@
#!/usr/bin/env python3
# Copyright 2022 - c0de <c0de@c0de.dev>
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
# pylint: disable=unnecessary-lambda,line-too-long,missing-module-docstring
import math
# Import game functions
from database.models import (
GuessModel as Guess,
PlayerModel as Player,
)
class ProcessGuess:
"""
A helper class for the GameManager that handles the
logic for all of the players at the end of a game
"""
def __init__(self, game, pitch_value, message):
self.game_manager = game
self.message = message
self.pitch_value = pitch_value
self.difference = 0
self.difference_score = 0
self.guesses = [Guess]
self.guess = Guess
def get_guesses(self):
"""
Get all guesses for this game as a list of combo Guess + Player models,
excluding invalid results, from lowest to highest value
http://docs.peewee-orm.com/en/latest/peewee/query_examples.html#joins-and-subqueries
"""
self.guesses = (
Guess.select(
Guess.guess,
Player.player_id,
Player.player_name,
Player.total_points,
)
.join(Player)
.where(
(Guess.game == self.game_manager.game.game_id)
& (Guess.guess > 0)
& (Guess.player.player_id == Player.player_id)
)
.order_by(Guess.guess)
)
return self.guesses
def update_difference_value(self):
"""Store the difference between the player's guessed value and the pitch_value"""
Guess.update({"difference": self.difference}).where(
(Guess.game == self.game_manager.game.game_id)
& (Guess.player == self.guess.player.player_id)
& (Guess.guess_id == self.guess.guess_id)
).execute()
def update_player_total_points(self):
"""Update player's total score with how many points they won this round"""
Player.update(
{
"total_points": math.floor(
self.guess.player.total_points + self.difference_score
)
}
).where(Player.player_id == self.guess.player.player_id).execute()
def get_difference(self, guess=None):
"""Difference calculation, includes "loop over" effect"""
if not guess:
guess = self.guess.guess
difference = abs(guess - self.pitch_value)
if difference > 500:
return 1000 - difference
self.difference = difference
return self.difference
def get_difference_score(self):
"""
Calculate points for the player based on how close
they are (within range of 0-500) to the pitch_value
"""
if self.difference == 0:
self.difference_score = 15
elif self.difference > 0 and self.difference < 21:
self.difference_score = 8
elif self.difference > 20 and self.difference < 51:
self.difference_score = 5
elif self.difference > 50 and self.difference < 101:
self.difference_score = 3
elif self.difference > 100 and self.difference < 151:
self.difference_score = 2
elif self.difference > 150 and self.difference < 201:
self.difference_score = 1
elif self.difference > 200 and self.difference < 495:
self.difference_score = 0
else:
self.difference_score = -5
return self.difference_score
def get_winner_loser(self):
"""Determine which guesses are closest and furthest from the pitch_value"""
guess_values = [record.guess for record in self.get_guesses()]
# Closest to the pitch_value
winner = min(guess_values, key=lambda guess: self.get_difference(guess))
# Furthest from the pitch_value
loser = max(guess_values, key=lambda guess: self.get_difference(guess))
return winner, loser
def process_guesses(self):
"""
Iterates through the guesses for this game, and appends to the message string
the results of how well that player performed this round.
Uses the pitch_value to determine the difference from their guess to the correct score
"""
winner, loser = self.get_winner_loser()
for guess in self.get_guesses():
self.guess = guess
difference = self.get_difference()
difference_score = self.get_difference_score()
self.update_difference_value()
self.update_player_total_points()
self.message += f"{guess.player.player_name} | {guess.guess} | {difference} | {difference_score} | {(guess.player.total_points + difference_score)}\n"
if guess.guess == winner:
closest_player_id = guess.player.player_id
if guess.guess == loser:
furthest_player_id = guess.player.player_id
return self.message, closest_player_id, furthest_player_id