Compare commits
23 Commits
3435e4ce7a
...
51092e52a2
Author | SHA1 | Date | |
---|---|---|---|
51092e52a2 | |||
b067a6ca07 | |||
bcbb74a3e1 | |||
0ed4ca4034 | |||
2d8dc471f5 | |||
1b53d230cb | |||
13eab14f17 | |||
3e98b025c7 | |||
f9a5a8023d | |||
98de64b7aa | |||
353f858bac | |||
e05f023c4e | |||
7818109a9c | |||
49f2630e38 | |||
175b02536c | |||
5cf6b30eb2 | |||
7cf006cd4f | |||
5131c4a3c1 | |||
fbf588a85e | |||
bf8819fb46 | |||
946d826dc4 | |||
83b6bda124 | |||
e68ef52292 |
@ -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):
|
||||
|
110
GhostBallBot/game/end_game.py
Normal file
110
GhostBallBot/game/end_game.py
Normal 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
|
@ -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)
|
@ -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
33
GhostBallBot/game/help.py
Normal 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)
|
61
GhostBallBot/game/manager.py
Normal file
61
GhostBallBot/game/manager.py
Normal 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)
|
||||
"""
|
33
GhostBallBot/game/new_game.py
Normal file
33
GhostBallBot/game/new_game.py
Normal 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>")
|
44
GhostBallBot/game/points.py
Normal file
44
GhostBallBot/game/points.py
Normal 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)
|
146
GhostBallBot/game/process_guess.py
Normal file
146
GhostBallBot/game/process_guess.py
Normal 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
|
Loading…
Reference in New Issue
Block a user