示例#1
0
文件: pong.py 项目: willkang7/pong_2
    def __init__(self):
        """Initialize the game, and create game resources."""
        self.screen = turtle.Screen()
        self.screen.title("Pong")
        self.screen.bgcolor("black")
        self.screen.setup(width=800, height=600)
        self.screen.tracer(0)

        # Game assets
        self.sb = Scoreboard()
        self.announcer = Announcer()
        self.paddle_a = Paddle(-350, 0)
        self.paddle_b = Paddle(350, 0)
        self.ball = Ball()
        self.game_active = True

        # Keyboard bindings
        self.screen.listen()
        self.screen.onkeypress(self.paddle_a.start_move_up, 'w')
        self.screen.onkeypress(self.paddle_a.start_move_down, 's')
        self.screen.onkeyrelease(self.paddle_a.stop_move_up, 'w')
        self.screen.onkeyrelease(self.paddle_a.stop_move_down, 's')
        self.screen.onkeypress(self.paddle_a.start_long, 'r')
        self.screen.onkeypress(self.paddle_a.prime_fastball, 't')
        self.screen.onkeypress(self.paddle_b.start_move_up, 'Up')
        self.screen.onkeypress(self.paddle_b.start_move_down, 'Down')
        self.screen.onkeyrelease(self.paddle_b.stop_move_up, 'Up')
        self.screen.onkeyrelease(self.paddle_b.stop_move_down, 'Down')
        self.screen.onkeypress(self.paddle_b.start_long, ',')
        self.screen.onkeypress(self.paddle_b.prime_fastball, '.')
示例#2
0
    def __init__(self, sender):
        Announcer.__init__(self, sender)
        self.logger = logging.getLogger("dudo.statemachine")
        self.logger.setLevel(logging.DEBUG)
        self.handler = logging.StreamHandler(sys.stdout)
        self.handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.handler.setFormatter(formatter)
        self.logger.addHandler(self.handler)

        self.angery_level = 0

        self.loop = asyncio.get_event_loop()
        self.timeout_task = None
        self.timeout_lock = asyncio.Lock()

        self.answers = dict()
        self.players = list()
        self.player_names = dict()

        self.previous_guesser = None
        self.current_state = None
        self.current_question = None

        self.questioners = list()
        self.guessers = list()

        self.current_bet = 0

        self.final_guess = None
        self.final_player = None

        self.game_owner = None
        self.timer = None
        self.dead = False
示例#3
0
    def __init__(self,
                 mqtt_server_ip,
                 mqtt_server_port,
                 mqtt_user=None,
                 mqtt_pass=None,
                 mqtt_base_topic="megaphone",
                 mp3_filename="output.mp3",
                 ext_amp_conf: ExternalAmplifierConfig = None):
        self.mqtt_server_ip = mqtt_server_ip
        self.mqtt_server_port = mqtt_server_port
        self.mqtt_user = mqtt_user
        self.mqtt_pass = mqtt_pass
        self.mqtt_base_topic = mqtt_base_topic
        self.client: mqtt.Client = mqtt.Client()
        self.mp3_filename = mp3_filename
        self.ext_amp_conf: ExternalAmplifierConfig = ext_amp_conf

        signal.signal(signal.SIGINT, self.signal_handler)
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect
        if (self.mqtt_user is not None) and (self.mqtt_pass is not None):
            self.client.username_pw_set(self.mqtt_user,
                                        password=self.mqtt_pass)
        self.client.will_set(f"{self.mqtt_base_topic}/state",
                             payload="offline",
                             retain=True)
        self.announcer = Announcer()
        self.announcer.on_status_change = self.status_change
示例#4
0
def main():
    # Setup
    pb = Pushbullet(os.getenv('PUSHBULLET_API_KEY'))
    logging.info('Connected to Pushbullet successfully.')

    def on_new(items, old):
        for title, city, prov, link, price, when, ships in items:
            message_body = (f'{title} at {price}€ in {city} {prov}.',
                            'Shipment available.' if ships else '',
                            f'Published {when}.', link)
            pb.push_note('Found new item',
                         '\n'.join([s for s in message_body if s]))
            logging.info('Pushed notification!')
            try:
                with open(OLD_FILE, 'w') as f:
                    f.write(repr(old))
            except IOError as err:
                logging.error(err)

    try:
        with open(OLD_FILE, 'r') as f:
            items = ast.literal_eval(f.read())
        logging.info('Old file loaded succesfully.')
    except IOError as err:
        logging.warning(err)
        logging.info('Couldn\'t load old file, fetching current ads...')
        html = get_all_ads_page()
        items = parse_ads(html)
        logging.info('Done.')

    announcer = Announcer(
        on_new=on_new,
        initial=items[:],
    )

    def job():
        logging.debug('Running main job.')
        try:
            logging.debug('Fetching ads...')
            html = get_all_ads_page()
            logging.debug('Fetched ads successfully.')
            items = parse_ads(html)
            announcer.submit(items)
        except ConnectionError:
            logging.warning('Couldn\' fetch ads.')
        except Exception as err:
            logging.error(err)

    # Configure scheduler
    logging.debug('Configuring scheduler')
    schedule.every().minute.do(job)
    logging.info('Entering main loop')
    logging.info(f'Looking for {SEARCH}')
    # Loop
    while (True):
        schedule.run_pending()
        time.sleep(1)
