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
                         table=MEGUCA_TABLE_NAME,
                         read_flag="read_only")

same_meguca = Meguca.FromMegucaRow(list(rows.values())[0][0])

print(same_meguca)

assert (new_meguca == same_meguca)

# Make a large city and try writing/reading it too.

# Default in-memory db
manager = DBManager(456)
# Test writing and reading a meguca from the DB. This ignores reconstructing friends, etc.
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)
    elif rand_val < 0.5:
        new_city.ContractMeguca(new_meguca.id)
        new_city.WitchMeguca(new_meguca.id)
    elif rand_val < 0.75:
        new_city.KillPotential(new_meguca.id)

new_city.WriteCityToDB(manager, forced=True)
Esempio n. 3
0
# Test Script to test some stuff
from copy import copy
import random

from Objs.Utils.GlobalDefines import *

from Objs.MegucaCity.MegucaCity import MegucaCity

new_city = MegucaCity(500)  # city_id = 500

# A simple test cycle. Set sensors, get new meguca, get new friend meguca, decay potential.
print("New Meguca!")
new_meguca = new_city.NewSensorMeguca()
print(new_meguca)

new_city.ContractMeguca(new_meguca.id)

friend_meguca = random.choice(list(new_city.contracted_megucas.values()))
print(friend_meguca.GetFriendlyName() + " brings friend!")
new_friend = new_city.NewMegucaFromFriend(friend_meguca)
print(new_friend)

print("But we don't contract.")

print("Decaying Potential...")
lost = new_city.PotentialDecay()
if lost:
    print("These megucas have lost potential and may no longer be contracted:")
    for l in lost:
        print(l.GetFriendlyName())
del lost
Esempio n. 4
0
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