[refactor] Processing guesses moved to own class

This commit is contained in:
c0de 2022-10-30 22:24:51 -05:00
parent f6860bb43f
commit e39a19da55
5 changed files with 148 additions and 68 deletions

View File

@ -18,7 +18,7 @@ import discord
# Import game functions # Import game functions
sys.path.append("..") sys.path.append("..")
import game from game.game import GameManager
class GhostBallClient(discord.Client): class GhostBallClient(discord.Client):
@ -31,7 +31,7 @@ class GhostBallClient(discord.Client):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
with game.GameManager() as self.game: with GameManager() as self.game:
self.game.discord = self self.game.discord = self
async def on_ready(self): async def on_ready(self):

View File

View File

@ -2,7 +2,7 @@
# Copyright 2022 - c0de <c0de@c0de.dev> # Copyright 2022 - c0de <c0de@c0de.dev>
# Licensed under the MIT License (https://opensource.org/licenses/MIT) # Licensed under the MIT License (https://opensource.org/licenses/MIT)
# pylint: disable=no-member # pylint: disable=no-member,unnecessary-lambda
""" """
A Context Manager / State Machine that keeps track of A Context Manager / State Machine that keeps track of
@ -11,6 +11,7 @@
""" """
import pdb import pdb
import math
import uuid import uuid
import datetime import datetime
@ -22,6 +23,7 @@ from database.models import (
GuessModel as Guess, GuessModel as Guess,
PlayerModel as Player, PlayerModel as Player,
) )
from game.guess import ProcessGuess
def check_is_running(method): def check_is_running(method):
@ -113,7 +115,7 @@ class GameManager:
return None, False, None, None return None, False, None, None
async def close_game(self): async def update_pitch_value(self):
"""Update game state database for closing arguments""" """Update game state database for closing arguments"""
# Determine arguments # Determine arguments
pitch_value, has_batter, batter_id, batter_guess = self.__stop_args__() pitch_value, has_batter, batter_id, batter_guess = self.__stop_args__()
@ -132,12 +134,12 @@ class GameManager:
).save() ).save()
# Save the pitch value # Save the pitch value
self.game.update( Game.update(
{ {
Game.pitch_value: pitch_value, Game.pitch_value: pitch_value,
Game.date_ended: datetime.datetime.now(), Game.date_ended: datetime.datetime.now(),
} }
) ).where(Game.game_id == self.game.game_id).execute()
return int(pitch_value) return int(pitch_value)
@ -148,28 +150,14 @@ class GameManager:
saves the pitch value, and displays differences saves the pitch value, and displays differences
""" """
pitch_value = await self.close_game() # How many valid guesses got placed?
guess_count = (
# Start calculating difference Guess.select().where((Guess.game.game_id == self.game.game_id)
# 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
records = (
Guess.select(
Guess.guess, Player.player_id, Player.player_name, Player.total_points
)
.join(Player)
.where(
(Guess.game_id == self.game.game_id)
& (Guess.guess > 0) & (Guess.guess > 0)
& (Guess.player_id == Player.player_id) ).count())
)
.order_by(Guess.guess)
)
# Minimum of 3 players # Discard the game if there weren't enough players
if len(records) < 1: if guess_count < 3:
self.game = None self.game = None
self.is_running = False self.is_running = False
await self.message.channel.send( await self.message.channel.send(
@ -181,41 +169,10 @@ class GameManager:
+ "PLAYER | GUESS | DIFFERENCE | POINTS GAINED | TOTAL POINTS\n" + "PLAYER | GUESS | DIFFERENCE | POINTS GAINED | TOTAL POINTS\n"
) )
def get_difference(guess): pitch_value = await self.update_pitch_value()
difference = abs(guess - pitch_value) guess_processor = ProcessGuess(game=self, pitch_value=pitch_value)
if difference > 500: message, closest_player_id, furthest_player_id = guess_processor.process_guesses()
return 1000 - difference
return difference
# Determine which guesses are closest and furthest from the pitch_value
guess_values = [record.guess for record in records]
closest_guess_value = min(
guess_values, key=lambda guess: get_difference(guess)
)
furthest_guess_value = max(
guess_values, key=lambda guess: get_difference(guess)
)
def get_difference_score():
# TODO: Calculate score based on scoring table
return 0
for record in records:
difference = abs(record.guess - pitch_value)
difference_score = get_difference_score()
# TODO: Update Guess.difference
# TODO: Update Player.total_points
if record.guess == closest_guess_value:
closest_player_id = record.player.player_id
if record.guess == furthest_guess_value:
furthest_player_id = record.player.player_id
message += f"{record.player.player_name} | {record.guess} | {difference} | {difference_score} | {record.player.total_points}\n"
message += ( message += (
f"\nCongrats <@{closest_player_id}>! You were the closest!\n" f"\nCongrats <@{closest_player_id}>! You were the closest!\n"
@ -241,15 +198,24 @@ class GameManager:
"Invalid value. It must be between 1 and 1000 inclusive" "Invalid value. It must be between 1 and 1000 inclusive"
) )
player_id, created = Player.get_or_create( # Create player if they don't exist
player_id=self.message.author.id, player_name="c0de" player, _ = Player.get_or_create(
player_id=self.message.author.id, player_name=self.message.author.name
) )
player_guess, created = Guess.get_or_create( # Create the guess (or allow us to say update successful)
guess_id=uuid.uuid4(), game_id=self.game.game_id, player_id=player_id _, created = Guess.get_or_create(
guess_id=uuid.uuid4(),
game_id=self.game.game_id,
player_id=player.player_id,
player_name=player.player_name,
) )
Guess.update({"guess": value}).where((Guess.game_id==self.game.game_id) & (Guess.player_id==player_id)).execute() Guess.update({"guess": value}).where(
(Guess.game_id == self.game.game_id)
& (Guess.player_id == self.message.author.id)
).execute()
if created: if created:
return await self.message.add_reaction("\N{THUMBS UP SIGN}") return await self.message.add_reaction("\N{THUMBS UP SIGN}")

114
GhostBallBot/game/guess.py Normal file
View File

@ -0,0 +1,114 @@
import math
# Import game functions
from database.models import (
GameModel as Game,
GuessModel as Guess,
PlayerModel as Player,
)
class ProcessGuess:
def __init__(self, game, **kwargs):
self.game_manager = game
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 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,
)
.join(Player)
.where(
(Guess.game_id == 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):
# Update player's difference in guessed value
Guess.update({"difference": self.difference}).where(
(Guess.game_id == self.game_manager.game.game_id)
& (Guess.player.player_id == self.guess.player.player_id)
& (Guess.guess_id == self.guess.guess_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()
def get_difference(self, guess=None):
"""Difference calculation, includes "loop over" effect"""
if not guess:
guess = self.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.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

View File

@ -1,4 +1,4 @@
#!/bin/bash #!/bin/bash
pylint main.py game.py discord_client database > lint.log pylint main.py game discord_client database > lint.log
black main.py game.py discord_client database black main.py game discord_client database