示例#5
0
def destalinate_job():
    print("Destalinating")
    if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
        print "ERR: Missing at least one Slack environment variable."
    else:
        warner = Warner()
        archiver = Archiver()
        announcer = Announcer()
        flagger = Flagger()
        print("Warning")
        warner.warn()
        print("Archiving")
        archiver.archive()
        print("Announcing")
        announcer.announce()
        print("Flagging")
        flagger.flag()
        print("OK: destalinated")
    print("END: destalinate_job")
示例#6
0
class App:

  """The main App class holds the references to the Sensor_handler and Announcer
  objects as well as all the scores.
  """

  def __init__(self):
    self.GPIO_handler = GPIO_handler()
    self.announcer    = Announcer()
    self.scores       = [0, 0]
    self.paused       = False

  def start(self):
    while not self.paused:
      # Wait for a goal to be scored.
      if self.GPIO_handler.check_for_goals(self):

        # Check if a team has won.
        if max(self.scores) >= 10:
          self.announcer.declare_winner(self)
          self.reset_scores(False)
        else:
          self.announcer.announce_goal(self)
          # wait a second.
          time.sleep(1)

  def reset_scores(self, announce):
    self.scores = [0, 0]
    if announce:
      self.announcer.announce_reset()
    time.sleep(1)
示例#7
0
def main():
    parser = argparse.ArgumentParser(
        "Parse stdin, and make annnouncements based on that.")
    parser.add_argument('file1', metavar="Audio_file_for_without_mask")
    parser.add_argument('file2',
                        metavar="Audio_file_for_mask_worn_incorrectly")
    parser.add_argument(
        '--detect-interval',
        default=2.0,
        type=float,
        help='In seconds. For which the detector counts the result.')
    parser.add_argument(
        '--detect-threshold',
        default=0.0,
        type=float,
        help=
        'In [0, 1]. If the ratio is above this value, announcement will be made'
    )
    parser.add_argument(
        '--announce-interval',
        default=5.0,
        type=float,
        help=
        'In seconds. The announcer refrain from announce after announcing for this period of time'
    )
    args = parser.parse_args()
    d = Detector(time_interval=args.detect_interval,
                 check_threshold=args.detect_threshold,
                 announcers={
                     WITHOUT_MASK:
                     Announcer(args.file1,
                               time_interval=args.announce_interval),
                     MASK_WORN_INCORRECTLY:
                     Announcer(args.file2,
                               time_interval=args.announce_interval)
                 })
    d.watch()
