def __init__(self, engine, pos): super().__init__(load_image('images/plane.gif'), pos) self.image_straight = self.image self.image_left = load_image('images/plane_turning_right_1.gif') self.image_right = load_image('images/plane_turning_left_1.gif') self.engine = engine self.speed = [0, 0] # [x, y] self.health = 3 self.score = 0 self.missiles = pygame.sprite.Group() self.explosions = pygame.sprite.Group() self.font = pygame.font.Font(None, 36) self.cooldown = Cooldown(150) self.explosion_sound = pygame.mixer.Sound('sound/explosion.wav') self.key = { K_RIGHT: False, K_LEFT: False, K_UP: False, K_DOWN: False, K_SPACE: False }
def __init__(self, pos): super().__init__() self.image = load_image('images/explosion_anim.jpg') self.rect = self.image.get_rect() self.rect.center = pos self.crop = (64, 64) self.dim = 4 self.cooldown = Cooldown(220) self.back = False
def __init__(self, engine, pos): super().__init__(load_image('images/plane.gif'), pos) self.image_straight = self.image self.image_left = load_image('images/plane_turning_right_1.gif') self.image_right = load_image('images/plane_turning_left_1.gif') self.engine = engine self.speed = [0, 0] # [x, y] self.score = 0 self.font = pygame.font.Font(None, 36) self.health = 3 #### self.cd = Cooldown(100)
class Explosion(pygame.sprite.Sprite): def __init__(self, pos): super().__init__() self.image = load_image('images/explosion_anim.jpg') self.rect = self.image.get_rect() self.rect.center = pos self.crop = (64, 64) self.dim = 4 self.cooldown = Cooldown(220) self.back = False def update(self, engine, delta): self.cooldown.update(delta) if self.cooldown.reset_if_ready(): if self.back: self.kill() else: self.back = True def draw(self, surface): target = pygame.rect.Rect((0, 0), self.crop) target.center = self.rect.center surface.blit(self.image, target, area=self.get_crop()) def get_crop(self): progress = self.cooldown.progress frame_count = self.dim**2 index = int(progress * frame_count) % frame_count if self.back: index = frame_count - index - 1 dim = self.dim - 1 x = dim - (index % self.dim) y = dim - (index // self.dim) cx = x * self.crop[0] cy = y * self.crop[1] return pygame.rect.Rect((cx, cy), self.crop)
class Player(GameObject): def __init__(self, engine, pos): super().__init__(load_image('images/plane.gif'), pos) self.image_straight = self.image self.image_left = load_image('images/plane_turning_right_1.gif') self.image_right = load_image('images/plane_turning_left_1.gif') self.engine = engine self.speed = [0, 0] # [x, y] self.score = 0 self.font = pygame.font.Font(None, 36) self.health = 3 #### self.cd = Cooldown(100) def handle_keys(self, event): speed_value = 500 arrows = (K_RIGHT, K_LEFT, K_UP, K_DOWN) if event.type == KEYDOWN: if event.key == K_SPACE and self.cd.ready: missile = Missile(self, self.rect.center) engine.missiles.add(missile) self.cd.reset() if event.type == KEYDOWN: if event.key == K_RIGHT: self.speed[0] = speed_value self.image = self.image_right elif event.key == K_LEFT: self.speed[0] = -speed_value self.image = self.image_left elif event.key == K_UP: self.speed[1] = -speed_value elif event.key == K_DOWN: self.speed[1] = speed_value elif event.type == KEYUP: if event.key in arrows: self.speed = [0, 0] self.image = self.image_straight def update(self, engine, delta): self.cd.update(delta) x, y = self.speed rect = self.rect self.rect = self.rect.move(x * delta, y * delta) if (self.rect.left <= 0 or self.rect.right >= engine.screen.get_width() or self.rect.top <= 0 or self.rect.bottom >= engine.screen.get_height()): self.rect = rect def draw(self, surface): super().draw(surface) self.draw_status(surface) def draw_status(self, screen): if pygame.font: # draw score score = self.font.render('Score: {}'.format(self.score), 1, (255, 0, 0)) scorepos = score.get_rect(centerx=screen.get_width() / 2) screen.blit(score, scorepos) """ draw health of the player """ health = self.font.render('Health: {}'.format(self.health), 1, (0, 255, 0)) healthpos = health.get_rect(centerx=screen.get_width() / 2, centery=35) screen.blit(health, healthpos)
from phonetic_alphabet.main import NonSupportedTextException from py_expression_eval import Parser from pyryver import Ryver from pyryver.util import retry_until_available from utils import Cooldown, TopicGenerator, bot_dir, console, send_message __version__ = "1.1.0" load_dotenv(dotenv_path=bot_dir / ".env") # Added path to support older versions of python-dotenv config = ConfigParser() config.read("brainbot.ini") tell_me_to_cooldown = Cooldown( config.getint("cooldowns", "tell_me_to", fallback=200)) topic_cooldown = Cooldown(config.getint("cooldowns", "topic", fallback=100)) math_parser = Parser() topic_engine = TopicGenerator() translator = Translator() # Wrap in async function to use async context manager async def main(): # Log into Ryver with regular username/password async with Ryver(getenv("RYVER_ORG"), getenv("RYVER_USER"), getenv("RYVER_PASS")) as ryver: console.log( f"Connected to {ryver.org} Ryver org as user {getenv('RYVER_USER')}" )
from os import getenv, system from sys import executable from dotenv import load_dotenv from py_expression_eval import Parser from pyryver import Ryver from pyryver.util import retry_until_available from utils import Cooldown, TopicGenerator, bot_dir, console, send_message __version__ = "0.4.0" load_dotenv(dotenv_path=bot_dir / ".env") # Added path to support older versions of python-dotenv tell_me_to_cooldown = Cooldown(300) topic_cooldown = Cooldown(120) topic_engine = TopicGenerator() math_parser = Parser() # Wrap in async function to use async context manager async def main(): # Log into Ryver with regular username/password async with Ryver(getenv("RYVER_ORG"), getenv("RYVER_USER"), getenv("RYVER_PASS")) as ryver: console.log( f"Connected to {ryver.org} Ryver org as user {getenv('RYVER_USER')}" )
def loader(ctrl, queue): """ Load an URL and push back links to the queue """ stats = dict( sleep=0, redirect=0, run=0, download=0, write=0, error=0, timeout=0, connerr=0 ) cooldown = Cooldown() def load(path, url): if cooldown.wait(): stats['sleep'] += 1 notify("DOWNLD", url) retry = False try: r = requests.get( url, headers = { 'user-agent': REQUESTS_USER_AGENT, }, timeout=REQUESTS_TIMEOUT ) stats['download'] += 1 if r.status_code != 200: notify("STATUS", r.status_code) retry = True if r.status_code == 429 or r.status_code >= 500: # Too many requests or server error cooldown.set() else: cooldown.clear() except requests.Timeout: notify("TIMEOUT", url) retry = True cooldown.set() stats['timeout'] += 1 except requests.exceptions.ConnectionError: # Connection refused? notify("CONNERR", url) retry = True cooldown.set() stats['connerr'] += 1 if retry: # Retry later notify("RETRY", url) ctrl.put((RETRY, path, url)) else: notify("PARSE", path) ctrl.put((PARSE,path,r.text)) notify("DONE") ctrl.put((DONE,path)) def _run(): path,url = queue.get() load(path, url) return worker(_run, "loader", stats)
bot_dir, console, handle_notification, remind_task, send_message, ) __version__ = "1.4.1" load_dotenv(dotenv_path=bot_dir / ".env") # Added path to support older versions of python-dotenv config = ConfigParser() config.read("brainbot.ini") tell_me_to_cooldown = Cooldown( config.getint("cooldowns", "tell_me_to", fallback=200)) topic_cooldown = Cooldown(config.getint("cooldowns", "topic", fallback=100)) repeat_cooldown = Cooldown(config.getint("cooldowns", "repeat", fallback=45)) phon_cooldown = Cooldown(config.getint("cooldowns", "phon", fallback=45)) poll_cooldown = Cooldown(config.getint("cooldowns", "poll", fallback=100)) # Load poll reactions poll_reactions = config.get( "misc", "poll_reactions", fallback="zero;one;two;three;four;five;six;seven;eight;nine;keycap_ten", ).split(";") math_parser = Parser() topic_engine = TopicGenerator() translator = Translator()
def cdx(ctrl, queue, sem, url): """ Query the CDX index to retrieve all captures for the `url` prefix """ stats = { 'run': 0, 'error': 0, 'push': 0, 'timeout': 0, 'connerr': 0, } cooldown = Cooldown() params = dict(url=url, matchType='prefix', limit=CDX_LIMIT, showResumeKey='true', resumeKey=None) fields = ('timestamp', 'original', 'statuscode') params['fl'] = ",".join(fields) def _next(): resumeKey = queue.get() cooldown.wait() try: params['resumeKey'] = resumeKey r = requests.get(CDX_API_ENDPOINT, timeout=REQUESTS_TIMEOUT, headers={ 'user-agent': REQUESTS_USER_AGENT, }, stream=True, params=params) notify("CDX", r.status_code) if r.status_code != 200: cooldown.set() return False resumeKey = None count = 0 items = [] for line in r.iter_lines(): count += 1 if not line: # ignore empty lines continue line = line.decode('utf-8') item = line.split() if len(item) == 1: # TEST ONLY # break # END TEST ONLY # resume key resumeKey = urllib.parse.unquote_plus(item[0]) notify('DEBUG', resumeKey) break # else item = {k: v for k, v in zip(fields, item)} if item.get("statuscode") == "200": items.append(item) finally: ctrl.put((CDX, resumeKey)) for item in items: # notify("PUSH", item['timestamp'], item['original']) stats['push'] += 1 sem.acquire() ctrl.put((CHECK, *capturetopath(item))) cooldown.clear() notify('DEBUG', count) return count == 0 def _run(): try: return _next() except requests.Timeout: notify("TIMEOUT", params['resumeKey']) stats['timeout'] += 1 cooldown.set(1) except requests.exceptions.ConnectionError: notify("CONNERR", params['resumeKey']) stats['connerr'] += 1 cooldown.set(1) except BrokenPipeError: return True finally: ctrl.put((UNLOCK, )) return worker(_run, "cdx", stats)
def __init__(self, pos): super().__init__(load_image('images/explosion_anim.jpg'), pos) self.crop = (64, 64) self.dim = 4 self.cooldown = Cooldown(220) self.back = False
class Player(GameObject): def __init__(self, engine, pos): super().__init__(load_image('images/plane.gif'), pos) self.image_straight = self.image self.image_left = load_image('images/plane_turning_right_1.gif') self.image_right = load_image('images/plane_turning_left_1.gif') self.engine = engine self.speed = [0, 0] # [x, y] self.health = 3 self.score = 0 self.missiles = pygame.sprite.Group() self.explosions = pygame.sprite.Group() self.font = pygame.font.Font(None, 36) self.cooldown = Cooldown(150) self.explosion_sound = pygame.mixer.Sound('sound/explosion.wav') self.key = { K_RIGHT: False, K_LEFT: False, K_UP: False, K_DOWN: False, K_SPACE: False } def handle_keys(self, event): if event.type not in (KEYDOWN, KEYUP): return speed_value = 500 if event.key in self.key: self.key[event.key] = event.type == KEYDOWN image = self.image speed = [0, 0] if self.key[K_RIGHT]: speed[0] = speed_value image = self.image_right if self.key[K_LEFT]: speed[0] = -speed_value image = self.image_left if self.key[K_UP]: speed[1] = -speed_value if self.key[K_DOWN]: speed[1] = speed_value if not self.key[K_RIGHT] and not self.key[K_LEFT]: image = self.image_straight self.speed = speed self.image = image def update(self, engine, delta): x, y = self.speed self.move(x * delta, y * delta) width, height = engine.screen.get_width(), engine.screen.get_height() if self.rect.left < 0: self.move(abs(self.rect.left), 0) if self.rect.right >= width: self.move(width - self.rect.right, 0) if self.rect.top < 0: self.move(0, -self.rect.top) if self.rect.bottom >= height: self.move(0, height - self.rect.bottom) self.cooldown.update(delta) if self.key[K_SPACE] and self.cooldown.reset_if_ready(): self.spawn_missile() self.missiles.update(engine, delta) self.explosions.update(engine, delta) def draw(self, surface): for missile in self.missiles: missile.draw(surface) for explosion in self.explosions: explosion.draw(surface) surface.blit(self.image, self.rect) self.draw_status(surface) def draw_status(self, screen): if pygame.font: # draw score text = self.font.render('Score: {}'.format(self.score), 1, (255, 0, 0)) textpos = text.get_rect(centerx=screen.get_width() / 2) screen.blit(text, textpos) # draw health text = self.font.render('Health: {}'.format(self.health), 1, (0, 255, 0)) textpos = text.get_rect(centerx=screen.get_width() / 2, centery=40) screen.blit(text, textpos) def lose_health(self): self.health -= 1 if self.health <= 0: self.engine.end() def on_enemy_destroyed(self, enemy): self.score += enemy.score self.explosions.add(Explosion(enemy.rect.center)) self.explosion_sound.play() def spawn_missile(self): missile = Missile(self, self.rect.center) self.missiles.add(missile)
# colors # https://www.pygame.org/docs/ref/color.html c = pygame.Color(255, 0, 0) # Create a color (R, G, B), each in interval [0, 255] engine.screen # window screen engine.screen.get_width() # window width engine.screen.get_height() # window height # delta clock = pygame.time.Clock() # create a delta clock delta = clock.tick(60) / 1000 # calculate delta in each update frame rect = rect.move(500 * delta, 0) # move rectangle in X axis by 500 * delta # cooldown cd = Cooldown(500) # 500 ms cooldown cd.update(delta) # update cooldown in every frame if cd.reset_if_ready(): # returns True if CD is ready and resets it if its ready pass # react to some key event for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() else: if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: pass # collisions # return all sprites from collection `items` that collide with `player`