def __init__(self, args, manager=None): # Initial object set up self.city_id = args.city_id self.db_path = args.db_path self.manager = DBManager(self.city_id, self.db_path) if manager is None else manager self.manager.CreateTableIfDoesNotExist(RUNNING_TABLE_FIELDS, table=RUNNING_TABLE_NAME) # Check if game is already running. If so, read from existing game. If not, start new game. potential_row = self.manager.ReadTable( RUNNING_ROW, RUNNING_PRIMARY_KEYS, {"CityId": self.city_id}, table=RUNNING_TABLE_NAME, read_flag="expected_modification") if not potential_row or args.restart: # Start New Game self.ClearExistingGame() self.manager.CreateTableIfDoesNotExist(MEGUCA_TABLE_FIELDS, table=MEGUCA_TABLE_NAME) self.manager.CreateTableIfDoesNotExist(VOTING_TABLE_FIELDS, table=VOTING_TABLE_NAME) self.city = MegucaCity(self.city_id) self.state = State(self.manager) for i, pop_count in enumerate(INITIAL_MEGUCA_POPULATION): for _ in range(pop_count): new_meguca = self.city.NewSensorMeguca() if i >= 1: self.city.ContractMeguca(new_meguca.id, None) if i == 2: self.city.WitchMeguca(new_meguca.id, None) elif i == 3: self.city.KillMeguca(new_meguca.id) # TODO: Add an introduction phase. self.phase = PHASE_ORDER[0] self.state.current_phase = self.phase.__name__ self.new_game = True else: # Reload existing game. self.city = MegucaCity.ReadCityFromDb(self.city_id, self.manager) self.state = State(self.manager) self.phase = self.PHASE_DICT[self.state.current_phase] self.new_game = False
import random import sqlite3 from Objs.DBManager.Defines import * from Objs.Utils.GlobalDefines import * from Objs.DBManager.DBManager import DBManager from Objs.Meguca.Defines import * from Objs.Meguca.Meguca import Meguca from Objs.MegucaCity.MegucaCity import MegucaCity fake_city_id = 500 # Default in-memory db manager = DBManager(fake_city_id) # Write an exception manager.WriteExceptionState("Test Exception") # Check db explicitly without using object. c = manager.connection.cursor() rows = c.execute("SELECT * FROM {}".format(EXCEPTION_TABLE_NAME)) # print columns print([x[0] for x in c.description]) # print rows for row in rows: print(row) # Test writing and reading a meguca from the DB. This ignores reconstructing friends, etc.
import random import sqlite3 from Objs.DBManager.Defines import * from Objs.Utils.GlobalDefines import * from Objs.DBManager.DBManager import DBManager from Objs.Meguca.Defines import * from Objs.Meguca.Meguca import Meguca from Objs.MegucaCity.MegucaCity import MegucaCity # Make a large city and try writing it. manager = DBManager(456, db_path="Data\ExampleDb.sqlite3") manager.CreateTableIfDoesNotExist(MEGUCA_TABLE_FIELDS, table=MEGUCA_TABLE_NAME) new_city = MegucaCity(456) # city_id = 456 for _ in range(50): new_meguca = new_city.NewSensorMeguca() # Hardcode just for testing here rand_val = random.random() if rand_val < 0.25: new_city.ContractMeguca(new_meguca.id, None) elif rand_val < 0.5: new_city.ContractMeguca(new_meguca.id, None) new_city.WitchMeguca(new_meguca.id, None) elif rand_val < 0.75: new_city.KillPotential(new_meguca.id) new_city.WriteCityToDB(manager, forced=True) manager.Commit()
class Main: PHASE_DICT = {x.__name__: x for x in PHASE_ORDER} def __init__(self, args, manager=None): # Initial object set up self.city_id = args.city_id self.db_path = args.db_path self.manager = DBManager(self.city_id, self.db_path) if manager is None else manager self.manager.CreateTableIfDoesNotExist(RUNNING_TABLE_FIELDS, table=RUNNING_TABLE_NAME) # Check if game is already running. If so, read from existing game. If not, start new game. potential_row = self.manager.ReadTable( RUNNING_ROW, RUNNING_PRIMARY_KEYS, {"CityId": self.city_id}, table=RUNNING_TABLE_NAME, read_flag="expected_modification") if not potential_row or args.restart: # Start New Game self.ClearExistingGame() self.manager.CreateTableIfDoesNotExist(MEGUCA_TABLE_FIELDS, table=MEGUCA_TABLE_NAME) self.manager.CreateTableIfDoesNotExist(VOTING_TABLE_FIELDS, table=VOTING_TABLE_NAME) self.city = MegucaCity(self.city_id) self.state = State(self.manager) for i, pop_count in enumerate(INITIAL_MEGUCA_POPULATION): for _ in range(pop_count): new_meguca = self.city.NewSensorMeguca() if i >= 1: self.city.ContractMeguca(new_meguca.id, None) if i == 2: self.city.WitchMeguca(new_meguca.id, None) elif i == 3: self.city.KillMeguca(new_meguca.id) # TODO: Add an introduction phase. self.phase = PHASE_ORDER[0] self.state.current_phase = self.phase.__name__ self.new_game = True else: # Reload existing game. self.city = MegucaCity.ReadCityFromDb(self.city_id, self.manager) self.state = State(self.manager) self.phase = self.PHASE_DICT[self.state.current_phase] self.new_game = False # TODO: Handle ending a game. def Run(self): vote_result = -1 vote_row = None results = [] if self.new_game: # Run the game starting phase. results.append( StartGameEvent(self.city).Run(self.state, vote_result)) else: # Get voting information. # TODO: Put this in the Communication Objects? vote_row = self.manager.ReadTable( VOTING_ROW, VOTING_PRIMARY_KEYS, { "CityId": self.city_id, "MostRecentEvent": 1 }, table=VOTING_TABLE_NAME, read_flag="expected_modification") if vote_row: assert (len(vote_row) == 1) row_data = tuple(vote_row.values())[0][0] vote_result = row_data.VoteResultInteger if vote_result == -1: raise AssertionError("Vote result not set! Is this correct?") # Make an instance of the phase this_phase = self.phase(self.city) while True: result = this_phase.Run(self.state, vote_result) results.append(result) # Is the phase done? If so, increment our own phase. event_done = Phase.CheckIfEventDone(self.state, this_phase.event_name) if event_done: # We can make this arbitrarily complex, but for now this is fine. new_phase_index = (PHASE_ORDER.index(self.phase) + 1) % (len(PHASE_ORDER)) self.phase = PHASE_ORDER[new_phase_index] self.state.current_phase = self.phase.__name__ # Does this result have a vote? if Phase.CheckIfVote(result): # If so, we're done and should return output. break if event_done: this_phase = self.phase(self.city) vote_result = -1 # We no longer have a vote result if we're continuing events. # Set original voting information to not most recent. if vote_row is not None: for key, single_row in vote_row.items(): vote_row[key] = (single_row[0]._replace(MostRecentEvent=0), True) else: vote_row = {} # Add new voting information vote_row[frozenset({self.city_id, results[-1].timestamp})] = (VOTING_ROW( self.city_id, results[-1].timestamp, json.dumps([r.output_text for r in results]), json.dumps(results[-1].votable_options), -1, 1), True) for result in results: print(result.output_text + "\n") # For readability when running in terminal for i, option in enumerate(results[-1].votable_options): print(f"{i}: {option}") self.manager.WriteTable(vote_row, [x[0] for x in VOTING_TABLE_FIELDS], table=VOTING_TABLE_NAME, forced=self.new_game) self.FinalizeGameOutput() def FinalizeGameOutput(self): if self.new_game: self.manager.WriteTable( {frozenset({self.city_id}): (RUNNING_ROW(self.city_id), True)}, [x[0] for x in RUNNING_TABLE_FIELDS], table=RUNNING_TABLE_NAME) else: self.manager.MarkWritten(table=RUNNING_TABLE_NAME) self.city.WriteCityToDB(self.manager, forced=True) self.state.WriteState() self.manager.Commit() def ClearExistingGame(self): pass
print(f"{i}: {option}") self.manager.WriteTable(vote_row, [x[0] for x in VOTING_TABLE_FIELDS], table=VOTING_TABLE_NAME, forced=self.new_game) self.FinalizeGameOutput() def FinalizeGameOutput(self): if self.new_game: self.manager.WriteTable( {frozenset({self.city_id}): (RUNNING_ROW(self.city_id), True)}, [x[0] for x in RUNNING_TABLE_FIELDS], table=RUNNING_TABLE_NAME) else: self.manager.MarkWritten(table=RUNNING_TABLE_NAME) self.city.WriteCityToDB(self.manager, forced=True) self.state.WriteState() self.manager.Commit() def ClearExistingGame(self): pass if __name__ == '__main__': args = parser.parse_args() manager = DBManager(args.city_id, args.db_path) try: main = Main(args, manager) main.Run() except Exception as e: manager.WriteExceptionState(str(e)) raise e
new_city = MegucaCity(fake_city_id) # city_id = 500 # First let's make a bunch of gucas. for _ in range(50): new_meguca = new_city.NewSensorMeguca() # Hardcode just for testing here rand_val = random.random() if rand_val < 0.25: new_city.ContractMeguca(new_meguca.id, None) elif rand_val < 0.5: new_city.ContractMeguca(new_meguca.id, None) new_city.WitchMeguca(new_meguca.id, None) elif rand_val < 0.75: new_city.KillPotential(new_meguca.id) manager = DBManager(fake_city_id) manager.CreateTableIfDoesNotExist(MEGUCA_TABLE_FIELDS, table=MEGUCA_TABLE_NAME) new_state = State(manager) # Select a meguca as the meguca to apply the ContractMeguca Event to (would normally be set by other event) event_instance = NewContractableMegucaEvent(new_city) event_instance.Run(new_state) # Write to db. new_state.WriteState() manager.Commit() recovered_state = State(manager)
from IncubatorFarming import Main parser = argparse.ArgumentParser( description='Incubator Farming Manual Run Script') parser.add_argument('city_id', type=int, help='An id that defines the city for this run.') parser.add_argument('db_path', help='The location of the db file this game is stored in.') parser.add_argument('--restart', action='store_true', help='Dummy Argument for Manual Running, do not use.') if __name__ == '__main__': args = parser.parse_args() manager = DBManager(args.city_id, args.db_path) while True: main = Main(args, manager) # TEMPORARY: Starting Truth for testing main.state.truth_level = 0.5 main.Run() while True: try: string_vote = input("Vote? ") if (string_vote == "q"): raise AssertionError( "There is no other way to exit this program >_>") vote = int(string_vote) break except (TypeError, ValueError): print("Invalid input!")