示例#8
0
def do(screen, songdata):

    onoff_opt = {
        ui.START: switch_onoff,
        ui.CONFIRM: switch_onoff,
        menus.CREATE: get_onoff,
        ui.LEFT: off_onoff,
        ui.RIGHT: on_onoff
    }
    offon_opt = {
        ui.START: switch_offon,
        ui.START: switch_offon,
        menus.CREATE: get_offon,
        ui.LEFT: off_offon,
        ui.RIGHT: on_offon
    }
    rotate_opt = {
        ui.START: switch_rotate,
        ui.CONFIRM: switch_rotate,
        ui.LEFT: switch_rotate_back,
        ui.RIGHT: switch_rotate,
        menus.CREATE: get_rotate
    }
    rotate_index_opt = {
        ui.START: switch_rotate_index,
        ui.CONFIRM: switch_rotate_index,
        ui.LEFT: switch_rotate_index_back,
        ui.RIGHT: switch_rotate_index,
        menus.CREATE: get_rotate_index
    }
    tuple_opt = {
        ui.START: switch_tuple,
        ui.CONFIRM: switch_tuple,
        ui.LEFT: switch_tuple_back,
        ui.RIGHT: switch_tuple,
        menus.CREATE: get_tuple
    }

    sprites = pygame.sprite.RenderUpdates()
    try:
        lines = file(os.path.join(pydance_path, "CREDITS")).read().split("\n")
        lines = [l.decode("utf-8") for l in lines]
        Credits([_("pydance %s") % VERSION] + lines).add(sprites)
    except:
        Credits([
            _("pydance %s") % VERSION,
            "http://icculus.org/pyddr",
            _("By Joe Wreschnig, Brendan Becker, & Pavel Krivitsky"),
            _("(Your CREDITS file is missing.)"),
        ]).add(sprites)

    m = ([
        _("Play Game"), {
            ui.START: wrap_ctr,
            ui.CONFIRM: wrap_ctr
        }, (GameSelect, songdata)
    ], [
        _("Map Keys"), {
            ui.START: wrap_ctr,
            ui.CONFIRM: wrap_ctr
        }, (pad.PadConfig, (screen, ))
    ], (_("Game Options"), [_("Autofail"), onoff_opt, (_("autofail"), )], [
        _("Assist Mode"), tuple_opt,
        (_("assist"), [(0, _("Off")), (1, _("Click")), (2, _("Full"))])
    ], [_("Announcer"), rotate_opt,
        ('djtheme', Announcer.themes())], (_("Themes ..."), [
            _("4 Panel"), rotate_opt,
            ("4p-theme", ThemeFile.list_themes("SINGLE"))
        ], [
            _("3 Panel"), rotate_opt,
            ("3p-theme", ThemeFile.list_themes("3PANEL"))
        ], [
            _("5 Panel"), rotate_opt,
            ("5p-theme", ThemeFile.list_themes("5PANEL"))
        ], [
            _("Large 6 Panel"), rotate_opt,
            ("6pl-theme", ThemeFile.list_themes("6PANEL"))
        ], [
            _("Small 6 Panel"), rotate_opt,
            ("6ps-theme", ThemeFile.list_themes("6VERSUS"))
        ], [
            _("Large 8 Panel"), rotate_opt,
            ("8pl-theme", ThemeFile.list_themes("8PANEL"))
        ], [
            _("Small 8 Panel"), rotate_opt,
            ("8ps-theme", ThemeFile.list_themes("8VERSUS"))
        ], [
            _("Large 9 Panel"), rotate_opt,
            ("9pl-theme", ThemeFile.list_themes("9PANEL"))
        ], [
            _("Small 9 Panel"), rotate_opt,
            ("9ps-theme", ThemeFile.list_themes("9VERSUS"))
        ], [
            _("Parapara"), rotate_opt,
            ("para-theme", ThemeFile.list_themes("PARAPARA"))
        ], [_("DMX"), rotate_opt,
            ("dmx-theme", ThemeFile.list_themes("DMX"))], [
                _("EZ2"), rotate_opt,
                ("ez2-theme", ThemeFile.list_themes("EZ2SINGLE"))
            ], [
                _("EZ2 Real"), rotate_opt,
                ("ez2real-theme", ThemeFile.list_themes("EZ2REAL"))
            ], [_("Back"), None, None]), [_("Back"), None, None]),
         (_("Graphic Options"), [_("Animation"), onoff_opt, ('animation', )], [
             _("Arrow Effects"), rotate_index_opt,
             ('explodestyle', (_('none'), _('rotate'), _('scale'),
                               _('rotate & scale')))
         ], [_("Backgrounds"), onoff_opt, ('showbackground', )], [
             _("Brightness"), tuple_opt,
             ('bgbrightness', [(32, _('very dark')), (64, _('dark')),
                               (127, _('normal')), (192, _('bright')),
                               (255, _('very bright'))])
         ], [_("Lyrics"), onoff_opt, ("showlyrics", )], [
             _("Lyrics Color"), rotate_opt,
             ("lyriccolor", [
                 _("pink/purple"),
                 _("purple/cyan"),
                 _("cyan/aqua"),
                 _("aqua/yellow"),
                 _("yellow/pink")
             ])
         ], [_("Back"), None, None]),
         (_("Interface Options"),
          [_("Save Input"), onoff_opt, ('saveinput', )], [
              _("Song Previews"),
              tuple_opt, ('previewmusic', [(0, "Off"), (1, "On"), (2, "Safe")])
          ], [_("Folders"), onoff_opt, ("folders", )],
          [_("Timer Display"), onoff_opt, ('fpsdisplay', )], [
              _("Song Info Screen"), tuple_opt,
              ('songinfoscreen',
               zip([0, 1, 2],
                   [_("Never"), _("Multi-song Only"),
                    _("Always")]))
          ], [
              _("Font (after restart)"), rotate_opt,
              ('fonttheme', FontTheme.themes())
          ], [
              _("Calibrate Latency"), {
                  ui.START: wrap_ctr,
                  ui.CONFIRM: wrap_ctr
              }, (calibrate.run, (screen, ))
          ], [_("Back"), None, None]))

    me = menus.Menu(_(""), m, screen, sprites)
    me.display()
            round(hourly_measurements[plant_id].water / measurement_count))
        average_temp = hourly_measurements[
            plant_id].temperature / measurement_count
        average_humidity = int(
            round(hourly_measurements[plant_id].humidity / measurement_count))
        average_light = int(
            round(hourly_measurements[plant_id].light / measurement_count))
        average_moisture = int(
            round(hourly_measurements[plant_id].moisture / measurement_count))
        global logic_layer
        light_on, water_time = logic_layer.commit_measurement(
            plant_id, average_water, average_temp, average_humidity,
            average_light, average_moisture)
        actuator_response = {'light_on': light_on, 'water_time': water_time}
        hourly_measurements[plant_id] = Measurement()
    return jsonify(actuator_response)


@app.route('/configure', methods=['POST'])
def configure():
    mac_address = request.values['mac_address']
    plant_id = logic_layer.configure(mac_address)
    response = {'plant_id': plant_id}
    return jsonify(response)


announcer_thread = Announcer()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
示例#10
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import config
from announcer import Announcer

inputs = "Pociąg osobowy do Grodziska Wielkopolskiego odjedzie z toru pierwszego przy peronie drugim"

inp2 = "Uzbrajanie systemu"


def status_change(message):
    print(message)


pa = Announcer(mp3_filename=config.mp3_filename,
               ext_amp_conf=config.ext_amplifier)
