def goal(self): """Prints generic win message and closes logger for program exit""" if not self.quit: # Winning message only printed if a player did not quit Logger.log('Player {} has won the game'.format(self.currentPlayer + 1)) self.closeLogger()
async def setup(): session = aiohttp.ClientSession() loop = asyncio.get_event_loop() database = Database(CONFIG.db_name, db_url=f"http://{CONFIG.host_name}:8123/") logger = Logger(database) dispatcher = DiffDepthStreamDispatcher(database, logger) logger.log_msg("Starting event loop...", LoggingLevel.INFO) for symbol in CONFIG.symbols: if "USD_" in symbol: loop.create_task( handle_depth_stream( symbol[4:], session, dispatcher, database, logger, loop, AssetType.USD_M, )) elif "COIN_" in symbol: loop.create_task( handle_depth_stream( symbol[5:], session, dispatcher, database, logger, loop, AssetType.COIN_M, )) else: loop.create_task( handle_depth_stream(symbol, session, dispatcher, database, logger, loop, AssetType.SPOT))
def executeMove(self): """Executes player-selected move when valid""" move = self.playerMoves[self.selectedMove] if not self.playerIsHuman(): # Print move selected by AI so human players can see selection Logger.log(' ' * 4, repr(move), '\n') # Execute move using type defined in moves dictionary self.moves[move.moveType](move)
def printBoard(self): """Prints game board for human players to analyze Note: Board layout and printing should be handled through the repr() method of a game's associated Board class """ if self.playerIsHuman(): Logger.log(repr(self.board), '\n')
def printMoves(self): """Retrieves possible moves for current player and prints list only for human players""" self.playerMoves = self.rulebook.getMoves(self) # Always add quit option to move list; can be overrided if game does not allow quits self.playerMoves += [Move(None, None, None, 'QUIT')] if self.playerIsHuman(): for i in range(len(self.playerMoves)): Logger.log('{:>4}. {}'.format(i + 1, repr(self.playerMoves[i]))) Logger.log('')
def chooseMove(self): try: Logger.log('Choose your next move:') userInput = input() # Attempt to force user input as integer selectedMove = int(userInput) - 1 Logger.log(str(selectedMove + 1), printLog=False) except ValueError: # Set input as invalid selection if error occurs selectedMove = -1 Logger.log(userInput, printLog=False) Logger.log('') return selectedMove
def main(_): # create log file open('logfile.txt', 'a').close() config = tf.ConfigProto(log_device_placement=True, allow_soft_placement=False) with tf.Session(config=config) as session: # Set Logger Output File sys.stdout = Logger(output_file='logfile.txt') model = Model(session) print('\n\t Start Training') model.train()
async def handle_depth_stream( symbol: str, session: ClientSession, dispatcher: DiffDepthStreamDispatcher, database: Database, logger: Logger, loop: AbstractEventLoop, asset_type: AssetType, ): next_full_fetch = time() logger.log_msg(f"Connecting to {asset_type.value + symbol} stream", LoggingLevel.INFO, symbol) prev_final_update_id = None while True: async with session.ws_connect(depth_stream_url(symbol, asset_type)) as ws: async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: try: data_raw = DiffDepthStreamMsg(**msg.json()) except ValidationError: print(msg.data) break s = data_raw.E / 1000.0 timestamp = datetime.utcfromtimestamp(s) if asset_type == AssetType.SPOT: first_update_id = data_raw.U final_update_id = data_raw.u else: first_update_id = data_raw.pu + 1 final_update_id = data_raw.u bids_quantity = [pairs[1] for pairs in data_raw.b] bids_price = [pairs[0] for pairs in data_raw.b] asks_quantity = [pairs[1] for pairs in data_raw.a] asks_price = [pairs[0] for pairs in data_raw.a] symbol = data_raw.s symbol_full = asset_type.value + symbol if next_full_fetch < time(): logger.log_msg( f"Fetching {symbol_full} full market depth", LoggingLevel.INFO, symbol_full, ) next_full_fetch += CONFIG.full_fetch_interval loop.create_task( get_full_depth(symbol, session, database, asset_type)) if (prev_final_update_id and prev_final_update_id + 1 != first_update_id): logger.log_msg( f"LOB dropped for {symbol_full}, refetching full market depth", LoggingLevel.INFO, symbol_full, ) dispatcher.insert( timestamp, first_update_id, final_update_id, bids_quantity, bids_price, asks_quantity, asks_price, symbol_full, ) if msg.type == aiohttp.WSMsgType.CLOSE: break logger.log_msg( f"Connection closed for {symbol_full} stream, retrying.", LoggingLevel.INFO, symbol, ) next_full_fetch = time()
def printQuit(self): """Prints quit message and associated player""" Logger.log('Player {} has quit the game'.format(self.currentPlayer + 1))
import random as rd from model import Logger as log from model import Holder as hld import matplotlib.pyplot as plt import time AREA_SIZE = 100 # HOW_MANY_WE_WANT_TO_SEE CELL_SIZE = 5 # SIZE OF SINGLE CELL TO DETERMINE WINDOW SIZE WINDOW_SIZE = AREA_SIZE * CELL_SIZE TIME = 11111 ENABLE_RANDOM_EVENTS = False AREA_NEW = np.zeros((AREA_SIZE, AREA_SIZE)) AREA_CURRENT = np.zeros((AREA_SIZE, AREA_SIZE)) LIFE, DEATH = 1, 0 DASHBOARD = np.zeros(10) LOG = log.Logger("logger") DB = hld.Holder("databaseXD") def main(): win = gp.GraphWin("GameLife", WINDOW_SIZE, WINDOW_SIZE) win.setBackground((gp.color_rgb(0, 0, 0))) bckg = gp.Image(gp.Point(WINDOW_SIZE / 2, WINDOW_SIZE / 2), WINDOW_SIZE, WINDOW_SIZE) populateAreaRandomly(AREA_CURRENT, AREA_SIZE, 14) l1, _ = countArea(AREA_CURRENT, AREA_SIZE) populateImageFromArea(bckg, AREA_CURRENT, CELL_SIZE, AREA_SIZE) bckg.draw(win) win.getMouse() newArea = AREA_CURRENT for i in range(0, TIME):
from model import Currency, Logger import time import threading from database import create_table, get_all_users, reset_field UPDATE_TIME = 5 GRAPH = 10 log = Logger("./history.txt", UPDATE_TIME) from queue_handler import init_bot, bot_loop, check_queue, update_queue create_table() init_bot() bot_thread = threading.Thread(target=bot_loop) bot_thread.start() btc = Currency('BTC', 'USD') eth = Currency('ETH', 'USD') btc_price = btc.get_price() eth_price = eth.get_price() last_prices = log.get_last_line() if not last_prices == None: last_prices = last_prices.split(",") btc_last_price = float(last_prices[1]) eth_last_price = float(last_prices[2]) btc_delta = (btc_last_price - btc_price) / btc_last_price * 100 eth_delta = (eth_last_price - eth_price) / eth_last_price * 100 else: btc_delta = 0.0 eth_delta = 0.0 log.log([btc_price, eth_price], [btc_delta, eth_delta]) while True: print("\n" * 20)
def printHand(self): """Prints player hand if any cards present""" if len(self.players[self.currentPlayer].hand): Logger.log("Player {}'s Hand: {}\n".format( self.currentPlayer + 1, repr(self.players[self.currentPlayer].hand)))
def printRound(self): """Prints round number if game allows rounds to be displayed""" # Round numbers are only printed after reaching the first player once per iteration if self.showRounds and self.currentPlayer == 0 and not self.invalid: roundNum = int(self.moveCount / len(self.players) + 1) Logger.log(' Round {} '.format(roundNum).center(50, '='), '\n')
def printBanner(self): """Prints banner containing name of game""" Logger.log('-' * 50) Logger.log('|', self.name.center(48), '|') Logger.log('-' * 50, '\n')
def printInvalidMoveMessage(self): """Prints invalid move message""" Logger.log('Invalid move selection. Please try again.', '\n')
def chooseSuit(self): # Randomly select suit to play selectedSuit = random.choice(range(0, 4)) Logger.log('Suit has been changed to {}\n'.format(suits[selectedSuit])) return selectedSuit
def chooseSuit(self): # Prints suits as list of options suitOptions = '' for i in range(len(suits)): suitOptions += '{:>4}. {}\n'.format(i + 1, suitCharacters[suits[i]]) # Continue asking for selected suit until valid input received selectedSuit = -1 while selectedSuit < 0: Logger.log(suitOptions, '\n', 'Choose suit to switch to:') try: userInput = input() # Attempt to force use input as integer selectedSuit = int(userInput) - 1 Logger.log(str(selectedSuit + 1), printLog=False) except ValueError: # Set input as invalid selection if error occurs selectedSuit = -1 Logger.log(userInput, printLog=False) Logger.log('') if not selectedSuit in range(0, 4): # Print invalid selection message if index out of bounds Logger.log('Invalid suit selection. Please try again.', '\n') selectedSuit = -1 Logger.log('Suit has been changed to {}\n'.format(suits[selectedSuit])) return selectedSuit
def closeLogger(self): """Closes logger, used at program exit""" Logger.close()