From e478589b8ece2a4ec538374b1e4433e7b67a314b Mon Sep 17 00:00:00 2001 From: hillexed Date: Sun, 21 Feb 2021 03:03:25 -0500 Subject: [PATCH] Begin moving weather to separate files --- games.py | 131 +++++----------------- gametext.py | 27 +++++ main_controller.py | 6 +- the_prestige.py | 8 +- weather.py | 273 +++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 334 insertions(+), 111 deletions(-) create mode 100644 gametext.py create mode 100644 weather.py diff --git a/games.py b/games.py index f12b787..42b3473 100644 --- a/games.py +++ b/games.py @@ -1,6 +1,7 @@ import json, random, os, math, jsonpickle -from enum import Enum import database as db +import weather +from gametext import base_string, appearance_outcomes data_dir = "data" games_config_file = os.path.join(data_dir, "games_config.json") @@ -28,33 +29,6 @@ def config(): with open(games_config_file) as config_file: return json.load(config_file) -def all_weathers(): - weathers_dic = { - #"Supernova" : weather("Supernova", "🌟"), - #"Midnight": weather("Midnight", "🕶"), - #"Slight Tailwind": weather("Slight Tailwind", "🏌️‍♀️"), - "Heavy Snow": weather("Heavy Snow", "❄"), - "Twilight" : weather("Twilight", "👻"), - "Thinned Veil" : weather("Thinned Veil", "🌌"), - "Heat Wave" : weather("Heat Wave", "🌄"), - "Drizzle" : weather("Drizzle", "🌧") - } - return weathers_dic - -class appearance_outcomes(Enum): - strikeoutlooking = "strikes out looking." - strikeoutswinging = "strikes out swinging." - groundout = "grounds out to" - flyout = "flies out to" - fielderschoice = "reaches on fielder's choice. {} is out at {} base." #requires .format(player, base_string) - doubleplay = "grounds into a double play!" - sacrifice = "hits a sacrifice fly towards" - walk = "draws a walk." - single = "hits a single!" - double = "hits a double!" - triple = "hits a triple!" - homerun = "hits a dinger!" - grandslam = "hits a grand slam!" class player(object): @@ -248,19 +222,22 @@ class game(object): else: self.max_innings = config()["default_length"] self.bases = {1 : None, 2 : None, 3 : None} - self.weather = weather("Sunny","🌞") + self.weather = weather.Weather() + self.current_batter = None - def get_batter(self): + def choose_next_batter(self): if self.top_of_inning: bat_team = self.teams["away"] - counter = self.weather.counter_away else: bat_team = self.teams["home"] - counter = self.weather.counter_home - if self.weather.name == "Heavy Snow" and counter == bat_team.lineup_position: - return bat_team.pitcher - return bat_team.lineup[bat_team.lineup_position % len(bat_team.lineup)] + self.current_batter = bat_team.lineup[bat_team.lineup_position % len(bat_team.lineup)] + self.weather.on_choose_next_batter(self) + + def get_batter(self): + if self.current_batter == None: + self.choose_next_batter() + return self.current_batter def get_pitcher(self): if self.top_of_inning: @@ -286,8 +263,8 @@ class game(object): bat_stat = random_star_gen("batting_stars", batter) pitch_stat = random_star_gen("pitching_stars", pitcher) - if weather.name == "Supernova": - pitch_stat = pitch_stat * 0.9 + + bat_stat, pitch_stat = self.weather.modify_stats_preroll(bat_stat, pitch_stat) pb_system_stat = (random.gauss(1*math.erf((bat_stat - pitch_stat)*1.5)-1.8,2.2)) hitnum = random.gauss(2*math.erf(bat_stat/4)-1,3) @@ -533,25 +510,19 @@ class game(object): def batterup(self): scores_to_add = 0 result = self.at_bat() + + self.weather.activate(self, result) # possibly modify result in-place + + if "text_only" in result: + return (result, 0) + if self.top_of_inning: offense_team = self.teams["away"] - weather_count = self.weather.counter_away defense_team = self.teams["home"] else: offense_team = self.teams["home"] - weather_count = self.weather.counter_home defense_team = self.teams["away"] - if self.weather.name == "Slight Tailwind" and "mulligan" not in self.last_update[0].keys() and not result["ishit"] and result["text"] != appearance_outcomes.walk: - mulligan_roll_target = -((((self.get_batter().stlats["batting_stars"])-5)/6)**2)+1 - if random.random() > mulligan_roll_target and self.get_batter().stlats["batting_stars"] <= 5: - result["mulligan"] = True - return (result, 0) - - if self.weather.name == "Heavy Snow" and weather_count == offense_team.lineup_position and "snow_atbat" not in self.last_update[0].keys(): - result["snow_atbat"] = True - result["text"] = f"{offense_team.lineup[offense_team.lineup_position % len(offense_team.lineup)].name}'s hands are too cold! {self.get_batter().name} is forced to bat!" - return (result, 0) defenders = defense_team.lineup.copy() defenders.append(defense_team.pitcher) @@ -570,8 +541,6 @@ class game(object): elif result["text"] == appearance_outcomes.homerun or result["text"] == appearance_outcomes.grandslam: self.get_batter().game_stats["total_bases"] += 4 self.get_batter().game_stats["home_runs"] += 1 - if self.weather.name == "Thinned Veil": - result["veil"] = True @@ -636,27 +605,10 @@ class game(object): self.get_batter().game_stats["rbis"] += scores_to_add self.get_pitcher().game_stats["runs_allowed"] += scores_to_add offense_team.lineup_position += 1 #put next batter up + self.choose_next_batter() if self.outs >= 3: self.flip_inning() - if self.weather.name == "Heat Wave": - if self.top_of_inning: - self.weather.home_pitcher = self.get_pitcher() - if self.inning >= self.weather.counter_home: - self.weather.counter_home = self.weather.counter_home - (self.weather.counter_home % 5) + 5 + random.randint(1,4) #rounds down to last 5, adds up to next 5. then adds a random number 2<=x<=5 to determine next pitcher - tries = 0 - while self.get_pitcher() == self.weather.home_pitcher and tries < 3: - self.teams["home"].set_pitcher(use_lineup = True) - tries += 1 - - - else: - self.weather.away_pitcher = self.get_pitcher() - if self.inning >= self.weather.counter_away: - self.weather.counter_away = self.weather.counter_away - (self.weather.counter_away % 5) + 5 + random.randint(1,4) - tries = 0 - while self.get_pitcher() == self.weather.away_pitcher and tries < 3: - self.teams["away"].set_pitcher(use_lineup = True) - tries += 1 + return (result, scores_to_add) #returns ab information and scores @@ -665,22 +617,17 @@ class game(object): for base in self.bases.keys(): self.bases[base] = None self.outs = 0 - if self.top_of_inning and self.weather.name == "Heavy Snow" and self.weather.counter_away < self.teams["away"].lineup_position: - self.weather.counter_away = self.pitcher_insert(self.teams["away"]) + + self.top_of_inning = not self.top_of_inning + + self.weather.on_flip_inning(self) + + self.choose_next_batter() if not self.top_of_inning: - if self.weather.name == "Heavy Snow" and self.weather.counter_home < self.teams["home"].lineup_position: - self.weather.counter_home = self.pitcher_insert(self.teams["home"]) self.inning += 1 if self.inning > self.max_innings and self.teams["home"].score != self.teams["away"].score: #game over self.over = True - self.top_of_inning = not self.top_of_inning - - if self.weather.name == "Drizzle": - if self.top_of_inning: - self.bases[2] = self.teams["away"].lineup[(self.teams["away"].lineup_position-1) % len(self.teams["away"].lineup)] - else: - self.bases[2] = self.teams["home"].lineup[(self.teams["home"].lineup_position-1) % len(self.teams["home"].lineup)] def pitcher_insert(self, this_team): rounds = math.ceil(this_team.lineup_position / len(this_team.lineup)) @@ -868,25 +815,3 @@ def search_team(search_term): teams.append(team_json) return teams -def base_string(base): - if base == 1: - return "first" - elif base == 2: - return "second" - elif base == 3: - return "third" - elif base == 4: - return "None" - -class weather(object): - name = "Sunny" - emoji = "🌞" - - def __init__(self, new_name, new_emoji): - self.name = new_name - self.emoji = new_emoji + "\uFE00" - self.counter_away = 0 - self.counter_home = 0 - - def __str__(self): - return f"{self.emoji} {self.name}" diff --git a/gametext.py b/gametext.py new file mode 100644 index 0000000..d7ec310 --- /dev/null +++ b/gametext.py @@ -0,0 +1,27 @@ +from enum import Enum + +class appearance_outcomes(Enum): + strikeoutlooking = "strikes out looking." + strikeoutswinging = "strikes out swinging." + groundout = "grounds out to" + flyout = "flies out to" + fielderschoice = "reaches on fielder's choice. {} is out at {} base." #requires .format(player, base_string) + doubleplay = "grounds into a double play!" + sacrifice = "hits a sacrifice fly towards" + walk = "draws a walk." + single = "hits a single!" + double = "hits a double!" + triple = "hits a triple!" + homerun = "hits a dinger!" + grandslam = "hits a grand slam!" + +def base_string(base): + if base == 1: + return "first" + elif base == 2: + return "second" + elif base == 3: + return "third" + elif base == 4: + return "None" + diff --git a/main_controller.py b/main_controller.py index 176c28f..b513322 100644 --- a/main_controller.py +++ b/main_controller.py @@ -174,7 +174,7 @@ def update_loop(): state["update_text"] = f"Top of {this_game.inning}. {this_game.teams['away'].name} batting!" if this_game.weather.name == "Drizzle": state["update_emoji"] = "🌧" - state["update_text"] += f' Due to inclement weather, {this_game.teams["away"].lineup[(this_game.teams["away"].lineup_position-1) % len(this_game.teams["away"].lineup)].name} is placed on second base.' + state["update_text"] += f'Due to inclement weather, {this_game.teams["away"].lineup[(this_game.teams["away"].lineup_position-1) % len(this_game.teams["away"].lineup)].name} is placed on second base.' elif this_game.weather.name == "Heat Wave" and hasattr(this_game.weather, "home_pitcher") and this_game.weather.home_pitcher.name != state["pitcher"]: state["update_emoji"] = "🌄" state["update_text"] += f' {this_game.weather.home_pitcher} is exhausted from the heat. {state["pitcher"]} is forced to pitch!' @@ -234,7 +234,7 @@ def update_loop(): if "veil" in this_game.last_update[0].keys(): state["update_emoji"] = "🌌" - state["update_text"] += f" {this_game.last_update[0]['batter']}'s will manifests on {games.base_string(this_game.last_update[1])} base." + state["update_text"] += f" {this_game.last_update[0]['batter']}'s will manifests on {gametext.base_string(this_game.last_update[1])} base." elif "error" in this_game.last_update[0].keys(): state["update_emoji"] = "👻" state["update_text"] = f"{this_game.last_update[0]['batter']}'s hit goes ethereal, and {this_game.last_update[0]['defender']} can't catch it! {this_game.last_update[0]['batter']} reaches base safely." @@ -261,4 +261,4 @@ def update_loop(): state["update_pause"] -= 1 socketio.emit("states_update", game_states) - time.sleep(8) \ No newline at end of file + time.sleep(8) diff --git a/the_prestige.py b/the_prestige.py index 1003b1a..6d63519 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -5,6 +5,7 @@ from league_storage import league_exists, season_save, season_restart from the_draft import Draft, DRAFT_ROUNDS from flask import Flask from uuid import uuid4 +import weather data_dir = "data" config_filename = os.path.join(data_dir, "config.json") @@ -1396,8 +1397,8 @@ async def watch_game(channel, newgame, user = None, league = None): def prepare_game(newgame, league = None, weather_name = None): if weather_name is None: - weathers = games.all_weathers() - newgame.weather = weathers[random.choice(list(weathers.keys()))] + weathers = weather.all_weathers() + newgame.weather = weathers[random.choice(list(weathers.keys()))]() state_init = { "away_name" : newgame.teams['away'].name, @@ -1420,9 +1421,6 @@ def prepare_game(newgame, league = None, weather_name = None): if newgame.weather.name == "Heavy Snow": newgame.weather.counter_away = random.randint(0,len(newgame.teams['away'].lineup)-1) newgame.weather.counter_home = random.randint(0,len(newgame.teams['home'].lineup)-1) - elif newgame.weather.name == "Heat Wave": - newgame.weather.counter_away = random.randint(2,4) - newgame.weather.counter_home = random.randint(2,4) return newgame, state_init async def start_tournament_round(channel, tourney, seeding = None): diff --git a/weather.py b/weather.py new file mode 100644 index 0000000..4087492 --- /dev/null +++ b/weather.py @@ -0,0 +1,273 @@ +import random +from gametext import appearance_outcomes + +class Weather: + def __init__(self): + self.name = "Sunny" + self.emoji = "🌞" + "\uFE00" + self.counter_away = 0 + self.counter_home = 0 + + def __str__(self): + return f"{self.emoji} {self.name}" + + def activate(self, game, result): + # activates after the batter calculation. modify result, or just return another thing + pass + + def modify_stats_preroll(self, bat_stat, pitch_stat): # ugly + # Activates before batting and pitch + return bat_stat, pitch_stat + + def on_flip_inning(self, game): + pass + + def on_choose_next_batter(self, game): + pass + +class Supernova(Weather): # todo + def __init__(self): + super().__init__() + self.name = "Supernova" + self.emoji = "🌟" + "\uFE00" + def activate(self, game, result): + pass + + def modify_stats_preroll(self, bat_stat, pitch_stat): + if self.weather.name == "Supernova": + pitch_stat = pitch_stat * 0.9 + +class Midnight(Weather): # todo + def __init__(self): + super().__init__() + self.name = "Midnight" + self.emoji = "🕶" + "\uFE00" + def activate(self, game, result): + pass + +class SlightTailwind(Weather): + def __init__(self): + super().__init__() + self.name = "Slight Tailwind" + self.emoji = "🏌️‍♀️" + "\uFE00" + def activate(self, game, result): + + if game.top_of_inning: + offense_team = game.teams["away"] + weather_count = self.counter_away + defense_team = game.teams["home"] + else: + offense_team = game.teams["home"] + weather_count = self.counter_home + defense_team = game.teams["away"] + + if "mulligan" not in game.last_update[0].keys() and not result["ishit"] and result["text"] != appearance_outcomes.walk: + mulligan_roll_target = -((((self.get_batter().stlats["batting_stars"])-5)/6)**2)+1 + if random.random() > mulligan_roll_target and self.get_batter().stlats["batting_stars"] <= 5: + result["mulligan"] = True + +class HeavySnow(Weather): + def __init__(self): + super().__init__() + self.name = "Heavy Snow" + self.emoji = "❄" + "\uFE00" + + def activate(self, game, result): + if game.top_of_inning: + offense_team = game.teams["away"] + weather_count = self.counter_away + else: + offense_team = game.teams["home"] + weather_count = self.counter_home + + if weather_count == offense_team.lineup_position and "snow_atbat" not in game.last_update[0].keys(): + result.clear() + result.update({ + "snow_atbat": True, + "text": f"{offense_team.lineup[offense_team.lineup_position % len(offense_team.lineup)].name}'s hands are too cold! {game.get_batter().name} is forced to bat!", + "text_only": True, + }) + + def on_flip_inning(self, game): + if game.top_of_inning and self.counter_away < game.teams["away"].lineup_position: + self.counter_away = game.pitcher_insert(game.teams["away"]) + + if not game.top_of_inning and self.counter_home < game.teams["home"].lineup_position: + self.counter_home = game.pitcher_insert(game.teams["home"]) + + def on_choose_next_batter(self, game): + if game.top_of_inning: + bat_team = game.teams["away"] + counter = self.counter_away + else: + bat_team = game.teams["home"] + counter = self.counter_home + + if counter == bat_team.lineup_position: + game.current_batter = bat_team.pitcher + +class Twilight(Weather): + def __init__(self): + super().__init__() + self.name = "Twilight" + self.emoji = "👻" + "\uFE00" + def activate(self, game, result): + pass + +class ThinnedVeil(Weather): + def __init__(self): + super().__init__() + self.name = "Thinned Veil" + self.emoji = "🌌" + "\uFE00" + + def activate(self, game, result): + if result["ishit"]: + if result["text"] == appearance_outcomes.homerun or result["text"] == appearance_outcomes.grandslam: + result["veil"] = True + +class HeatWave(Weather): + def __init__(self): + super().__init__() + self.name = "Heat Wave" + self.emoji = "🌄" + "\uFE00" + + self.counter_away = random.randint(2,4) + self.counter_home = random.randint(2,4) + + def on_flip_inning(self, game): + current_pitcher = game.get_pitcher() + if game.top_of_inning: + bat_team = game.teams["away"] + counter = self.counter_away + else: + bat_team = game.teams["home"] + counter = self.counter_home + + should_change_pitcher = False + if game.inning >= counter: + change_pitcher = True + if game.top_of_inning: + self.counter_home = self.counter_home - (self.counter_home % 5) + 5 + random.randint(1,4) #rounds down to last 5, adds up to next 5. then adds a random number 2<=x<=5 to determine next pitcher + else: + self.counter_away = self.counter_away - (self.counter_away % 5) + 5 + random.randint(1,4) + + if should_change_pitcher: + tries = 0 + while game.get_pitcher() == current_pitcher and tries < 3: + bat_team.set_pitcher(use_lineup = True) + tries += 1 + +class Drizzle(Weather): + def __init__(self): + super().__init__() + self.name = "Drizzle" + self.emoji = "🌧" + + def on_flip_inning(self, game): + if game.top_of_inning: + next_team = "away" + else: + next_team = "home" + + lineup = game.teams[next_team].lineup + game.bases[2] = lineup[(game.teams[next_team].lineup_position-1) % len(lineup)] + +class Sun2(Weather): + def __init__(self): + super().__init__() + self.name = "Sun 2" + def activate(self, game): + for teamtype in game.teams: + team = game.teams[teamtype] + if team.score >= 10: + team.score -= 10 + # no win counting yet :( + result.clear() + result.update({ + "text": "The {} collect 10! Sun 2 smiles.".format(team.name), + "text_only": True, + }) + +class NameSwappyWeather(Weather): + def __init__(self): + super().__init__() + self.name = "Literacy" + self.activation_chance = 0.01 + def activate(self, game): + if random.random() < self.activation_chance: + teamtype = random.choice(["away","home"]) + team = game.teams[teamtype] + player = random.choice(team.lineup) + old_player_name = player.name + if ' ' in player.name: + names = player.name.split(" ") + first_first_letter = names[0][0] + last_first_letter = names[-1][0] + names[0][0] = last_first_letter + names[-1][0] = first_first_letter + player.name = ' '.join(names) + else: + #name is one word, so turn 'bartholemew' into 'martholebew' + first_letter = player.name[0] + last_letter = player.name[-1] + player.name[0] = last_letter + player.name[-1] = first_letter + + result.clear() + result.update({ + "text": "{} is Literate! {} is now {}!".format(old_player_name,old_player_name, player.name), + "text_only": True, + }) + +class Feedback(Weather): + def __init__(self): + super().__init__() + self.name = "Feedback" + self.activation_chance = 0.01 + self.swap_batter_vs_pitcher_chance = 0.8 + def activate(self, game, result): + if random.random() < self.activation_chance: + # feedback time + result = {} + player1 = None + player2 = None + if random.random() < self.swap_batter_vs_pitcher_chance: + # swapping batters + # theoretically this could swap players already on base :( + homePlayerIndex = random.randint(len(teams["home"].lineup)) + awayPlayerIndex = random.randint(len(teams["away"].lineup)) + + homePlayer = teams["home"].lineup[homePlayerIndex] + awayPlayer = teams["away"].lineup[awayPlayerIndex] + + teams["home"].lineup[homePlayerIndex] = awayPlayer + teams["away"].lineup[awayPlayerIndex] = homePlayer + else: + # swapping pitchers + player1 = teams["home"].pitcher + player2 = teams["away"].pitcher + teams["home"].set_pitcher(player2) + teams["away"].set_pitcher(player1) + + result.clear() + result.update({ + "text": "{} and {} switched teams in the feedback!".format(player1.name,player2.name), + "text_only": True, + }) + +def all_weathers(): + weathers_dic = { + #"Supernova" : Supernova, + #"Midnight": Midnight, + #"Slight Tailwind": SlightTailwind, + "Heavy Snow": HeavySnow, +# "Twilight" : Twilight, +# "Thinned Veil" : ThinnedVeil, + "Heat Wave" : HeatWave, + "Drizzle" : Drizzle, # works +# Sun2, +# Feedback, +# NameSwappyWeather, + } + return weathers_dic +