pa.on_status_change = status_change
pa.say(inp2, play_chime="gong")
示例#11
0
	def __init__(self):
		self.warrior1 = Warrior()
		self.warrior2 = Warrior()
		self.odds1, self.odds2 = self._genOdds(self.warrior1,self.warrior2)
		self.announcer = Announcer()
示例#12
0
class Battle:
	def __init__(self):
		self.warrior1 = Warrior()
		self.warrior2 = Warrior()
		self.odds1, self.odds2 = self._genOdds(self.warrior1,self.warrior2)
		self.announcer = Announcer()

	def _genOdds(self,warrior1,warrior2):
		"""This helper function will determine the odds of each warrior winning based
		on the stats and equipment value of each warrior."""
		war1val = warrior1.getStats() + warrior1.getDamStat() + warrior1.getDefValue()
		war2val = warrior2.getStats() + warrior2.getDamStat() + warrior2.getDefValue()
		totodds = war1val + war2val
		return int((float(war1val)/totodds)*10), 10 - int((float(war2val)/totodds)*10)

	def getOdds(self, warrior):
		if warrior == self.warrior1:
			return self.odds1

		else:
			return self.odds2

	def battle(self):
		"""This method sets up the battle then calls the turn method to determine
		the outcome of each round and then update the warriors."""
		while self.warrior1.getHP() > 0 and self.warrior2.getHP() > 0:
			self.fightRound(self.warrior1,self.warrior2)

			if self.warrior1.getHP() <= 0:
				return self.warrior2.getName(), self.odds2
			elif self.warrior2.getHP() <= 0:
				return self.warrior2.getName(), self.odds1

	def fightRound(self,warrior1,warrior2):
		"""This method will simulate one round of combat by checking which warrior
		has higher dexterity, then seeing who got damaged how much."""
		if warrior1.getDex() > warrior2.getDex():
			self._simHit(warrior1,warrior2)
			if warrior2.getHP() <= 0:
				print
				print self.announcer.getDead(warrior2)
				return warrior1.getName(),self.odds1
				raw_input("\nPush <Enter> to continue.")
			else:
				self._simHit(warrior2,warrior1)
				if warrior1.getHP() <= 0:
					print
					print self.announcer.getDead(warrior1)
					return warrior2.getName(),self.odds2
					raw_input("\nPush <Enter> to continue.")

		else:
			self._simHit(warrior2,warrior1)
			if warrior1.getHP() <= 0:
				print
				print self.announcer.getDead(warrior1)
				return warrior2.getName(),self.odds2
				raw_input("\nPush <Enter> to continue.")
			else:
				self._simHit(warrior1,warrior2)
				if warrior2.getHP() <= 0:
					print
					print self.announcer.getDead(warrior2)
					return warrior1.getName(), self.odds1
					raw_input("\nPush <Enter> to continue.")


	def _simHit(self,warrior1,warrior2):
		"""Helper function to determine who hits first and how much damage they do.
		Critical hits and dodges occur when a 20 is rolled."""
		aroll, droll = randrange(1,21) + (warrior1.getDex() * .5), randrange(1,21) + (warrior2.getDex() * .5)

		if aroll >= 20 or droll >= 20:
			if aroll >= 20 and droll != 20:
				if warrior1.getDex() > warrior1.getStr():
					try:
						warrior2.updateHP(warrior1.getDamStat() * randrange(2,(int(warrior1.getDex()*.4))))
					except ValueError:
						warrior2.updateHP(warrior1.getDamStat()*2)
					print
					print self.announcer.getCriticalHit(warrior1,warrior2)
					raw_input("\nPush <Enter> to continue.")
				else:
					try:
						warrior2.updateHP(warrior1.getDamStat() * randrange(2,(int(warrior1.getDex()*.4))))
					except ValueError:
						warrior2.updateHP(warrior1.getDamStat()*2)
						print
						print self.announcer.getCriticalHit(warrior1,warrior2)
						raw_input("\nPush <Enter> to continue.")
			elif droll >= 20 and aroll != 20:
				warrior2.updateHP(0)
				print
				print self.announcer.getCriticalDodge(warrior1,warrior2)
				raw_input("\nPush <Enter> to continue.")
			else:
				warrior1.updateHP(int(warrior2.getDamStat()*.2))
				warrior2.updateHP(int(warrior1.getDamStat()*.2))
				print
				print self.announcer.getCriticalBoth()
				raw_input("\nPush <Enter> to continue.")

		elif aroll > droll:
			if warrior1.getDex() > warrior1.getStr():
				try:
					warrior2.updateHP(warrior1.getDamStat() * randrange(0,int(warrior1.getDex()*.2)) - randrange(0,int(warrior2.getDefValue())))
				except ValueError:
					warrior2.updateHP(warrior1.getDamStat() - randrange(0,1 + int(warrior2.getDefValue())))
				print
				print self.announcer.getHit(warrior1,warrior2)
				raw_input("\nPush <Enter> to continue.")
			else:
				try:
					warrior2.updateHP(warrior1.getDamStat() * randrange(0,int(warrior1.getStr()*.2 - randrange(0,int(warrior2.getDefValue())))))
				except ValueError:
					warrior2.updateHP(warrior1.getDamStat() - randrange(0,1 + int(warrior2.getDefValue())))
				print
				print self.announcer.getHit(warrior1,warrior2)
				raw_input("\nPush <Enter> to continue.")

		else:
			print
			print self.announcer.getDodge(warrior1,warrior2)
			raw_input("\nPush <Enter> to continue.")
