def test_no_start_evaluate_None(self): ''' ''' timestamp = datetime.datetime(2018, 4, 23, 0, 0) sch = Schedule(None, DEFAULT_STOP, DEFAULT_ZONE, DEFAULT_DAYS) target = sch.evaluate(timestamp) self.assertEqual(target, None)
def test_no_stop_evaluate_True(self): ''' ''' timestamp = datetime.datetime(2018, 4, 23, 12, 0) sch = Schedule(DEFAULT_START, None, DEFAULT_ZONE, DEFAULT_DAYS) target = sch.evaluate(timestamp) self.assertEqual(target, True)
def test_evaluate_False(self): ''' ''' timestamp = datetime.datetime(2018, 4, 23, 23, 0) sch = Schedule(DEFAULT_START, DEFAULT_STOP, DEFAULT_ZONE, DEFAULT_DAYS) target = sch.evaluate(timestamp) self.assertEqual(target, False)
def setUp(self): self.scheduler = Scheduler() self.schedules = self.scheduler.scheduler(10, 'activities.txt') self.schedules_1 = Schedule() self.schedules_2 = Schedule() self.schedules_1.agenda = [('Giant Puzzle Dinosaurs', 30), ('Enigma Challenge', 45), ('Human Table Football', 30)] self.schedules_2.agenda = [('Salsa & Pickles', 15), ('Indiano Drizzle', 45), ('Buggy Driving', 30)]
def test_empty_start_stop(self): ''' ''' with self.assertRaises(ValueError) as cm: sch = Schedule(None, None, DEFAULT_ZONE, DEFAULT_DAYS) self.assertRegex(cm.exception.args[0], 'start_time or stop_time must be set')
def test_invalid_start_stop(self): ''' ''' with self.assertRaises(ValueError) as cm: sch = Schedule(DEFAULT_START, DEFAULT_START, DEFAULT_ZONE, DEFAULT_DAYS) self.assertRegex(cm.exception.args[0], 'stop_time ".*" must be after start_time ".*"')
def test_invalid_stop_type(self): ''' ''' stop = '22:00' with self.assertRaises(TypeError) as cm: sch = Schedule(DEFAULT_START, stop, DEFAULT_ZONE, DEFAULT_DAYS) self.assertRegex(cm.exception.args[0], 'stop_time must be a datetime.time object')
def test_invalid_zone_type(self): ''' ''' zone = 'UTC' with self.assertRaises(TypeError) as cm: sch = Schedule(DEFAULT_START, DEFAULT_STOP, zone, DEFAULT_DAYS) self.assertRegex(cm.exception.args[0], 'time_zone must be a datetime.tzinfo object')
def test_invalid_days_value(self): ''' ''' days = set(['mon','tue','wed','thu','fri']) with self.assertRaises(TypeError) as cm: sch = Schedule(DEFAULT_START, DEFAULT_STOP, DEFAULT_ZONE, days) self.assertRegex(cm.exception.args[0], 'days must be a set of scheduler.Day')
def test_create_from_string(self): ''' ''' sch = Schedule.from_string(DEFAULT_SCHEDULE_STRING) self.assertTrue(sch) self.assertEqual(sch.start_time, DEFAULT_START) self.assertEqual(sch.stop_time, DEFAULT_STOP) self.assertEqual(sch.time_zone, DEFAULT_ZONE) self.assertEqual(sch.days, DEFAULT_DAYS)
def test_create(self): ''' Create a schedule object ''' sch = Schedule(DEFAULT_START, DEFAULT_STOP, DEFAULT_ZONE, DEFAULT_DAYS) self.assertTrue(sch) self.assertEqual(sch.start_time, DEFAULT_START) self.assertEqual(sch.stop_time, DEFAULT_STOP) self.assertEqual(sch.time_zone, DEFAULT_ZONE) self.assertEqual(sch.days, DEFAULT_DAYS)
def test_create_empty_stop(self): ''' ''' sch = Schedule(DEFAULT_START, None, DEFAULT_ZONE, DEFAULT_DAYS) self.assertTrue(sch) self.assertEqual(sch.start_time, DEFAULT_START) self.assertEqual(sch.stop_time, None) self.assertEqual(sch.time_zone, DEFAULT_ZONE) self.assertEqual(sch.days, DEFAULT_DAYS)
def execute_schedule(self, schedule, track_full_pass=False, compute_ant_points=True, N=None): if self._disabled: # Note, the scheduler itself is also enabled/disabled. But also want to prevent the creation of new schedules. raise Exception( "RPCSchedulerServer: Currently disabled. Call enable() first") schedule = Schedule.from_json(schedule) self.scheduler = Scheduler(self.gs, schedule, track_full_pass=track_full_pass, compute_ant_points=compute_ant_points, enforce_signoffs=self._enforce_signoffs) self.scheduler.execute(N=N)
def send_schedule(date: str): group = db.get_group_of_user(event["message"]["from_id"]) gid = db.get_schedule_descriptor(group) s = Schedule(date, gid) s.get_raw() if s.is_exist(): sch = s.generate() bot.send_message(msg=sch, pid=event["message"]["from_id"]) else: bot.send_message(msg="Расписание отсутствует.", pid=event["message"]["from_id"])
def __init__(self): #window setup pygame.display.set_caption('Necromonster') pygame.display.set_icon(pygame.image.load(os.path.join('rec', 'misc', 'icon.png'))) self.main_path = os.getcwd() # initiate the clock and screen self.clock = pygame.time.Clock() self.last_tick = pygame.time.get_ticks() self.screen_res = [900, 650] self.center_point = [470., 350.] self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32) #DEBUG values self.DEBUG = 1 self.RECT_DEBUG = 0 #Init custom game classe(s) self.EntityHandler = EntityHandler(self) self.Scheduler = Schedule(self) self.Projectile = Projectile self.Monster = Monster self.Item = Item self.Invent = Invent(self) self.Weapon = Weapon self.Garment = Garment self.Player = Player(self) self.HUD = HUD(self) # Init entity manager vars self.entities = [] # load fonts, create font list self.text_list = [] self.default_font = pygame.font.SysFont(None, 20) # get the map that you are on self.blit_list = mapLoader.load('home', self) self.Item(self, 'Mythril', [350, 400], world=1) while 1: self.Loop()
def get_scheduled_instances(self): instances = [] ec2 = boto3.client('ec2') regions = [ region['RegionName'] for region in ec2.describe_regions()['Regions'] ] for region in regions: ec2 = boto3.client('ec2', region_name=region) # TODO: Add filters to ignore the following instances # Instance State = shutting-down or terminated # Instances in auto-scaling groups filters = [{'Name': 'tag-key', 'Values': [EC2.SCHEDULE_TAG]}] result = ec2.describe_instances(Filters=filters) # TODO: Get rid of this double 'for' loop for reservation in result['Reservations']: for ec2_instance in reservation['Instances']: id = region + ':' + ec2_instance['InstanceId'] running = self._get_state(ec2_instance['State']) schedule = self._get_schedule(ec2_instance['Tags']) logger.info( 'Instance [{}]: Running= {} Schedule= {}'.format( id, running, schedule)) # Ignore instances that are not running or stopped if running != None: try: instances.append( Instance(id, running, Schedule.from_string(schedule), provider.aws.EC2(id))) except Exception as e: logger.error('Instance [{}]: {}'.format(id, e)) return instances
import logging import pytz import datetime from scheduler import Instance, Schedule, Day DEFAULT_ID = 0 DEFAULT_START = datetime.time(hour=10, minute=0) DEFAULT_STOP = datetime.time(hour=22, minute=0) DEFAULT_ZONE = pytz.timezone('UTC') DEFAULT_DAYS = set( [Day.Mon, Day.Tue, Day.Wed, Day.Thu, Day.Fri, Day.Sat, Day.Sun]) DEFAULT_SCHEDULE = Schedule(DEFAULT_START, DEFAULT_STOP, DEFAULT_ZONE, DEFAULT_DAYS) NO_START_SCHEDULE = Schedule(None, DEFAULT_STOP, DEFAULT_ZONE, DEFAULT_DAYS) NO_STOP_SCHEDULE = Schedule(DEFAULT_START, None, DEFAULT_ZONE, DEFAULT_DAYS) logger = logging.getLogger() logger.setLevel(logging.WARNING) logger.addHandler(logging.StreamHandler()) class InstanceTestCase(unittest.TestCase): """ Unit tests for Instance """ ######################################################################
class Necro(): def __init__(self): """ Main game class initialization. All other class references point to this class as "game" """ # window setup pygame.display.set_caption('Necromonster') pygame.display.set_icon(pygame.image.load(os.path.join('rec', 'misc', 'icon.png'))) self.main_path = os.getcwd() # initiate the clock and screen object self.clock = pygame.time.Clock() self.FPS = 50 self.last_tick = pygame.time.get_ticks() self.screen_res = [900, 650] self.center_point = [470, 350] self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32) #DEBUG values self.DEBUG = 1 self.RECT_DEBUG = 0 self.angle = 0 #Init and assign custom game class(es) self.EntityHandler = EntityHandler(self) self.ParticleManager = ParticleManager(self) self.Scheduler = Schedule(self) self.Entity = Entity self.Projectile = Projectile self.Monster = Monster self.NPC = NPC self.NPCText = NPCText self.Item = Item self.Inventory = Invent self.Invent = self.Inventory(self) self.Weapon = Weapon self.Garment = Garment self.Player = Player(self) self.HUD = HUD(self) # Init entity manager vars self.entities = [] self.shadows = [] # load fonts, create font list # do not use pygame.font.SysFont! self.text_list = [] self.default_font = pygame.font.Font(os.path.join('rec', 'font', 'freesansbold.ttf'), 15) self.speak_font = pygame.font.Font(os.path.join('rec', 'font', 'freesansbold.ttf'), 30) # load the map that player is on self.INSIDE = 0 self.blit_list = mapLoader.load('home', self) # spawn initial map items/entities self.Item(self, 'Mythril', [350, 400], world=1) self.NPC(self, "blacksmith", [400, 400], 100, 'still') for i in xrange(4): self.Monster(self, 'chicken', [200+(i*50),650], 1, 'neutral') self.Monster(self, "goop", [100, 100], 1, 'aggressive') # begin main game loop while 1: self.Loop() def Loop(self): """ Main loop of the game. Calls tick, draw, and event processing functions. Tick and draw are only called every 20 milliseconds """ self.eventLoop() self.Tick() self.Draw() pygame.display.update() def eventLoop(self): """ Uses pygame event handling to process keypresses and mouse clicks. Used for chat, interacting with objects, and inventory management """ for event in pygame.event.get(): event # prevents exit button freeze up if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: # toggle chat bar active if not self.HUD.chat_active: if event.key == K_e: self.Invent.toggleView() if event.key == K_t: #activate the chat bar self.HUD.chat_message = '' self.HUD.chat_active = 1 self.Player.can_move = 0 return 0 # process chat messages. Remove or add characters while chat box is open if event.key == K_ESCAPE or event.key == K_RETURN: self.HUD.processCommand(self.HUD.chat_message) self.HUD.chat_active = 0 self.Player.can_move = 1 self.HUD.chat_message = '' elif event.key == K_BACKSPACE: self.HUD.chat_message = self.HUD.chat_message[:-1] elif event.key <= 255: char = chr(event.key) if self.keys_pressed[K_LSHIFT] or self.keys_pressed[K_RSHIFT]: char = char.upper() self.HUD.chat_message += char # interaction with entities on space bar press if event.key == K_SPACE: for monster in self.EntityHandler.monsters: if monster.NPC: if monster.isPlayerClose(75) and monster.interacting == False: monster.interacting = True elif not monster.isPlayerClose(75) or monster.interacting == True: monster.interacting = False self.HUD.delPrompt() # inventory management, checks for item throws, and placement in slots. elif event.type == MOUSEBUTTONDOWN: self.Invent.last_click = pygame.mouse.get_pos() if self.Invent.in_hand: self.Invent.testThrow(self.Invent.last_click) if self.Invent.shown: self.Invent.inventClick(self.Invent.last_click) elif pygame.mouse.get_pressed()[0]: self.Player.attack(pygame.mouse.get_pos()) def Tick(self): """ Updates all game math and entity states. No drawing is done. """ ttime = self.clock.tick(self.FPS) self.keys_pressed = pygame.key.get_pressed() if self.keys_pressed[K_EQUALS]: self.HUD.daytime_start -= 3 if self.keys_pressed[K_MINUS]: self.HUD.daytime_start += 3 self.Scheduler.update() self.EntityHandler.updateAll(ttime) self.Invent.update() self.HUD.updateDay() for index, text in enumerate(self.text_list): if text[2]: raise DeprecationWarning self.last_tick = pygame.time.get_ticks() def off(self, coords): """ Offsets image coordinates to appear correct from the view of the player. Should be called on all surface coordinates before blitting. """ newx = coords[0] - self.Player.player_r.x + 450 newy = coords[1] - self.Player.player_r.y + 325 return [newx, newy] def unoff(self, coords): """ Removes the offset created by the off() function. """ newx = coords[0] + self.Player.player_r.x - 450 newy = coords[1] + self.Player.player_r.y - 325 return [newx, newy] def getCenterBlit(self, surface, pos): pos[0] = pos[0] + surface.get_width() / 2 pos[1] = pos[1] + surface.get_height() / 2 return pos def rotopoint(self, surface, angle, pos): size = surface.get_size() if pos[0] > size[0]/2 or pos[1] > size[1]/2: print 'BIG ASS HONKEY' new_surf_size = [(size[0] - pos[0])*2, (size[1] - pos[1])*2] new_surf_blit_pos = [new_surf_size[0] - size[0], new_surf_size[1] - size[1]] new_surf = pygame.Surface(new_surf_size, pygame.SRCALPHA, 32) new_surf.blit(surface, new_surf_blit_pos) return pygame.transform.rotate(new_surf, angle) def testrot(self, image, angle): loc = image.get_rect().center new_rot = pygame.transform.rotate(image, angle) new_rot.get_rect(center=loc) return new_rot, new_rot.get_rect() def Draw(self): """ Completes all blitting to the screend object, includes HUD updates. """ tile_width = self.tile[1][0] tile_height = self.tile[1][1] tile_extrax = self.Player.player_r.x % tile_width tile_extray = self.Player.player_r.y % tile_height y = 0 for i in xrange(self.screen_res[1] / tile_height + 3): for i in xrange(self.screen_res[0] / tile_width + 3): self.screen.blit(self.tile[0], [i * tile_width - tile_width - tile_extrax, y - tile_height - tile_extray]) y += self.tile[1][1] if self.shadows: for s in self.shadows: s.update(self.screen) for surf in self.blit_list: if 'player' in surf: self.EntityHandler.blitAll() else: self.screen.blit(surf[0], self.off(surf[1])) for text in self.text_list: self.screen.blit(text[0], text[1]) if self.Invent.shown: self.Invent.draw() if self.DEBUG: self.screen.blit(self.default_font.render(str(round(self.clock.get_fps())), True, (255, 255, 255)), [0, 0]) self.screen.blit(self.default_font.render(str('%s, %s' % (self.Player.player_r.x, self.Player.player_r.y)), True, (255, 255, 255)), [0, 12]) self.screen.blit(self.default_font.render(str(pygame.mouse.get_pos()), True, (255, 255, 255)), [0, 24]) if self.RECT_DEBUG: ps = pygame.Surface(self.Player.player_dims) ps.fill([255, 0, 0]) self.screen.blit(ps, self.off([self.Player.player_r.x, self.Player.player_r.y])) #Draws player and head text if it exists if self.Player.head_drawn: if self.Player.head_drawn[3]: self.screen.blit(self.Player.head_drawn[0], self.Player.head_drawn[1]) else: self.Player.game.screen.blit(self.Player.head_drawn[0], self.off(self.Player.head_drawn[1])) self.ParticleManager.update() if self.Player.map_change: self.HUD.updateMapTrans() self.HUD.blitHUD()
def simulate(params): class ClientSim(object): def __init__(self, env, films_list: list, schedule: Schedule): self.client = Client(films_list) self.client.statistics['hall'] = {} self.action = env.process(self.run()) self.env = env self.schedule = schedule self.client.statistics['schedule'] = schedule self.available_sessions = [] def run(self): if len(ticket_shop.queue) * 1.5 <= len( food_shop.queue ): # TODO: передать ticket и food кассы в класс при инициализации with ticket_shop.request() as req: self.client.statistics['went to cinema'] = self.env.now yield req yield self.env.process(self.buy_ticket()) if self.client.drink_preference + self.client.food_preference != 0: with food_shop.request() as req: yield req yield self.env.process(self.buy_snacks()) else: if self.client.food_preference + self.client.drink_preference != 0: with food_shop.request() as req: yield req yield self.env.process(self.buy_snacks()) with ticket_shop.request() as req: self.client.statistics['went to cinema'] = self.env.now yield req yield self.env.process(self.buy_ticket()) def get_available_sessions(self) -> list: now = self.new_now(self.env.now) now_minus_30min = now - datetime.timedelta(minutes=30) now_plus_1hour = now + datetime.timedelta(hours=1) sessions = [] for i in range(len(self.schedule.queues)): for j in range(len(self.schedule.queues[i])): start_time = self.schedule.queues[i][j].start_time free_sits = self.schedule.queues[i][j].free_sits if now_minus_30min < start_time < now_plus_1hour and free_sits > 0\ and self.schedule.queues[i][j].available is True: sessions.append(self.schedule.queues[i][j]) return sessions def choise_session(self): for i in self.client.films: session_dict = dict([(session.film_name, session) for session in self.available_sessions]) session_films = [ session.film_name for session in self.available_sessions ] if i.name in session_films: return session_dict[i.name] return None # возвращаем пустоту, если для клиента нет подходящего фильма def new_now(self, now): return datetime.datetime.combine( datetime.date.today() + datetime.timedelta( days=(8 + round(now) // 60) // 24), # точный день datetime.time((8 + round(now) // 60) % 24, round(now) % 60)) def buy_ticket(self): # TODO: когда кончаются билеты удалить сессию из расписания (сделать недоступной) self.available_sessions = self.get_available_sessions() self.chosen_session = self.choise_session() if self.chosen_session is not None: self.chosen_session.free_sits -= 1 if self.chosen_session.free_sits == 0: self.chosen_session.available = False self.client.statistics['bought ticket'] = True self.client.statistics['film'] = self.chosen_session.film_name self.client.statistics['hall'][ 'capacity'] = self.chosen_session.capacity self.client.statistics['hall'][ 'name'] = self.chosen_session.hall_name now = self.new_now(self.env.now) self.client.statistics['ticket buying time'] = self.env.now self.client.statistics[ 'session begining time'] = self.chosen_session.start_time self.client.statistics['spend money'] = self.chosen_session.ticket_price +\ (self.client.food_preference + self.client.drink_preference)*250 print(f'{self.client.id} bought ticket at {now}') print(f'на фильм {self.chosen_session.film_name} осталось' f' {self.chosen_session.free_sits} билетов') yield self.env.timeout(0.5) else: self.client.statistics['bought ticket'] = False self.client.statistics['ticket buying time'] = None print(f'{self.client.id} didnt find needed film and went away') def buy_snacks(self): now = self.new_now(self.env.now) self.client.statistics['snacks buying time'] = now timeout_snacks = self.client.drink_preference + self.client.food_preference self.client.statistics['bought snacks'] = timeout_snacks print(f'{self.client.id} bought snacks at {now}') yield self.env.timeout(timeout_snacks) daily_schedule = Schedule(FILMS_COUNT, HALLS_COUNT) print(daily_schedule) # films_for_choice = daily_schedule.films_list env = simpy.Environment() ticket_shop = simpy.Resource(env, capacity=TICKET_SHOP_CAPACITY) food_shop = simpy.Resource(env, capacity=FOOD_SHOP_CAPACITY) clients = [] def client_creating(env, clients): for i in range(CLIENT_COUNT): client = ClientSim(env, films_for_choice, daily_schedule) clients.append(client) yield env.timeout(CLIENT_GEN_TIMEOUT) env.process(client_creating(env, clients)) env.run(until=990) # Перенос статистики в файл statistic = [] for i in range(clients.__len__()): statistic.append(clients[i].client.statistics) with open('sim.pickle', 'wb') as writer: pickle.dump(statistic, writer)
elif (db.get_session_state( event["message"]["from_id"]) == "ask_for_schedule_date"): if re.match(r"^\d\d(.|-|/)\d\d(.|-|/)20\d\d$", event["message"]["text"]): try: d = datetime.datetime.strptime( event["message"]["text"], "%d-%m-%Y").strftime("%Y-%m-%d") except ValueError: bot.send_message( msg="Неверный формат даты. Попробуйте еще раз.", pid=event["message"]["from_id"], ) else: group = db.get_group_of_user(event["message"]["from_id"]) s = Schedule(d, group) s.get_raw() if s.is_exist(): schedule = s.generate() bot.send_message( msg=schedule, pid=event["message"]["from_id"], keyboard=kbs.generate_schedule_keyboard(), ) db.update_session_state(event["message"]["from_id"], "main") else: bot.send_message( msg= "Расписание отсутствует.\nПопробуй указать другую " "дату.",
class Necro(): def __init__(self): #window setup pygame.display.set_caption('Necromonster') pygame.display.set_icon(pygame.image.load(os.path.join('rec', 'misc', 'icon.png'))) self.main_path = os.getcwd() # initiate the clock and screen self.clock = pygame.time.Clock() self.last_tick = pygame.time.get_ticks() self.screen_res = [900, 650] self.center_point = [470., 350.] self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32) #DEBUG values self.DEBUG = 1 self.RECT_DEBUG = 0 #Init custom game classe(s) self.EntityHandler = EntityHandler(self) self.Scheduler = Schedule(self) self.Projectile = Projectile self.Monster = Monster self.Item = Item self.Invent = Invent(self) self.Weapon = Weapon self.Garment = Garment self.Player = Player(self) self.HUD = HUD(self) # Init entity manager vars self.entities = [] # load fonts, create font list self.text_list = [] self.default_font = pygame.font.SysFont(None, 20) # get the map that you are on self.blit_list = mapLoader.load('home', self) self.Item(self, 'Mythril', [350, 400], world=1) while 1: self.Loop() def Loop(self): # main game loop self.eventLoop() if pygame.time.get_ticks() - self.last_tick > 20: self.Tick() self.Draw() pygame.display.update() def eventLoop(self): # the main event loop, detects keypresses for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: if not self.HUD.chat_active: if event.key == K_e: self.Invent.toggleView() if event.key == K_t: #activate the chat bar self.HUD.chat_message = '' self.HUD.chat_active = 1 self.Player.can_move = 0 return 0 if event.key == K_ESCAPE or event.key == K_RETURN: message = self.HUD.chat_message.split() if len(message) >1: if len(message) > 2: self.HUD.command(message[0], message[1], message[2]) else: self.HUD.command(message[0], message[1]) self.HUD.chat_active = 0 self.Player.can_move = 1 self.HUD.chat_message = '' elif event.key == K_BACKSPACE: self.HUD.chat_message = self.HUD.chat_message[:-1] elif event.key <= 255: char = chr(event.key) if self.keys_pressed[K_LSHIFT] or self.keys_pressed[K_RSHIFT]: char = char.upper() self.HUD.chat_message += char elif event.type == MOUSEBUTTONDOWN: if self.Invent.in_hand: self.Invent.testThrow(pygame.mouse.get_pos()) if self.Invent.shown: self.Invent.inventClick(pygame.mouse.get_pos()) elif pygame.mouse.get_pressed()[0]: self.Player.attack(pygame.mouse.get_pos()) def Tick(self): # updates to player location and animation frame ttime = self.clock.tick() self.keys_pressed = pygame.key.get_pressed() self.Scheduler.update() self.EntityHandler.updateAll(ttime) self.Invent.update() for index, text in enumerate(self.text_list): if text[2]: raise DeprecationWarning self.last_tick = pygame.time.get_ticks() def off(self, coords): newx = coords[0] - self.Player.player_r.x + 450 newy = coords[1] - self.Player.player_r.y + 325 return [newx, newy] def Draw(self): #Responsible for calling all functions that draw to the screen tile_width = self.tile[1][0] tile_height = self.tile[1][1] tile_extrax = self.Player.player_r.x % tile_width tile_extray = self.Player.player_r.y % tile_height y = 0 for i in xrange(self.screen_res[1] / tile_height + 3): for i in xrange(self.screen_res[0] / tile_width + 3): self.screen.blit(self.tile[0], [i * tile_width - tile_width - tile_extrax, y - tile_height - tile_extray]) y += self.tile[1][1] for surf in self.blit_list: if 'player' in surf: self.EntityHandler.blitAll() else: self.screen.blit(surf[0], self.off(surf[1])) for text in self.text_list: self.screen.blit(text[0], text[1]) if self.Invent.shown: self.Invent.draw() if self.DEBUG: self.screen.blit(self.default_font.render(str(round(self.clock.get_fps())), True, (255, 255, 255)), [0, 0]) self.screen.blit(self.default_font.render(str('%s, %s' % (self.Player.player_r.x, self.Player.player_r.y)), True, (255, 255, 255)), [0, 12]) self.screen.blit(self.default_font.render(str(pygame.mouse.get_pos()), True, (255, 255, 255)), [0, 24]) if self.RECT_DEBUG: ps = pygame.Surface(self.Player.player_dims) ps.fill([255, 0, 0]) self.screen.blit(ps, self.off([self.Player.player_r.x, self.Player.player_r.y])) self.HUD.blitHUD()
from scheduler import Schedule Schedule().every(3).do(lambda i, d: print('Fizz', end='')).every(5).do( lambda i, d: print("Buzz", end='')).every(1).do(lambda i, d: print( i + 1, end='') if ((i + 1) % 3) * ((i + 1) % 5) != 0 else None).every( 1).do(lambda i, d: print()).forNext(100).execute()
def test_addtask(): s = Schedule('maoxu', 'work schedule') s.add_task('test', 'test content', 100) s.add_task('cs106', 'teach cs106', 10) assert 'test' in s.tasks assert 'cs106' in s.tasks
def test_removetask(): s = Schedule('maoxu', 'personal schedule') s.add_task('test', 'test content', 100) s.remove_task('test') assert s.tasks == {}
def __init__(self): """ Main game class initialization. All other class references point to this class as "game" """ # window setup pygame.display.set_caption('Necromonster') pygame.display.set_icon( pygame.image.load(os.path.join('rec', 'misc', 'icon.png'))) self.main_path = os.getcwd() # initiate the clock and screen object self.clock = pygame.time.Clock() self.FPS = 50 self.last_tick = pygame.time.get_ticks() self.screen_res = [900, 650] self.center_point = [470, 350] self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32) #DEBUG values self.DEBUG = 1 self.RECT_DEBUG = 0 self.angle = 0 #Init and assign custom game class(es) self.EntityHandler = EntityHandler(self) self.ParticleManager = ParticleManager(self) self.Scheduler = Schedule(self) self.Entity = Entity self.Projectile = Projectile self.Monster = Monster self.NPC = NPC self.NPCText = NPCText self.Item = Item self.Inventory = Invent self.Invent = self.Inventory(self) self.Weapon = Weapon self.Garment = Garment self.Player = Player(self) self.HUD = HUD(self) # Init entity manager vars self.entities = [] self.shadows = [] # load fonts, create font list # do not use pygame.font.SysFont! self.text_list = [] self.default_font = pygame.font.Font( os.path.join('rec', 'font', 'freesansbold.ttf'), 15) self.speak_font = pygame.font.Font( os.path.join('rec', 'font', 'freesansbold.ttf'), 30) # load the map that player is on self.INSIDE = 0 self.blit_list = mapLoader.load('home', self) # spawn initial map items/entities self.Item(self, 'Mythril', [350, 400], world=1) self.NPC(self, "blacksmith", [400, 400], 100, 'still') for i in xrange(4): self.Monster(self, 'chicken', [200 + (i * 50), 650], 1, 'neutral') self.Monster(self, "goop", [100, 100], 1, 'aggressive') # begin main game loop while 1: self.Loop()
class Necro(): def __init__(self): """ Main game class initialization. All other class references point to this class as "game" """ # window setup pygame.display.set_caption('Necromonster') pygame.display.set_icon( pygame.image.load(os.path.join('rec', 'misc', 'icon.png'))) self.main_path = os.getcwd() # initiate the clock and screen object self.clock = pygame.time.Clock() self.FPS = 50 self.last_tick = pygame.time.get_ticks() self.screen_res = [900, 650] self.center_point = [470, 350] self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32) #DEBUG values self.DEBUG = 1 self.RECT_DEBUG = 0 self.angle = 0 #Init and assign custom game class(es) self.EntityHandler = EntityHandler(self) self.ParticleManager = ParticleManager(self) self.Scheduler = Schedule(self) self.Entity = Entity self.Projectile = Projectile self.Monster = Monster self.NPC = NPC self.NPCText = NPCText self.Item = Item self.Inventory = Invent self.Invent = self.Inventory(self) self.Weapon = Weapon self.Garment = Garment self.Player = Player(self) self.HUD = HUD(self) # Init entity manager vars self.entities = [] self.shadows = [] # load fonts, create font list # do not use pygame.font.SysFont! self.text_list = [] self.default_font = pygame.font.Font( os.path.join('rec', 'font', 'freesansbold.ttf'), 15) self.speak_font = pygame.font.Font( os.path.join('rec', 'font', 'freesansbold.ttf'), 30) # load the map that player is on self.INSIDE = 0 self.blit_list = mapLoader.load('home', self) # spawn initial map items/entities self.Item(self, 'Mythril', [350, 400], world=1) self.NPC(self, "blacksmith", [400, 400], 100, 'still') for i in xrange(4): self.Monster(self, 'chicken', [200 + (i * 50), 650], 1, 'neutral') self.Monster(self, "goop", [100, 100], 1, 'aggressive') # begin main game loop while 1: self.Loop() def Loop(self): """ Main loop of the game. Calls tick, draw, and event processing functions. Tick and draw are only called every 20 milliseconds """ self.eventLoop() self.Tick() self.Draw() pygame.display.update() def eventLoop(self): """ Uses pygame event handling to process keypresses and mouse clicks. Used for chat, interacting with objects, and inventory management """ for event in pygame.event.get(): event # prevents exit button freeze up if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: # toggle chat bar active if not self.HUD.chat_active: if event.key == K_e: self.Invent.toggleView() if event.key == K_t: #activate the chat bar self.HUD.chat_message = '' self.HUD.chat_active = 1 self.Player.can_move = 0 return 0 # process chat messages. Remove or add characters while chat box is open if event.key == K_ESCAPE or event.key == K_RETURN: self.HUD.processCommand(self.HUD.chat_message) self.HUD.chat_active = 0 self.Player.can_move = 1 self.HUD.chat_message = '' elif event.key == K_BACKSPACE: self.HUD.chat_message = self.HUD.chat_message[:-1] elif event.key <= 255: char = chr(event.key) if self.keys_pressed[K_LSHIFT] or self.keys_pressed[ K_RSHIFT]: char = char.upper() self.HUD.chat_message += char # interaction with entities on space bar press if event.key == K_SPACE: for monster in self.EntityHandler.monsters: if monster.NPC: if monster.isPlayerClose( 75) and monster.interacting == False: monster.interacting = True elif not monster.isPlayerClose( 75) or monster.interacting == True: monster.interacting = False self.HUD.delPrompt() # inventory management, checks for item throws, and placement in slots. elif event.type == MOUSEBUTTONDOWN: self.Invent.last_click = pygame.mouse.get_pos() if self.Invent.in_hand: self.Invent.testThrow(self.Invent.last_click) if self.Invent.shown: self.Invent.inventClick(self.Invent.last_click) elif pygame.mouse.get_pressed()[0]: self.Player.attack(pygame.mouse.get_pos()) def Tick(self): """ Updates all game math and entity states. No drawing is done. """ ttime = self.clock.tick(self.FPS) self.keys_pressed = pygame.key.get_pressed() if self.keys_pressed[K_EQUALS]: self.HUD.daytime_start -= 3 if self.keys_pressed[K_MINUS]: self.HUD.daytime_start += 3 self.Scheduler.update() self.EntityHandler.updateAll(ttime) self.Invent.update() self.HUD.updateDay() for index, text in enumerate(self.text_list): if text[2]: raise DeprecationWarning self.last_tick = pygame.time.get_ticks() def off(self, coords): """ Offsets image coordinates to appear correct from the view of the player. Should be called on all surface coordinates before blitting. """ newx = coords[0] - self.Player.player_r.x + 450 newy = coords[1] - self.Player.player_r.y + 325 return [newx, newy] def unoff(self, coords): """ Removes the offset created by the off() function. """ newx = coords[0] + self.Player.player_r.x - 450 newy = coords[1] + self.Player.player_r.y - 325 return [newx, newy] def getCenterBlit(self, surface, pos): pos[0] = pos[0] + surface.get_width() / 2 pos[1] = pos[1] + surface.get_height() / 2 return pos def rotopoint(self, surface, angle, pos): size = surface.get_size() if pos[0] > size[0] / 2 or pos[1] > size[1] / 2: print 'BIG ASS HONKEY' new_surf_size = [(size[0] - pos[0]) * 2, (size[1] - pos[1]) * 2] new_surf_blit_pos = [ new_surf_size[0] - size[0], new_surf_size[1] - size[1] ] new_surf = pygame.Surface(new_surf_size, pygame.SRCALPHA, 32) new_surf.blit(surface, new_surf_blit_pos) return pygame.transform.rotate(new_surf, angle) def testrot(self, image, angle): loc = image.get_rect().center new_rot = pygame.transform.rotate(image, angle) new_rot.get_rect(center=loc) return new_rot, new_rot.get_rect() def Draw(self): """ Completes all blitting to the screend object, includes HUD updates. """ tile_width = self.tile[1][0] tile_height = self.tile[1][1] tile_extrax = self.Player.player_r.x % tile_width tile_extray = self.Player.player_r.y % tile_height y = 0 for i in xrange(self.screen_res[1] / tile_height + 3): for i in xrange(self.screen_res[0] / tile_width + 3): self.screen.blit(self.tile[0], [ i * tile_width - tile_width - tile_extrax, y - tile_height - tile_extray ]) y += self.tile[1][1] if self.shadows: for s in self.shadows: s.update(self.screen) for surf in self.blit_list: if 'player' in surf: self.EntityHandler.blitAll() else: self.screen.blit(surf[0], self.off(surf[1])) for text in self.text_list: self.screen.blit(text[0], text[1]) if self.Invent.shown: self.Invent.draw() if self.DEBUG: self.screen.blit( self.default_font.render(str(round(self.clock.get_fps())), True, (255, 255, 255)), [0, 0]) self.screen.blit( self.default_font.render( str('%s, %s' % (self.Player.player_r.x, self.Player.player_r.y)), True, (255, 255, 255)), [0, 12]) self.screen.blit( self.default_font.render(str(pygame.mouse.get_pos()), True, (255, 255, 255)), [0, 24]) if self.RECT_DEBUG: ps = pygame.Surface(self.Player.player_dims) ps.fill([255, 0, 0]) self.screen.blit( ps, self.off([self.Player.player_r.x, self.Player.player_r.y])) #Draws player and head text if it exists if self.Player.head_drawn: if self.Player.head_drawn[3]: self.screen.blit(self.Player.head_drawn[0], self.Player.head_drawn[1]) else: self.Player.game.screen.blit( self.Player.head_drawn[0], self.off(self.Player.head_drawn[1])) self.ParticleManager.update() if self.Player.map_change: self.HUD.updateMapTrans() self.HUD.blitHUD()
print(f"Learning rate: {scope['learning_rate']}") def save(step, scope): print("Export...") def update_g(step, scope): print("Update G") def update_d(step, scope): print("Update D") def plot_training(step, scope): print("Plot") batch = Schedule().first().do(batch_info) batch.forNext(5).every(1).do(update_g) batch.then().do(update_d) training = Schedule() training.every(1).do(lambda step, scope: batch.withScope( learning_rate=scope.get("learning_rate", 5 / (step + 5)))) training.every(10).do(save) training.every(10).do(plot_training) training.forNext(20) training.then().do(training.withScope(learning_rate=0.1).forNext(20)) training.execute()
def main(): s = Schedule() s.go()
def main(): s = Schedule() s.run() app.run()
from scheduler import Schedule line = (Schedule(length=10).every(1).do(lambda step, scope: print( ".", end="")).whileTrue(lambda step, scope: step < scope["length"])) line.then().do(lambda step, scope: print()) line.withScope(length=10).execute() triangle = Schedule().every(1).do( lambda step, scope: line.withScope(length=step)) triangle.first().do(line) triangle.forNext(20).execute() triangle.then().do(line) Schedule(h=10).every(1).do(line).until( lambda step, scope: step == scope["h"]).execute()
def __init__(self): """ Main game class initialization. All other class references point to this class as "game" """ # window setup pygame.display.set_caption('Necromonster') pygame.display.set_icon(pygame.image.load(os.path.join('rec', 'misc', 'icon.png'))) self.main_path = os.getcwd() # initiate the clock and screen object self.clock = pygame.time.Clock() self.FPS = 50 self.last_tick = pygame.time.get_ticks() self.screen_res = [900, 650] self.center_point = [470, 350] self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32) #DEBUG values self.DEBUG = 1 self.RECT_DEBUG = 0 self.angle = 0 #Init and assign custom game class(es) self.EntityHandler = EntityHandler(self) self.ParticleManager = ParticleManager(self) self.Scheduler = Schedule(self) self.Entity = Entity self.Projectile = Projectile self.Monster = Monster self.NPC = NPC self.NPCText = NPCText self.Item = Item self.Inventory = Invent self.Invent = self.Inventory(self) self.Weapon = Weapon self.Garment = Garment self.Player = Player(self) self.HUD = HUD(self) # Init entity manager vars self.entities = [] self.shadows = [] # load fonts, create font list # do not use pygame.font.SysFont! self.text_list = [] self.default_font = pygame.font.Font(os.path.join('rec', 'font', 'freesansbold.ttf'), 15) self.speak_font = pygame.font.Font(os.path.join('rec', 'font', 'freesansbold.ttf'), 30) # load the map that player is on self.INSIDE = 0 self.blit_list = mapLoader.load('home', self) # spawn initial map items/entities self.Item(self, 'Mythril', [350, 400], world=1) self.NPC(self, "blacksmith", [400, 400], 100, 'still') for i in xrange(4): self.Monster(self, 'chicken', [200+(i*50),650], 1, 'neutral') self.Monster(self, "goop", [100, 100], 1, 'aggressive') # begin main game loop while 1: self.Loop()