示例#13
0
    def __init__(self, pid, config, songconf, game):
        self.theme = GFXTheme(
            mainconfig.get("%s-theme" % game.theme, "default"), pid, game)
        self.pid = pid
        self.failed = False
        self.escaped = False

        self.__dict__.update(config)

        if self.speed < 0:
            self.target_bpm = -self.speed
        else:
            self.target_bpm = None

        self.game = game

        if self.scrollstyle == 2: self.top = 240 - game.width / 2
        elif self.scrollstyle == 1: self.top = 352
        else: self.top = 64

        self.secret_kind = songconf["secret"]

        self.score = scores.scores[songconf["scoring"]](pid, "NONE", game)
        self.combos = combos.combos[songconf["combo"]](pid, game)
        self.grade = grades.grades[songconf["grade"]]()
        Lifebar = lifebars.bars[songconf["lifebar"]]
        self.lifebar = Lifebar(pid, self.theme, songconf, game)
        self.judging_disp = JudgingDisp(self.pid, game)
        self.stats = stats.Stats()
        self.announcer = Announcer(mainconfig["djtheme"])

        self.listeners = [
            self.combos, self.score, self.grade, self.lifebar,
            self.judging_disp, self.stats, self.announcer
        ]

        if not game.double:
            self.judge = judge.judges[songconf["judge"]](self.pid, songconf)
            self.listeners.append(self.judge)
            arr, arrfx = self.theme.toparrows(self.top, self.pid)
            self.toparr = arr
            self.toparrfx = arrfx
            self.listeners.extend(arr.values() + arrfx.values())
            self.holdtext = HoldJudgeDisp(self.pid, self, self.game)
            self.listeners.append(self.holdtext)
        else:
            Judge = judge.judges[songconf["judge"]]
            self.judge = [
                Judge(self.pid * 2, songconf),
                Judge(self.pid * 2 + 1, songconf)
            ]
            self.listeners.extend(self.judge)
            arr1, arrfx1 = self.theme.toparrows(self.top, self.pid * 2)
            arr2, arrfx2 = self.theme.toparrows(self.top, self.pid * 2 + 1)
            self.arrows = [
                self.theme.arrows(self.pid * 2),
                self.theme.arrows(self.pid * 2 + 1)
            ]
            self.toparr = [arr1, arr2]
            self.toparrfx = [arrfx1, arrfx2]
            self.listeners.extend(arr1.values() + arr2.values() +
                                  arrfx1.values() + arrfx2.values())
            self.holdtext = [
                HoldJudgeDisp(self.pid * 2, self, self.game),
                HoldJudgeDisp(self.pid * 2 + 1, self, self.game)
            ]
            self.listeners.extend(self.holdtext)
示例#14
0
class AnnouncerTestCase(TestCase):
    def setUp(self):
        self.announcer = Announcer()

    def test_subscribe_do_with_announcement(self):
        a = A()
        a.holder = 10
        self.holder = 0

        def func(announcement):
            self.holder = announcement.holder

        self.announcer.subscribe(when=A, do=func)

        self.assertEqual(self.holder, 0)
        self.announcer.announce(a)
        self.assertEqual(self.holder, 10)

    def test_subscribe_send_to(self):
        a = A()
        a.holder = 10
        self.holder = 0

        self.announcer.subscribe(when=A, send='setHolder', to=self)

        self.assertEqual(self.holder, 0)
        self.announcer.announce(a)
        self.assertEqual(self.holder, 10)

    def setHolder(self, announcement):
        self.holder = announcement.holder

    def test_subscribe_send_to_with_multi_subscriber(self):
        a = A()
        a.holder = 5
        self.holder = 0

        for i in range(2):
            self.announcer.subscribe(when=A, send='addHolder', to=self)

        self.assertEqual(self.holder, 0)
        self.announcer.announce(a)
        self.assertEqual(self.holder, 10)

    def addHolder(self, announcement):
        self.holder += announcement.holder

    def test_subscribe_send_to_with_inherited_announcement(self):
        a = A()
        b1 = B1()
        b2 = B2()

        def makeAppendHolderOf(s):
            def appendHolder(ann):
                self.holder.add(s)

            return appendHolder

        self.announcer.subscribe(when=A, do=makeAppendHolderOf('A'))

        self.announcer.subscribe(when=B1, do=makeAppendHolderOf('B1'))

        self.announcer.subscribe(when=B2, do=makeAppendHolderOf('B2'))

        self.holder = set()
        self.announcer.announce(b1)
        self.assertTrue({'B1'} == self.holder)

        self.holder = set()
        self.announcer.announce(b2)
        self.assertTrue({'B2'} == self.holder)

        self.holder = set()
        self.announcer.announce(a)
        self.assertTrue({'A', 'B1', 'B2'} == self.holder)

    def appendHolder(self, announcement):
        self.holder.add(announcement.value())
示例#15
0
文件: pong.py 项目: willkang7/pong_2
class Pong:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game resources."""
        self.screen = turtle.Screen()
        self.screen.title("Pong")
        self.screen.bgcolor("black")
        self.screen.setup(width=800, height=600)
        self.screen.tracer(0)

        # Game assets
        self.sb = Scoreboard()
        self.announcer = Announcer()
        self.paddle_a = Paddle(-350, 0)
        self.paddle_b = Paddle(350, 0)
        self.ball = Ball()
        self.game_active = True

        # Keyboard bindings
        self.screen.listen()
        self.screen.onkeypress(self.paddle_a.start_move_up, 'w')
        self.screen.onkeypress(self.paddle_a.start_move_down, 's')
        self.screen.onkeyrelease(self.paddle_a.stop_move_up, 'w')
        self.screen.onkeyrelease(self.paddle_a.stop_move_down, 's')
        self.screen.onkeypress(self.paddle_a.start_long, 'r')
        self.screen.onkeypress(self.paddle_a.prime_fastball, 't')
        self.screen.onkeypress(self.paddle_b.start_move_up, 'Up')
        self.screen.onkeypress(self.paddle_b.start_move_down, 'Down')
        self.screen.onkeyrelease(self.paddle_b.stop_move_up, 'Up')
        self.screen.onkeyrelease(self.paddle_b.stop_move_down, 'Down')
        self.screen.onkeypress(self.paddle_b.start_long, ',')
        self.screen.onkeypress(self.paddle_b.prime_fastball, '.')

    def run_game(self):
        """Start the main loop for the game."""
        while self.game_active:
            self._update_paddles()
            self._update_ball()
            self._check_paddle_ball_collision()
            self._check_score()
            self.screen.update()
            time.sleep(1 / 120)

    def _update_paddles(self):
        """Update the positions of the paddles."""
        self.paddle_a.update()
        self.paddle_b.update()

    def _update_ball(self):
        """Update the position of the ball."""
        self.ball.move()
        hit_border = self.ball.check_horizontal_borders()
        if hit_border:
            winsound.PlaySound("sounds/bounce.wav", winsound.SND_ASYNC)

    def _check_paddle_ball_collision(self):
        """Check if a paddle and ball collided."""
        if (self.ball.xcor() < -340 and self.ball.xcor() > -350 and
                self.ball.ycor() < self.paddle_a.ycor() + self.paddle_a.hitbox
                and self.ball.ycor() >
                self.paddle_a.ycor() - self.paddle_a.hitbox):
            self.ball.dx *= -1
            winsound.PlaySound("sounds/bounce.wav", winsound.SND_ASYNC)
            self.ball.increase_speed()
            self.paddle_a.end_long()
            self.paddle_b.end_fastball(self.ball)
            self.paddle_a.start_fastball(self.ball)
        elif (self.ball.xcor() > 340 and self.ball.xcor() < 350 and
              self.ball.ycor() < self.paddle_b.ycor() + self.paddle_b.hitbox
              and
              self.ball.ycor() > self.paddle_b.ycor() - self.paddle_b.hitbox):
            self.ball.dx *= -1
            winsound.PlaySound("sounds/bounce.wav", winsound.SND_ASYNC)
            self.ball.increase_speed()
            self.paddle_b.end_long()
            self.paddle_a.end_fastball(self.ball)
            self.paddle_b.start_fastball(self.ball)

    def _check_score(self):
        """Check if a player scored."""
        if self.ball.xcor() > 410:
            self.sb.increment_a()
        elif self.ball.xcor() < -410:
            self.sb.increment_b()
        else:
            return False

        # Reset round only if a player scored.
        self._reset_round()

    def _reset_round(self):
        """Announce point and reset positions."""
        # Check to finish the game.
        if self.sb.score_a == 5 or self.sb.score_b == 5:
            winsound.PlaySound("sounds/game_finished.wav", winsound.SND_ASYNC)
            self.announcer.announce_finished()
            time.sleep(3)
            self.game_active = False

        # Check to finish the round.
        else:
            if self.sb.get_consecutive_points() > 2:
                winsound.PlaySound("sounds/dominating.wav", winsound.SND_ASYNC)
                self.announcer.announce_dominating()
            else:
                winsound.PlaySound("sounds/point_scored.wav",
                                   winsound.SND_ASYNC)
                self.announcer.announce_point()
            time.sleep(1)

            # Get ready for next round.
            self.announcer.clear_announcement()
            self.ball.reset_position()
            self.ball.reset_speed()
            self.paddle_a.reset()
            self.paddle_b.reset()
示例#16
0
    def play_game(self):
        """Playing the game."""
        announcer = Announcer()
        diff = announcer.display_supported_difficulties()
        lang = announcer.ask_for_language()

        self.read_from_file(announcer.difficulty[diff][1][0],
                            announcer.difficulty[diff][1][1], lang)

        chosen_word = self.choose_word()
        hidden_word = self.hidden_word(chosen_word)
        won = False
        print("The word is: {}\n".format(" ".join(hidden_word)))

        while self.tries > 0 and not won:
            announcer.display_dashed_word()
            inp = announcer.ask_for_input()
            while self.letter_has_been_used(inp):
                print("You already used letter: '{}'".format(inp))
                inp = self.ask_for_input()
            self.used_letters.append(inp)
            print("Used letters: {}\n".format(sorted(self.used_letters)))

            if self.right_guess(chosen_word, hidden_word, inp):
                announcer.right_guess_feedback(inp, hidden_word)
            else:
                announcer.wrong_guess_feedback(inp, hidden_word)
                announcer.tries -= 1

            # Check if game has been won or not.
            if announcer.game_over_won(hidden_word):
                won = True
            elif announcer.tries == 0:
                announcer.game_over_lost(chosen_word)
                exit()
示例#17
0
 def setUp(self):
     self.announcer = Announcer()
示例#18
0
文件: judge.py 项目: Scowley4/pydance
 def __init__(self, pid, songconf):
     self._pid = pid
     self._scale = songconf["judgescale"]
     self._ann = Announcer(mainconfig["djtheme"])
示例#19
0
class Worker(object):
    def __init__(self,
                 mqtt_server_ip,
                 mqtt_server_port,
                 mqtt_user=None,
                 mqtt_pass=None,
                 mqtt_base_topic="megaphone",
                 mp3_filename="output.mp3",
                 ext_amp_conf: ExternalAmplifierConfig = None):
        self.mqtt_server_ip = mqtt_server_ip
        self.mqtt_server_port = mqtt_server_port
        self.mqtt_user = mqtt_user
        self.mqtt_pass = mqtt_pass
        self.mqtt_base_topic = mqtt_base_topic
        self.client: mqtt.Client = mqtt.Client()
        self.mp3_filename = mp3_filename
        self.ext_amp_conf: ExternalAmplifierConfig = ext_amp_conf

        signal.signal(signal.SIGINT, self.signal_handler)
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect
        if (self.mqtt_user is not None) and (self.mqtt_pass is not None):
            self.client.username_pw_set(self.mqtt_user,
                                        password=self.mqtt_pass)
        self.client.will_set(f"{self.mqtt_base_topic}/state",
                             payload="offline",
                             retain=True)
        self.announcer = Announcer()
        self.announcer.on_status_change = self.status_change

    # noinspection PyUnusedLocal
    def signal_handler(self, signum, frame):
        print('You pressed Ctrl+C - or killed me with -2')
        print("disconnect handler")
        self.client.publish(f"{self.mqtt_base_topic}/state", payload='offline')
        self.client.disconnect()
        sys.exit(0)

    def status_change(self, message):
        print(message)
        self.client.publish(f"{self.mqtt_base_topic}/log", payload=message)

    # noinspection PyUnusedLocal
    def on_connect(self, client, userdata, flags, rc):
        print("error = " + str(rc))
        self.client.publish(f"{self.mqtt_base_topic}/state", payload='online')
        self.client.subscribe(f"{self.mqtt_base_topic}/announce")

    # noinspection PyUnusedLocal
    def on_disconnect(self, userdata, flags, rc):
        print("disconnect on")
        self.client.publish(f"{self.mqtt_base_topic}/state",
                            payload='offline',
                            retain=True)

    # noinspection PyUnusedLocal
    def on_message(self, client, userdata, msg):
        my_json = msg.payload.decode('utf8')
        is_parsing_ok: bool = False
        payload = None
        try:
            data = json.loads(my_json)
            print(data)
            payload = data['payload']
            text = '{"payload": "' + payload + '"}'
            self.client.publish(f"{self.mqtt_base_topic}/log", payload=payload)
            is_parsing_ok = True
        except Exception as e:
            print(e)
            self.client.publish(f"{self.mqtt_base_topic}/log",
                                payload='wrong announce structure')
        if is_parsing_ok:
            try:
                self.announcer.say(payload)
            except Exception as e:
                print(e)
                self.client.publish(f"{self.mqtt_base_topic}/log",
                                    payload='Playing failed')

    def run(self):
        self.client.connect(self.mqtt_server_ip, self.mqtt_server_port, 60)
        self.client.loop_start()
        while True:
            time.sleep(10)
示例#20
0
def do(screen, songdata):

  onoff_opt = { ui.START: switch_onoff, ui.CONFIRM: switch_onoff,
                menus.CREATE: get_onoff, ui.LEFT: off_onoff,
                ui.RIGHT: on_onoff }
  offon_opt = { ui.START: switch_offon, ui.START: switch_offon,
	menus.CREATE: get_offon, ui.LEFT: off_offon, ui.RIGHT: on_offon }
  rotate_opt = { ui.START: switch_rotate, ui.CONFIRM: switch_rotate,
                 ui.LEFT: switch_rotate_back,
                 ui.RIGHT: switch_rotate,
                 menus.CREATE: get_rotate }
  rotate_index_opt = { ui.START: switch_rotate_index,
                       ui.CONFIRM: switch_rotate_index,
                       ui.LEFT: switch_rotate_index_back,
                       ui.RIGHT: switch_rotate_index,
                       menus.CREATE: get_rotate_index }
  tuple_opt = { ui.START: switch_tuple, ui.CONFIRM: switch_tuple,
                ui.LEFT: switch_tuple_back,
                ui.RIGHT: switch_tuple,
                menus.CREATE: get_tuple }

  sprites = pygame.sprite.RenderUpdates()
  try:
    lines = file(os.path.join(pydance_path, "CREDITS")).read().split("\n")
    lines = [l.decode("utf-8") for l in lines]
    Credits([_("pydance %s") % VERSION] + lines).add(sprites)
  except:
    Credits([_("pydance %s") % VERSION,
             "http://icculus.org/pyddr",
             _("By Joe Wreschnig, Brendan Becker, & Pavel Krivitsky"),
             _("(Your CREDITS file is missing.)"),
             ]).add(sprites)

  m = ([_("Play Game"), {ui.START: wrap_ctr, ui.CONFIRM: wrap_ctr},
	(GameSelect, songdata)],
       [_("Map Keys"), {ui.START: wrap_ctr, ui.CONFIRM: wrap_ctr},
        (pad.PadConfig, (screen,))],
       (_("Game Options"),
        [_("Autofail"), onoff_opt, (_("autofail"),)],
        [_("Assist Mode"), tuple_opt, (_("assist"),
                                    [(0, _("Off")),
                                     (1, _("Click")),
                                     (2, _("Full"))])],
        [_("Announcer"), rotate_opt, ('djtheme', Announcer.themes())],
        (_("Themes ..."),
         [_("4 Panel"), rotate_opt,
          ("4p-theme", ThemeFile.list_themes("SINGLE"))],
         [_("3 Panel"), rotate_opt,
          ("3p-theme", ThemeFile.list_themes("3PANEL"))],
         [_("5 Panel"), rotate_opt,
          ("5p-theme", ThemeFile.list_themes("5PANEL"))],
         [_("Large 6 Panel"), rotate_opt,
          ("6pl-theme", ThemeFile.list_themes("6PANEL"))],
         [_("Small 6 Panel"), rotate_opt,
          ("6ps-theme", ThemeFile.list_themes("6VERSUS"))],
         [_("Large 8 Panel"), rotate_opt,
          ("8pl-theme", ThemeFile.list_themes("8PANEL"))],
         [_("Small 8 Panel"), rotate_opt,
          ("8ps-theme", ThemeFile.list_themes("8VERSUS"))],
         [_("Large 9 Panel"), rotate_opt,
          ("9pl-theme", ThemeFile.list_themes("9PANEL"))],
         [_("Small 9 Panel"), rotate_opt,
          ("9ps-theme", ThemeFile.list_themes("9VERSUS"))],
         [_("Parapara"), rotate_opt,
          ("para-theme", ThemeFile.list_themes("PARAPARA"))],
         [_("DMX"), rotate_opt,
          ("dmx-theme", ThemeFile.list_themes("DMX"))],
         [_("EZ2"), rotate_opt,
          ("ez2-theme", ThemeFile.list_themes("EZ2SINGLE"))],
         [_("EZ2 Real"), rotate_opt,
          ("ez2real-theme", ThemeFile.list_themes("EZ2REAL"))],
         [_("Back"), None, None]
         ),
        [_("Back"), None, None]
        ),
       (_("Graphic Options"),
        [_("Animation"), onoff_opt, ('animation',)],
        [_("Arrow Effects"), rotate_index_opt,
         ('explodestyle', (_('none'), _('rotate'), _('scale'), _('rotate & scale')))],
        [_("Backgrounds"), onoff_opt, ('showbackground',)],
        [_("Brightness"), tuple_opt, ('bgbrightness',
                                   [(32, _('very dark')),
                                    (64, _('dark')),
                                    (127, _('normal')),
                                    (192, _('bright')),
                                    (255, _('very bright'))])],
        [_("Lyrics"), onoff_opt, ("showlyrics",)],
        [_("Lyrics Color"), rotate_opt, ("lyriccolor",
                                     [_("pink/purple"), _("purple/cyan"),
                                      _("cyan/aqua"), _("aqua/yellow"),
                                      _("yellow/pink")])],
        [_("Back"), None, None]
        ),
       (_("Interface Options"),
        [_("Save Input"), onoff_opt, ('saveinput',)],
        [_("Song Previews"), tuple_opt, ('previewmusic',
                                      [(0, "Off"), (1, "On"), (2, "Safe")])],
        [_("Folders"), onoff_opt, ("folders",)],
        [_("Timer Display"), onoff_opt, ('fpsdisplay',)],
        [_("Song Info Screen"), tuple_opt, ('songinfoscreen',
                                         zip([0, 1, 2],
                                             [_("Never"), _("Multi-song Only"), _("Always")]))],
        [_("Font (after restart)"), rotate_opt, ('fonttheme', FontTheme.themes())],
        [_("Calibrate Latency"), {ui.START: wrap_ctr, ui.CONFIRM: wrap_ctr}, (calibrate.run, (screen,))],
        [_("Back"), None, None]
        )
       )

  me = menus.Menu(_("Main Menu"), m, screen, sprites)
  me.display()
示例#21
0
 def __init__(self):
   self.GPIO_handler = GPIO_handler()
   self.announcer    = Announcer()
   self.scores       = [0, 0]
   self.paused       = False