예제 #1
0
 def testRing(self):
     ring = Ring()
     self.assertEqual(ring.polished, True)
     ring.wear()
     self.assertEqual(ring.polished, False)
     ring.polish()
     self.assertEqual(ring.polished, True)
예제 #2
0
    def __init__(self, expression):

        FieldItem.__init__(self)

        # Parse Expression if needed
        if type(expression) is str:
            expression = parse(expression)
            debug(2, 'init Figure', expression)

        self.expression = expression.withRoot()

        # History of Expression
        self.history = history.History()

        # Colorspace
        self.detColorSpace()

        # Size of Figure
        self.sizeRing = Ring(
            (0, 0), 1.0)  # Ring for setting size of Figure (used in morphing)
        self.refreshTransform()

        self.groups = []
        self.buildGroups()
        self.buildGeometry()

        self.history.step(self.expression.copy())

        # Eating Act
        self.eating = None
 def __init__(self, tap):
     """
     tap (RingPosition): the starting point where our stretch begins
     """
     self.__in_tap = tap
     self.__buffer = Ring(2**16)
     self.__fading_out = False
예제 #4
0
    def prepare(self):
        ame_data = AMEData(DummyIFace())

        # create reference particle
        p = Particle(6, 6, ame_data, Ring('ESR', 108.5))
        p.qq = 3
        p.ke_u = 422
        p.path_length_m = 108.5
        p.f_analysis_mhz = 245
        p.i_beam_uA = 1.2
        print('Reference particle:', p)
        print('Isobars:')
        for pp in p.get_isobars():
            print(pp)
        # get some nuclides
        # nuclides = p.get_all_in_all()
        nuclides = p.get_nuclides(57, 59, 81, 83, 2)
        #nuclides = p.get_nuclides(20, 92, 40, 143, 10)
        self.n_rows = int(len(nuclides))

        self.nuclidic_data = np.array([])
        self.nuclidic_labels = []

        for pp in nuclides:
            pp.calculate_revolution_frequency()
            brho = pp.get_magnetic_rigidity()
            values = [pp.revolution_frequency, brho]
            self.n_cols = len(values)

            self.nuclidic_data = np.append(self.nuclidic_data, values)
            self.nuclidic_labels.append(pp.get_short_name())

        # print(self.nuclidic_labels)
        self.nuclidic_data = np.reshape(self.nuclidic_data,
                                        (self.n_rows, self.n_cols))
예제 #5
0
 def key_listener(self, event):
     key = repr(event.char) 
     if key == "'q'":
         self.entities.append(Ring("blue", self))
     else:
         for i in self.entities:
             if type(i) is Ring:
                 ring = i
                 print("Ring pos: " , ring.y)
                 msg = self.check_accuracy(ring.y)
예제 #6
0
	def gameSummary(self, p1peer, p2peer, s1peer, winner):
		p1key = p1peer[2].publickey if p1peer[2] is not None else self.main.getPublicKey()
		p2key = p2peer[2].publickey if p2peer[2] is not None else self.main.getPublicKey()
		s1key = s1peer[2].publickey if s1peer[2] is not None else self.main.getPublicKey()
		
		scoreJsonHash, scoreJson = self.createScoreFile(p1peer, p2peer, s1peer, winner)
		
		myprivateKey = self.main.rsaKey;

		if p1peer[2] is None:
			#create two ring with both player and sign it and send it to the other two
			ringP1P2 = Ring([p1key, p2key], 2048)
			ringP1S1 = Ring([p1key, s1key], 2048)

			signp1p2 = ringP1P2.sign(scoreJsonHash, myprivateKey);
			signp1s1 = ringP1S1.sign(scoreJsonHash, myprivateKey);

			signs = [{"player1:player2": signp1p2}, {"player1:spectator": signp1s1}]
		
		if p2peer[2] is None:
			ringP1P2 = Ring([p1key, p2key], 2048)
			ringP2S1 = Ring([p2key, s1key], 2048)

			signp1p2 = ringP1P2.sign(scoreJsonHash, myprivateKey);
			signp2s1 = ringP2S1.sign(scoreJsonHash, myprivateKey);

			signs = [{"player1:player2": signp1p2}, {"player2:spectator": signp2s1}]
		
		if s1peer[2] is None:
			ringP1S1 = Ring([p1key, s1key], 2048)
			ringP2S1 = Ring([p2key, s1key], 2048)

			signp1s1 = ringP1S1.sign(scoreJsonHash, myprivateKey);
			signp2s1 = ringP2S1.sign(scoreJsonHash, myprivateKey);

			signs = [{"player1:spectator": signp1s1}, {"player2:spectator": signp2s1}]
	
		self.summary = [{"result": scoreJson,
					"sha256": scoreJsonHash,
					"sign": signs[0]
				},{"result": scoreJson,
					"sha256": scoreJsonHash,
					"sign": signs[1]
				}]
		print ">>>>>>>Summary ready<<<<<<<";
		self.webclient.sendMessage(WebSocketMessage.create
					("local","TTTS_GAME_OVER_MSGS","Game Result Object [" + str(scoreJsonHash) + "] created and signed"))
	
	
		#print "<<Results>>"
		#print summary
		#print
		
		if p1peer[2] is None:
			self.main.sendMulticast("SIGN_RESULT")
			
			signedResults = self.summary
			
			self.main.sendMulticast("RESULT_RING " + json.dumps(signedResults[0]))
			self.main.sendMulticast("RESULT_RING " + json.dumps(signedResults[1]))
예제 #7
0
def test_tap_activation():
    a = Ring(16)
    t = a.create_tap()
    t.deactivate()
    assert t.name in a.inactive_taps
    assert t.name not in a.active_taps
    a.append(np.arange(15))
    a.append([99])
    t.activate()
    assert t.name in a.active_taps
    assert t.name not in a.inactive_taps
    s = t.get_samples(1)
    assert s[0] == 99
예제 #8
0
    def start_draft(
        self,
        users: t.Iterable[AbstractUser],
        pool_specification: PoolSpecification,
        infinites: Infinites,
        draft_format: str,
        reverse: bool,
        finished_callback: t.Callable[[Draft], None],
    ) -> t.Tuple[t.Tuple[AbstractUser, Drafter], ...]:

        drafters = tuple(
            (
                user,
                Drafter(
                    user,
                    str(uuid.uuid4()),
                ),
            )
            for user in
            users
        )

        drafters_ring = Ring(
            drafter
            for _, drafter in
            drafters
        )

        def _finished_callback(_draft: Draft):
            self.draft_complete(_draft)
            finished_callback(_draft)

        draft = Draft(
            key = str(uuid.uuid4()),
            drafters = drafters_ring,
            pool_specification = pool_specification,
            infinites = infinites,
            draft_format = draft_format,
            finished_callback = _finished_callback,
            reverse = reverse,
        )

        draft.start()

        with self._lock:
            self._drafts.add(draft)

            for drafter in drafters_ring.all:
                self._drafters[drafter.key] = draft.get_draft_interface(drafter)

        return drafters
예제 #9
0
    def __init__(self, env, inner_circle_len, outer_circle_len):
        # Test circle lengths
        for circle_len in (inner_circle_len, outer_circle_len):
            assert circle_len >= 16, 'Circle lenght has to be at least 16'
            assert circle_len % 4 == 0, 'Circle lenght must be divisible by 4'

        self.env = env

        # Generate circles of Resources
        self.inner_circle = Ring([
            simpy.resources.resource.PriorityResource(env, capacity=1)
            for i in range(inner_circle_len)
        ])
        self.outer_circle = Ring([
            simpy.resources.resource.PriorityResource(env, capacity=1)
            for i in range(outer_circle_len)
        ])

        # Create indices of exit slots (exit pointers)
        self.inner_exits_indices = RoundAbout.Exits(
            *RoundAbout.calculate_exit_indices(inner_circle_len))
        self.outer_exits_indices = RoundAbout.Exits(
            *RoundAbout.calculate_exit_indices(outer_circle_len))
예제 #10
0
    def getBounding(bubbles):
        "Returns Bounding Ring of Bubbles in Group"

        center = Vector2((0, 0))
        ws = 0
        for b in bubbles:
            weight = b.ring.r**2
            center += b.ring.pos * weight
            ws += 1.0 * weight
        center /= ws

        radius = max([ Vector2( center, b.ring.pos ).length() + b.ring.r  \
                        for b in bubbles ])

        return Ring(center, radius)
예제 #11
0
 def testNecklace(self):
     testMetal: str = "platinum"
     testGem: str = "ruby"
     testSize: int = 8
     ring = Ring(metal=testMetal, gem=testGem, size=testSize)
     self.assertEqual(ring.gem, "ruby")
     self.assertEqual(ring.metal, "platinum")
     ring.gem = "pearl"
     ring.metal = "titanium"
     ring.size = 7
     self.assertEqual(ring.gem, "pearl")
     self.assertEqual(ring.metal, "titanium")
     ring.wear()
     self.assertEqual(ring.polished, False)
     ring.polish()
     self.assertEqual(ring.polished, True)
예제 #12
0
    def __init__(self):

        # Group Topology
        self.parent = None  # Noke  # not Bubble: for Group.buildGeometry()
        self.childs = []  # Nokes
        self.upper = False  # Upper level - first child

        self.group = None  # Parent Group of Bubble

        # Geometry and Correction
        self.ring = Ring((0, 0), 1)

        # For building Geometry
        self.tight = 0  # Left (Parents) and right (Childs) Tights
        self.corr = 0  # Correction of Radius
        self.angles = {}  # dict {Bubble:angle}

        # Eating
        self.fading = None  # Fading object
예제 #13
0
파일: node.py 프로젝트: vamc19/pythonamo
    def __init__(self, is_leader, leader_hostname, my_hostname, tcp_port=13337, sloppy_Qsize=5, sloppy_R=3, sloppy_W=3):

        self.ongoing_requests = []
        self.is_leader = is_leader
        self.leader_hostname = leader_hostname
        self.hostname = my_hostname
        self.tcp_port = tcp_port
        self.my_address = (self.hostname, self.tcp_port)

        self.membership_ring = Ring(replica_count=sloppy_Qsize - 1)  # Other nodes in the membership
        if self.is_leader:
            self.membership_ring.add_node(leader_hostname)

        # todo: look into this, do we need both?
        self.bootstrapping = True
        self.is_member = False

        # Flag to keep track of a add-node is underway
        self._membership_in_progress = False

        self.sloppy_Qsize = sloppy_Qsize  # total members to replicate on

        # number of peers required for a read or write to succeed.
        self.sloppy_R = sloppy_R
        self.sloppy_W = sloppy_W

        # Book keeping for membership messages
        self._req_responses = defaultdict(set)
        self._sent_req_messages = {}
        self._received_req_messages = {}
        self._req_sender = {}  # Keeps track to sender for add and delete requests
        self.current_view = 0  # increment this on every leader election
        self.membership_request_id = 0  # increment this on every request sent to peers

        # Maintains handoff messages to be sent
        # IP : set(handoff messages)
        self._handoff_messages = defaultdict(set)
        self.handoff_timer = None
        self.create_handoff_timer = lambda: Timer(5, self.try_sending_handoffs)

        self.log_prefix = os.getcwd()
        self.ring_log_file = os.path.join(self.log_prefix, self.hostname + '.ring')
        self.db_path = os.path.join(self.log_prefix, self.hostname + '.db')
        self.handoff_log = os.path.join(self.log_prefix, self.hostname + '.pickle')

        try:
            with open(self.ring_log_file, 'r') as f:
                hosts = f.readlines()
                for h in hosts:
                    self.membership_ring.add_node(h.strip())
            print("Restored membership information from %s" % self.ring_log_file)
        except FileNotFoundError:
            pass

        try:
            with open(self.handoff_log, 'rb') as f:
                self._handoff_messages = pickle.loads(f.read())

            if len(self._handoff_messages) > 0:
                self.handoff_timer = self.create_handoff_timer()
                self.handoff_timer.start()

            print("Restored hand off messages from %s" % self.handoff_log)
        except FileNotFoundError:
            pass

        self.request_timelimit = 2.0
        self.req_message_timers = {}

        self.db = Storage(self.db_path)  # set up sqlite table

        # create tcp socket for communication with peers and clients
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_socket.setblocking(False)  # Non-blocking socket
        self.tcp_socket.bind((self.hostname, self.tcp_port))
        self.tcp_socket.listen(10)

        # has hostnames mapped to open sockets
        self.connections = {}
        self.client_list = set()
예제 #14
0
    def test_ring_size(self):
        ring = Ring(1)

        self.assertEqual(str(ring), '1')
예제 #15
0
 def add_ring(self):
     r = Ring(self.size)
     r.position = (self.size.width + self.new_pipe_trigger / 2 +
                   Pipe.blocksize / 2, r.position.y)
     self.add_child(r)
     self.rings.append(r)
예제 #16
0
파일: game.py 프로젝트: outshaker/pyCFE
# game object, use ring to keep game running
from card import Deck, Cards
from player import Player
from ring import Ring
from time import sleep

deck = Deck()
disP = Cards()
p1 = Player("A", deck, disP)
p2 = Player("B", deck, disP)
players = Ring([p1, p2])
turn = 0

while True:
    turn = turn + 1
    print("turn#%d " % turn, end='')
    players.now().action()
    players.goNext()
    sleep(1)
예제 #17
0
def creative(c, background, stock, store):

    debug(c.DEBUG, "ENTERING: campaign")

    versionID = stock.getVersion()

    timeClock = clockCounter()
    allSprites = pygame.sprite.Group()
    ringSprite = pygame.sprite.GroupSingle()
    circSprites = pygame.sprite.LayeredUpdates()
    buttonSprites = pygame.sprite.Group()  # @UnusedVariable
    starSprites = pygame.sprite.LayeredUpdates()
    caughtSprite = pygame.sprite.GroupSingle()
    dieingSprites = pygame.sprite.GroupSingle()
    scoreSprite = pygame.sprite.GroupSingle()
    pBox = playBox()  # a jukebox for handling music settings.
    pygame.mixer.music.set_endevent(USEREVENT)

    ring = Ring(c.CENTER, stock.campaign["Ring"], stock.campaign["Ring Glow"],
                c.FULLSCREEN)
    '''CREATE IMAGES'''
    ring.add(ringSprite, allSprites)
    scoreboard = Scoreboard(c.DISPLAY_W, c.DISPLAY_H)
    scoreboard.add(scoreSprite, allSprites)
    box_img = stock.campaign["RGB Light"]
    background_rect = background.get_rect()
    background_rect.center = c.CENTER
    OGBackground = background.copy()
    '''INSTANTIATING OTHER VARIABLES'''
    rotAngle = 0  # background rotation angle
    waitCounterCirc = 0
    waitCounterStar = 0
    countingCircleTime = False
    countingStarTime = False
    countingWaitTime = False
    totalWaitTime = 0
    totalCircleTime = 0
    totalStarTime = 0
    newStartTime = 0
    oldStartTime = 0
    pause_selection = 0
    newCircleColor = ''
    oldCircleColor = ''
    newStarAngle = ''
    oldStarAngle = ''
    circleWaitStart = 0
    circleWaitMade = 0
    circleColor = ''
    starWaitStart = 0
    starWaitMade = 0
    pauseStartTime = None  #datetime variable
    pauseEndTime = None  #datetime variable
    finishedCircleActions = False
    finishedStarActions = False
    circleAction = '_'
    starAction = '_'
    counter = 0
    starWaiting = False
    circleWaiting = False
    countingWaitTime = False
    r = 0
    g = 0
    b = 0
    paused = False
    total_input = 0
    fpsList = []
    toggle_color_r = False
    toggle_color_g = False
    toggle_color_b = False
    display_sprites = True
    controls = c.CONTROL_LIST
    leftHold = False
    rightHold = False
    upHold = False
    downHold = False
    quitGame = False  # if user returns a True from pause, we quit game, etc.
    startTime = 0
    newInput = True
    currentColor = (0, 0, 0)
    colorList = ""

    # open the files that we'll be saving to.
    genFile = os.path.join(c.DATA_DIR, 'creative_commands/genCommands.txt')
    circleFile = os.path.join(c.DATA_DIR,
                              'creative_commands/circleCommands.txt')
    starFile = os.path.join(c.DATA_DIR, 'creative_commands/starCommands.txt')
    genFile = open(genFile, 'w')
    circleFile = open(circleFile, 'w')
    starFile = open(starFile, 'w')
    """BUTTON / SPRITE RENDERING"""
    r_letter = c.FONT_LARGE.render('R', True, c.RED)
    r_letter.scroll(2, 0)
    r_letter_rect = r_letter.get_rect()
    r_letter_rect.center = (c.CENTER_X - 50, (c.CENTER_Y * 2) - 20)
    box_rectR = r_letter_rect

    g_letter = c.FONT_LARGE.render('G', True, c.GREEN)
    g_letter.scroll(1, 0)
    g_letter_rect = g_letter.get_rect()
    g_letter_rect.center = (c.CENTER_X, (c.CENTER_Y * 2) - 20)
    box_rectG = g_letter_rect

    b_letter = c.FONT_LARGE.render('B', True, c.BLUE)
    b_letter.scroll(2, 0)
    b_letter_rect = b_letter.get_rect()
    b_letter_rect.center = (c.CENTER_X + 50, (c.CENTER_Y * 2) - 20)
    box_rectB = b_letter_rect

    stageDisplay = stock.creative["Circle Building"]
    stageDisplay_rect = stageDisplay.get_rect()
    stageDisplay_rect.topright = (c.DISPLAY_W, 0)

    debug(c.DEBUG, "Variable and object instantiating successful.")
    showSplashScreen(c, stock)
    load_song(c, "It's Melting.ogg")  # stops other music from playing too

    debug(c.DEBUG, "Stars and Circles ready! ")

    debug(c.DEBUG, "Now building Circles")

    # --CIRCLE MAKING Loop//--
    going = True
    pygame.mixer.music.play(0, 0)
    timeClock.playTimeSet()
    while going:
        counter += 1
        # Paint the background
        c.DISPLAYSURFACE.fill((0, 0, 0))
        c.DISPLAYSURFACE.blit(background, background_rect)
        if counter % 5 == 0:
            background, background_rect, rotAngle = \
            rotateBackground(c.CENTER, OGBackground, counter, rotAngle)
        """LOGGING output information: FPS, event info, AA, etc."""
        # for every 30 or FPS number of frames, print an average fps.
        fpsList.append(c.FPSCLOCK.get_fps())
        if counter == (c.FPS * 5):
            debug(c.DEBUG, ("Average FPS: {0}".format(mean(fpsList))))
            debug(c.DEBUG,
                  ("Current Score: {0}".format(scoreboard.scoreString)))
            counter = 0
            pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList)))
            fpsList = []

        #=======================================================================
        # """Get input to know if we should put in a wait action"""
        # if total_input == 0:
        #     if not countingWaitTime:
        #         debug(c.DEBUG, "STARTING COUNT WAIT TIME")
        #         countingWaitTime = True
        #         timeClock.setTime(1)
        #=======================================================================

        if newCircleColor != '':
            oldCircleColor = newCircleColor
        """EVENT HANDLING INPUT"""
        # grab all the latest input
        latest_events = pygame.event.get()
        for event in latest_events:
            if event.type == QUIT:
                going = False
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                if c.DEBUG:
                    going = False
                    pygame.mixer.music.stop()
                #===============================================================
                # else:
                #     # have to time how long pause takes, for the wait.
                #     pauseStartTime = datetime.datetime.now()
                #     pause_selection = pause()
                #     pauseEndTime = datetime.datetime.now()
                #     pauseTotalTime = (pauseEndTime - pauseStartTime)
                #     starWaitStart = starWaitStart + pauseTotalTime
                #     circleWaitStart = circleWaitStart + pauseTotalTime
                #===============================================================
            # --game-play events//--
            elif event.type == KEYDOWN and event.key == controls[0]:
                r = 255
                toggle_color_r = True
                total_input += 1
                colorList += 'R'
            elif event.type == KEYUP and event.key == controls[0]:
                r = 0
                toggle_color_r = False
                total_input += -1
                colorList = colorList.replace('R', '')
            elif event.type == KEYDOWN and event.key == controls[1]:
                g = 255
                toggle_color_g = True
                total_input += 1
                colorList += 'G'
            elif event.type == KEYUP and event.key == controls[1]:
                g = 0
                toggle_color_g = False
                total_input += -1
                colorList = colorList.replace('G', '')
            elif event.type == KEYDOWN and event.key == controls[2]:
                b = 255
                toggle_color_b = True
                total_input += 1
                colorList += 'B'
            elif event.type == KEYUP and event.key == controls[2]:
                b = 0
                toggle_color_b = False
                total_input += -1
                colorList = colorList.replace('B', '')
            #====================================
            # --non-game-play events//--
            #====================================
            # if O is pressed, toggle context display -------TO BE REMOVED SOON
            elif event.type == KEYDOWN and event.key == K_o:
                if display_sprites == True:
                    display_sprites = False
                else:
                    display_sprites = True
            elif event.type == KEYDOWN and event.key == K_s:
                # add ten seconds to the total playtime.
                pygame.mixer.music.stop()
                newStartTime = (datetime.datetime.now() - timeClock.playTime
                                ).total_seconds() + 10 + oldStartTime
                # since the song is now 10 seconds ahead, we have to make sure there is a 10 second difference
                # in recording of actions.
                timeClock.timeIn = timeClock.timeIn - datetime.timedelta(
                    seconds=10)
                pygame.mixer.music.play(0, newStartTime)
                # need to record where we last began.
                oldStartTime = newStartTime
                debug(c.DEBUG, "new Start Time: %f" % newStartTime)
            # if P is pressed, pause game.
            elif event.type == KEYUP and event.key == controls[7]:
                None
                #===============================================================
                # # have to time how long pause takes, for the wait.
                # pauseStartTime = datetime.datetime.now()
                # pause_selection = pause()
                # pauseEndTime = datetime.datetime.now()
                # pauseTotalTime = (pauseEndTime - pauseStartTime)
                # starWaitStart = starWaitStart + pauseTotalTime
                # circleWaitStart = circleWaitStart + pauseTotalTime
                #===============================================================
            """LOGGING of inputs"""
            if event.type == KEYDOWN or event.type == KEYUP:
                debug(c.DEBUG,
                      (pygame.event.event_name(event.type), event.dict))
                debug(c.DEBUG, "NEWINPUT FOUND")
                newInput = True
                newCircleColor = colorList  # grab color at time of recording.

        if pygame.event.peek(USEREVENT):
            going = False

        if pause_selection == 3:
            going = False
            return

        #if an action has been input, test total_inputs:
        """Get input to know if we should put in a wait action"""
        if not (total_input == 0):
            if countingWaitTime:
                countingWaitTime = False
                totalWaitTime = timeClock.getDelta(True)
                debug(c.DEBUG, "Old wait time recorded")
                circleFile.write(" W{0} ".format(totalWaitTime +
                                                 totalCircleTime))
                # if it isn't counting wait time, then it IS counting circleTime
                countingCircleTime = True
                debug(c.DEBUG, "Now counting circle time")
                timeClock.setTime(1)
                # newInput is set to false, since we already know its a new
                # input based on change in counting. newInput is only
                # relevant for when the circle color changes without a wait
                # in between.
                newInput = False
            else:
                if countingCircleTime:
                    if newInput:
                        #first, we must store the old input.
                        totalCircleTime = timeClock.getDelta(True)
                        circleFile.write(" C{0},{1} ".format(
                            oldCircleColor, totalCircleTime))
                        # a wait time must be introduced so that other circles
                        # don't spawn.
                        circleFile.write(" W{0} ".format(totalCircleTime))
                        newInput = False
                        debug(c.DEBUG, "Old circle time recorded")
                        debug(c.DEBUG, "New circle time recording")
                        #now we start the new Input recording..
                        timeClock.setTime(1)
        else:
            if not countingWaitTime:
                if countingCircleTime:
                    totalCircleTime = timeClock.getDelta(True)
                    circleFile.write(" C{0},{1} ".format(
                        oldCircleColor, totalCircleTime))
                    newInput = False
                    debug(c.DEBUG, "Old circle time recorded")
                    countingCircleTime = False
                else:
                    debug(c.DEBUG, "Now counting wait time")
                    countingWaitTime = True
                    timeClock.setTime(1)
            elif not (going):
                totalWaitTime = timeClock.getDelta(True)
                circleFile.write(" W{0} ".format(totalWaitTime))
        """DISPLAY SPRITE TOGGLE"""
        allSprites.update()
        if display_sprites == True:
            dieingSprites.draw(c.DISPLAYSURFACE)
            caughtSprite.draw(c.DISPLAYSURFACE)
            circSprites.draw(c.DISPLAYSURFACE)
            starSprites.draw(c.DISPLAYSURFACE)
            ringSprite.draw(c.DISPLAYSURFACE)
            if toggle_color_r:
                c.DISPLAYSURFACE.blit(r_letter, r_letter_rect)
            if toggle_color_g:
                c.DISPLAYSURFACE.blit(g_letter, g_letter_rect)
            if toggle_color_b:
                c.DISPLAYSURFACE.blit(b_letter, b_letter_rect)
            c.DISPLAYSURFACE.blit(box_img, box_rectR)
            c.DISPLAYSURFACE.blit(box_img, box_rectG)
            c.DISPLAYSURFACE.blit(box_img, box_rectB)
            c.DISPLAYSURFACE.blit(stageDisplay, stageDisplay_rect)
            scoreSprite.draw(c.DISPLAYSURFACE)
            c.DISPLAYSURFACE.blit(versionID, (0, 0))
        """DELAY"""
        c.FPSCLOCK.tick_busy_loop(c.FPS)
        """UPDATE"""
        pygame.display.flip()  # update()
    circleFile.close()
    if quitGame == 3:
        return

    debug(c.DEBUG, "Now building Stars")
    """Reinitializing Variables."""
    newStartTime = 0
    oldStartTime = 0
    stageDisplay = stock.creative["Star Building"]
    stageDisplay_rect = stageDisplay.get_rect()
    stageDisplay_rect.topright = (c.DISPLAY_W, 0)

    # --STAR MAKING Loop//--
    going = True
    pygame.mixer.music.play(0, 0)
    timeClock.playTimeSet()
    while going:
        counter += 1
        # Paint the background
        c.DISPLAYSURFACE.fill((0, 0, 0))
        c.DISPLAYSURFACE.blit(background, background_rect)
        if counter % 5 == 0:
            background, background_rect, rotAngle = \
            rotateBackground(c.CENTER, OGBackground, counter, rotAngle)
        """LOGGING output information: FPS, event info, AA, etc."""
        # for every 30 or FPS number of frames, print an average fps.
        fpsList.append(c.FPSCLOCK.get_fps())
        if counter == (c.FPS * 5):
            debug(c.DEBUG, ("Average FPS: {0}".format(mean(fpsList))))
            debug(c.DEBUG,
                  ("Current Score: {0}".format(scoreboard.scoreString)))
            counter = 0
            pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList)))
            fpsList = []

        #=======================================================================
        # """Get input to know wif we should put in a wait action"""
        # if total_input == 0:
        #     if not countingWaitTime:
        #         debug(c.DEBUG, "STARTING COUNT WAIT TIME")
        #         countingWaitTime = True
        #         timeClock.setTime(1)
        #=======================================================================

        if newStarAngle != '':
            oldStarAngle = newStarAngle
        """EVENT HANDLING INPUT"""
        # grab all the latest input
        latest_events = pygame.event.get()
        for event in latest_events:
            if event.type == QUIT:
                going = False
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                if c.DEBUG:
                    going = False
                    pygame.mixer.music.stop()
                else:
                    None
                    #===========================================================
                    # # have to time how long pause takes, for the wait.
                    # pauseStartTime = datetime.datetime.now()
                    # pause_selection = pause()
                    # pauseEndTime = datetime.datetime.now()
                    # pauseTotalTime = (pauseEndTime - pauseStartTime)
                    # starWaitStart = starWaitStart + pauseTotalTime
                    # circleWaitStart = circleWaitStart + pauseTotalTime
                    #===========================================================
            # --game-play events//--
            # Ring Spinning
            elif event.type == KEYDOWN and event.key == controls[5]:
                total_input += 1
                leftHold = True
                if upHold:
                    ring.spin('upleft')
                elif downHold:
                    ring.spin('downleft')
                else:
                    ring.spin('left')
            elif event.type == KEYUP and event.key == controls[5]:
                leftHold = False
                total_input += -1
            elif event.type == KEYDOWN and event.key == controls[6]:
                rightHold = True
                total_input += 1
                if upHold:
                    ring.spin('upright')
                elif downHold:
                    ring.spin('downright')
                else:
                    ring.spin('right')
            elif event.type == KEYUP and event.key == controls[6]:
                rightHold = False
                total_input += -1
            elif event.type == KEYDOWN and event.key == controls[3]:
                upHold = True
                total_input += 1
                if leftHold:
                    ring.spin('upleft')
                elif rightHold:
                    ring.spin('upright')
                else:
                    ring.spin('up')
            elif event.type == KEYUP and event.key == controls[3]:
                upHold = False
                total_input += -1
            elif event.type == KEYDOWN and event.key == controls[4]:
                downHold = True
                total_input += 1
                if leftHold:
                    ring.spin('downleft')
                elif rightHold:
                    ring.spin('downright')
                else:
                    ring.spin('down')
            elif event.type == KEYUP and event.key == controls[4]:
                downHold = False
                total_input += -1

            #====================================
            # --non-game-play events//--
            #====================================
            # if O is pressed, toggle context display -------TO BE REMOVED SOON
            elif event.type == KEYDOWN and event.key == K_o:
                if display_sprites == True:
                    display_sprites = False
                else:
                    display_sprites = True
            elif event.type == KEYDOWN and event.key == K_s:
                # add ten seconds to the total playtime.
                pygame.mixer.music.stop()
                newStartTime = (datetime.datetime.now() - timeClock.playTime
                                ).total_seconds() + 10 + oldStartTime
                # since the song is now 10 seconds ahead, we have to make sure there is a 10 second difference
                # in recording of actions.
                timeClock.timeIn = timeClock.timeIn - datetime.timedelta(
                    seconds=10)
                pygame.mixer.music.play(0, newStartTime)
                # need to record where we last began.
                oldStartTime = newStartTime
                debug(c.DEBUG, "new Start Time: %f" % newStartTime)
            # if P is pressed, pause game.
            elif event.type == KEYUP and event.key == controls[7]:
                None
                #===============================================================
                # # have to time how long pause takes, for the wait.
                # pauseStartTime = datetime.datetime.now()
                # pause_selection = pause()
                # pauseEndTime = datetime.datetime.now()
                # pauseTotalTime = (pauseEndTime - pauseStartTime)
                # starWaitStart = starWaitStart + pauseTotalTime
                # circleWaitStart = circleWaitStart + pauseTotalTime
                #===============================================================
            """LOGGING of inputs"""
            if event.type == KEYDOWN or event.type == KEYUP:
                debug(c.DEBUG,
                      (pygame.event.event_name(event.type), event.dict))
                debug(c.DEBUG, "NEWINPUT FOUND")
                newInput = True
                newStarAngle = ring.angle  # grab angle at time of recording.

        if pygame.event.peek(USEREVENT):
            pygame.mixer.music.stop()
            going = False

        if pause_selection == 3:
            going = False
            return

        #if an action has been input, test total_inputs:
        """Get input to know if we should put in a wait action"""
        if not (total_input == 0):
            if countingWaitTime:
                countingWaitTime = False
                totalWaitTime = timeClock.getDelta(True)
                debug(c.DEBUG, "Old wait time recorded")
                starFile.write(" W{0} ".format(totalWaitTime + totalStarTime))
                # if it isn't counting wait time, then it IS counting circleTime
                countingStarTime = True
                debug(c.DEBUG, "Now counting star time")
                timeClock.setTime(1)
                # newInput is set to false, since we already know its a new
                # input based on change in counting. newInput is only
                # relevant for when the circle color changes without a wait
                # in between.
                newInput = False
            else:
                if countingStarTime:
                    if newInput:
                        #first, we must store the old input.
                        totalStarTime = timeClock.getDelta(True)
                        starFile.write(" F{0},{1} ".format(
                            oldStarAngle, totalStarTime))
                        # a wait time must be introduced so that other circles
                        # don't spawn.
                        starFile.write(" W{0} ".format(totalStarTime))
                        newInput = False
                        debug(c.DEBUG, "Old star time recorded")
                        debug(c.DEBUG, "New star time recording")
                        #now we start the new Input recording..
                        timeClock.setTime(1)
        else:
            if not countingWaitTime:
                if countingStarTime:
                    totalStarTime = timeClock.getDelta(True)
                    starFile.write(" F{0},{1} ".format(oldStarAngle,
                                                       totalStarTime))
                    newInput = False
                    debug(c.DEBUG, "Old star time recorded")
                    countingStarTime = False
                else:
                    debug(c.DEBUG, "Now counting wait time")
                    countingWaitTime = True
                    timeClock.setTime(1)
            elif not (going):
                totalWaitTime = timeClock.getDelta(True)
                starFile.write(" W{0} ".format(totalWaitTime))
        """DISPLAY SPRITE TOGGLE"""
        allSprites.update()
        if display_sprites == True:
            dieingSprites.draw(c.DISPLAYSURFACE)
            caughtSprite.draw(c.DISPLAYSURFACE)
            circSprites.draw(c.DISPLAYSURFACE)
            starSprites.draw(c.DISPLAYSURFACE)
            ringSprite.draw(c.DISPLAYSURFACE)
            if toggle_color_r:
                c.DISPLAYSURFACE.blit(r_letter, r_letter_rect)
            if toggle_color_g:
                c.DISPLAYSURFACE.blit(g_letter, g_letter_rect)
            if toggle_color_b:
                c.DISPLAYSURFACE.blit(b_letter, b_letter_rect)
            c.DISPLAYSURFACE.blit(box_img, box_rectR)
            c.DISPLAYSURFACE.blit(box_img, box_rectG)
            c.DISPLAYSURFACE.blit(box_img, box_rectB)
            c.DISPLAYSURFACE.blit(stageDisplay, stageDisplay_rect)
            scoreSprite.draw(c.DISPLAYSURFACE)
            c.DISPLAYSURFACE.blit(versionID, (0, 0))
        """DELAY"""
        c.FPSCLOCK.tick_busy_loop(c.FPS)
        """UPDATE"""
        pygame.display.flip()  # update()
    starFile.close()
    if quitGame == 3:
        return

    debug(c.DEBUG, "Showing built commands")
    """REINITIALIZING"""

    stageDisplay = stock.creative["Build Testing"]
    stageDisplay_rect = stageDisplay.get_rect()
    stageDisplay_rect.topright = (c.DISPLAY_W, 0)

    genList = os.path.join(c.DATA_DIR, 'creative commands/genCommands.txt')
    circleList = os.path.join(c.DATA_DIR,
                              'creative commands/circleCommands.txt')
    starList = os.path.join(c.DATA_DIR, 'creative commands/starCommands.txt')
    genList, circleList, starList = commander(c, genList, circleList,
                                              starList)  # commander takes the
    #                     commands.txt and converts it into a formatted list.
    circleList, starList = iter(circleList), iter(starList)

    # take in the genList parameters now, before the level begins.
    for loop in range(len(genList)):
        setting = genList[loop]
        if setting[0] == 'B':
            # if the command is BPM, set the proper variables.
            pBox.cWait = setting[1]
            pBox.fWait = setting[2]
            pBox.cSpeed = setting[3]
            pBox.fSpeed = setting[4]
        elif setting[0] == 'J':
            startTime = setting[1]
        # change the general speed for circles/stars
        elif setting[0][0] == 'W':
            if setting[0] == 'WG':
                pBox.cWait = setting[1]
                pBox.fWait = setting[1]
            elif setting[0] == 'WC':
                pBox.cWait = setting[1]
            elif setting[0] == 'WF':
                pBox.fWait = setting[1]

    # --Main Game Loop//--
    going = True
    pygame.mixer.music.play(0, startTime)
    while going:
        counter += 1
        waitCounterCirc += 1
        waitCounterStar += 1
        # Paint the background
        c.DISPLAYSURFACE.fill((0, 0, 0))
        c.DISPLAYSURFACE.blit(background, background_rect)
        if counter % 5 == 0:
            background, background_rect, rotAngle = \
            rotateBackground(c.CENTER, OGBackground, counter, rotAngle)
        """LOGGING output information: FPS, event info, AA, etc."""
        # for every 30 or FPS number of frames, print an average fps.
        fpsList.append(c.FPSCLOCK.get_fps())
        if counter == (c.FPS * 5):
            debug(c.DEBUG, ("Average FPS: {0}".format(mean(fpsList))))
            debug(c.DEBUG,
                  ("Current Score: {0}".format(scoreboard.scoreString)))
            counter = 0
            pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList)))
            fpsList = []
        """TAKE ACTION COMMAND LIST"""
        # for every new action, if the wait was long enough, perform the action
        if not circleWaiting:
            if not finishedCircleActions:
                try:
                    circleAction = circleList.next()
                except:
                    finishedCircleActions = True
            # if the circleAction is to spawn a circle/star, gotta que it up.
            if circleAction[0] == 'C':
                circleWaiting = True
            # change the general speed for circles/stars
            elif circleAction[0] == 'CS':
                if circleAction[0] == 'CS':
                    pBox.cSpeed = circleAction[1]
            elif circleAction[0][0] == 'W':
                if circleAction[0] == 'W':
                    circleWaitStart = datetime.datetime.now()
                    circleWaiting = True
                    circleWaitMade = datetime.datetime.now(
                    )  # time started waiting
                elif circleAction[0] == 'WC':
                    pBox.cWait = circleAction[1]
            elif circleAction[0] == 'S':
                pygame.mixer.music.stop()
                going = False
        if circleWaiting:
            # All main actions have to wait before they can be performed,
            # so once an action is read, waiting becomes True, and we test to
            # see if the time passed is valid for the given wait time.
            if circleAction[0] == 'C':
                if waitCounterCirc >= pBox.cWait:
                    if circleAction[2] == '':
                        # if there is no given speed, then it's the global
                        # speed. . .
                        tempSpeed = pBox.cSpeed
                    else:
                        tempSpeed = circleAction[2]
                    tempColor = circleAction[1]
                    debug(c.DEBUG,
                          ("{0}'s speed: {1}".format(tempColor, tempSpeed)))
                    tempCirc = Circle(stock.campaign['Circle'], c.CENTER,
                                      tempSpeed, tempColor, pBox.layer)
                    tempCirc.add(circSprites, allSprites)
                    circMade = datetime.datetime.now()  #for debugging
                    pBox.layer += 1  #determines which get drawn on top
                    circleWaiting = False
                    waitCounterCirc = 0
            elif circleAction[0] == 'W':
                change = datetime.datetime.now() - circleWaitStart
                # if the action is to JUST wait x amount of time
                if change.total_seconds() >= circleAction[1] / c.FPS:
                    circleWaiting = False
                    totalWaitTime = datetime.datetime.now() - circleWaitMade
                    debug(c.DEBUG,
                          ("Wait Time: ", totalWaitTime.total_seconds()))
                    waitCounterCirc = 0

        if not starWaiting:
            if not finishedStarActions:
                try:
                    starAction = starList.next()
                except:
                    finishedStarActions = True
            if starAction[0] == 'F':
                starWaiting = True
            # change the general speed for circles/stars
            elif starAction[0] == 'FS':
                pBox.fSpeed = starAction[1]
            elif starAction[0][0] == 'W':
                if starAction[0] == 'W':
                    starWaitStart = datetime.datetime.now()
                    starWaiting = True
                    starWaitMade = datetime.datetime.now()
                elif starAction[0] == 'WF':
                    pBox.fWait = starAction[1]
            elif starAction[0] == 'S':
                pygame.mixer.music.stop()
                going = False
        if starWaiting:
            if starAction[0] == 'F':
                if waitCounterStar >= pBox.fWait:
                    if starAction[2] == '':
                        tempSpeed = pBox.fSpeed
                    else:
                        tempSpeed = starAction[2]
                    tempAngle = starAction[1]
                    images = (stock.campaign['Star Lit'],
                              stock.campaign['Star Unlit'])
                    tempStar = Star(images, c.CENTER, tempSpeed, tempAngle)
                    tempStar.add(starSprites, allSprites)
                    # no longer waiting, bring on the next starAction!
                    starWaiting = False
                    waitCounterStar = 0
            elif starAction[0] == 'W':
                change = datetime.datetime.now() - starWaitStart
                # if the starAction is to JUST wait x amount of time
                if change.total_seconds() >= starAction[1] / 30.0:
                    starWaiting = False
                    totalWaitTime = datetime.datetime.now() - starWaitMade
                    debug(c.DEBUG,
                          ("Wait Time: ", totalWaitTime.total_seconds()))
                    waitCounterStar = 0
                    # we must also set the wait for the next starAction to 0,
                    # or else the wait would be Wx + Wcircle/star.

        # test real quick to see if the song is over.
        if pygame.event.peek(USEREVENT):
            pygame.mixer.music.stop()
            going = False

        if pause_selection == 3:
            going = False
            return
        """EVENT HANDLING INPUT"""
        # grab all the latest input
        latest_events = pygame.event.get()
        for event in latest_events:
            if event.type == QUIT:
                going = False
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                if c.DEBUG:
                    going = False
                else:
                    # have to time how long pause takes, for the wait.
                    pauseStartTime = datetime.datetime.now()
                    pause_selection = pause()
                    pauseEndTime = datetime.datetime.now()
                    pauseTotalTime = (pauseEndTime - pauseStartTime)
                    starWaitStart = starWaitStart + pauseTotalTime
                    circleWaitStart = circleWaitStart + pauseTotalTime
            # --game-play events//--
            elif event.type == KEYDOWN and event.key == controls[0]:
                r = 255
                toggle_color_r = True
                total_input += 1
            elif event.type == KEYUP and event.key == controls[0]:
                r = 0
                toggle_color_r = False
                total_input += -1
            elif event.type == KEYDOWN and event.key == controls[1]:
                g = 255
                toggle_color_g = True
                total_input += 1
            elif event.type == KEYUP and event.key == controls[1]:
                g = 0
                toggle_color_g = False
                total_input += -1
            elif event.type == KEYDOWN and event.key == controls[2]:
                b = 255
                toggle_color_b = True
                total_input += 1
            elif event.type == KEYUP and event.key == controls[2]:
                b = 0
                toggle_color_b = False
                total_input += -1
            # Ring Spinning
            elif event.type == KEYDOWN and event.key == controls[5]:
                leftHold = True
                if upHold:
                    ring.spin('upleft')
                elif downHold:
                    ring.spin('downleft')
                else:
                    ring.spin('left')
            elif event.type == KEYUP and event.key == controls[5]:
                leftHold = False
            elif event.type == KEYDOWN and event.key == controls[6]:
                rightHold = True
                if upHold:
                    ring.spin('upright')
                elif downHold:
                    ring.spin('downright')
                else:
                    ring.spin('right')
            elif event.type == KEYUP and event.key == controls[6]:
                rightHold = False
            elif event.type == KEYDOWN and event.key == controls[3]:
                upHold = True
                if leftHold:
                    ring.spin('upleft')
                elif rightHold:
                    ring.spin('upright')
                else:
                    ring.spin('up')
            elif event.type == KEYUP and event.key == controls[3]:
                upHold = False
            elif event.type == KEYDOWN and event.key == controls[4]:
                downHold = True
                if leftHold:
                    ring.spin('downleft')
                elif rightHold:
                    ring.spin('downright')
                else:
                    ring.spin('down')
            elif event.type == KEYUP and event.key == controls[4]:
                downHold = False

            #====================================
            # --non-game-play events//--
            #====================================
            # if O is pressed, toggle context display -------TO BE REMOVED SOON
            elif event.type == KEYDOWN and event.key == K_o:
                if display_sprites == True:
                    display_sprites = False
                else:
                    display_sprites = True
            # if P is pressed, pause game.
            elif event.type == KEYUP and event.key == controls[7]:
                # have to time how long pause takes, for the wait.
                pauseStartTime = datetime.datetime.now()
                pause_selection = pause()
                pauseEndTime = datetime.datetime.now()
                pauseTotalTime = (pauseEndTime - pauseStartTime)
                starWaitStart = starWaitStart + pauseTotalTime
                circleWaitStart = circleWaitStart + pauseTotalTime
            """LOGGING of inputs"""
            if event.type == KEYDOWN or event.type == KEYUP:
                debug(c.DEBUG,
                      (pygame.event.event_name(event.type), event.dict))
        """CATCH CIRCLES MATCHING COLORS"""
        # catch matching circles!!
        for circle in circSprites.sprites():
            if circle.catchable:
                # catchable becomes true when the circle comes in contact
                # with the ring.
                debug(c.DEBUG, (circle.color, (r, g, b)))
                circle.add(caughtSprite)
                circle.remove(circSprites)
                circle.catch()
                totalCircTime = datetime.datetime.now() - circMade
        """REPEATED POINTS HOLDING COLORS CAUGHT"""
        # every .1 seconds should add or remove points based on accuracy
        if not (caughtSprite.sprite is None):
            for circle in caughtSprite.sprites():
                if circle.color == (r, g, b) and not (circle.dieing):
                    debug(c.DEBUG,
                          ("CIRCTIME: ", totalCircTime.total_seconds()))
                    #if the circle is more than 1 color, than we give bonus
                    if circle.color[0] + circle.color[1] + circle.color[
                            2] > 255:
                        scoreboard.addScore(40)
                    else:
                        scoreboard.addScore(20)
                    circle.remove(caughtSprite)
                    circle.add(dieingSprites)
                else:
                    circle.remove(caughtSprite)
                    circle.add(dieingSprites)
                    scoreboard.addScore(-10)

        # a circle begins in circSprites, then hits the ring, gets caught, and
        # goes into "caughtSprite" group. From there, it tries to match with
        # the user's input, then dies and goes into the "dieingCircs" group.
        # the purpose of the last group is just to have it animate the fading
        # or "dieing" sequence before disappearing.
        for circle in dieingSprites.sprites():
            circle.death()
        """DELETE FREE STARS SHOOTING"""
        for star in starSprites.sprites():

            if star.travDist >= (264 - star.speed) and not (star.shooting):
                # this tests the stars' distance, once it's close enough. . .
                if not ((ringSprite.sprite.angle) % 360
                        == (star.angleDeg) % 360):
                    debug(c.DEBUG, "Star Died at:")
                    debug(c.DEBUG, ("Ring Angle: ", ringSprite.sprite.angle))
                    debug(c.DEBUG, ("Star Angle: ", star.angleDeg))
                    star.kill()
                    scoreboard.addScore(-30)
                else:
                    debug(c.DEBUG, "Star Made it at:")
                    debug(c.DEBUG, ("Ring Angle: ", ringSprite.sprite.angle))
                    debug(c.DEBUG, ("Star Angle: ", star.angleDeg))
            if star.shooting:
                #                 debug(c.DEBUG, 'I AM SHOOTING1!')
                # if the star has gone off the screen in the x or y direction
                # kill it and add points!!
                if star.pos[0] > c.DISPLAY_W or star.pos[0] < 0:
                    star.kill()
                    #                     debug(c.DEBUG, 'KILLED A STAR')
                    scoreboard.addScore(50)
                elif star.pos[1] > c.DISPLAY_H or star.pos[1] < 0:
                    star.kill()
                    #                     debug(c.DEBUG, 'KILLED A STAR')
                    scoreboard.addScore(50)


#         debug(c.DEBUG, ('Stars #: {0}'.format(len(starSprites.sprites())))
        """DISPLAY SPRITE TOGGLE"""
        allSprites.update()
        if display_sprites == True:
            dieingSprites.draw(c.DISPLAYSURFACE)
            caughtSprite.draw(c.DISPLAYSURFACE)
            circSprites.draw(c.DISPLAYSURFACE)
            starSprites.draw(c.DISPLAYSURFACE)
            ringSprite.draw(c.DISPLAYSURFACE)
            if toggle_color_r:
                c.DISPLAYSURFACE.blit(r_letter, r_letter_rect)
            if toggle_color_g:
                c.DISPLAYSURFACE.blit(g_letter, g_letter_rect)
            if toggle_color_b:
                c.DISPLAYSURFACE.blit(b_letter, b_letter_rect)
            c.DISPLAYSURFACE.blit(box_img, box_rectR)
            c.DISPLAYSURFACE.blit(box_img, box_rectG)
            c.DISPLAYSURFACE.blit(box_img, box_rectB)
            c.DISPLAYSURFACE.blit(stageDisplay, stageDisplay_rect)
            scoreSprite.draw(c.DISPLAYSURFACE)
            c.DISPLAYSURFACE.blit(versionID, (0, 0))
        """DELAY"""
        c.FPSCLOCK.tick_busy_loop(c.FPS)
        """UPDATE"""
        pygame.display.flip()  # update()

    return
예제 #18
0
from kuju import Kuju
from ruut import Ruut
from kolmnurk import Kolmnurk
from ring import Ring

kuju = Kuju()
ruut = Ruut(2)
kolmnurk = Kolmnurk(5, 2)
ring = Ring(5)

print(kuju)
print(ruut)
print(kolmnurk)
print(ring)

print("kuju pindala " + str(kuju.pindala()))
print("ruut pindala " + str(ruut.pindala()))
print("kolmnurga pindala " + str(kolmnurk.pindala()))
print("ringi pindala " + str(ring.pindala()))
예제 #19
0
    
    def remove_entity(self, key): 
        self.entities.remove(key)
    
root = tk.Tk()

canvas = Canvas(root, width=500, height=500)
canvas.pack()

canvas.create_text(100, 100, anchor=W, font="Purisa",
                text="{}".format("asd"))
        

app = Application(canvas, master=root)

app.add_entity(Ring("#264348", app))

continuing_game = True
while continuing_game:
    root.update_idletasks()
    root.update()    
    time.sleep(1 / 15)
    try:
        app.update()
    except:
        print("Program terminated")
        continuing_game = False
    

    
    
예제 #20
0
from ring import Ring

inp = [int(l.strip()) for l in open('input.txt').read()]

inp.extend(range(max(inp) + 1, 10**6 + 1))

r = Ring(inp)
curr = r.find(inp[0])
inp_min = min(inp)

for i in range(10**7):
    tmp = r.remove(curr.nxt.val, 2)

    destination_val = curr.val - 1
    while not r.has(destination_val):
        destination_val -= 1
        if destination_val < inp_min:
            destination_val = r.get_max_val()
            break
    r.insert(destination_val, tmp)
    curr = curr.nxt

one = r.find(1)
print(one.nxt.val * one.nxt.nxt.val)
예제 #21
0
	def validateRings(self, ringContent):
		
		if self.dbwritten:
			self.webclient.sendMessage(WebSocketMessage.create("local","TTTS_GAME_OVER_MSGS","Rings verification cancelled, results already written to DB"))
			return
		
		ring = json.loads(ringContent)
		
		result = ring['result']
		sha256 = ring['sha256']
		ringsignature = ring['sign']
		
		testsha256 = hashlib.sha256(result).hexdigest()

		if testsha256 != sha256:
			print "ERROR: The hashes %s and %s are not equal"%(testsha256,sha256)
			return;
		
		result = json.loads(result.replace("'", "\"").replace("\n", "$"))
		
		p1 = result['player1']
		p2 = result['player2']
		s1 = result['spectator']
		
		result['player1'][1] = result['player1'][1].replace("$", "\n")
		result['player2'][1] = result['player2'][1].replace("$", "\n")
		result['spectator'][1] = result['spectator'][1].replace("$", "\n")
		
		p1key = RSA.importKey(result['player1'][1])
		p2key = RSA.importKey(result['player2'][1])
		s1key = RSA.importKey(result['spectator'][1])
		
		ringGroupStr = ringsignature.keys()[0]
		
		ringGroup = ringGroupStr.split(":")
		
		if ringGroup[0] == "player1":
			firstkey = p1key;
		elif ringGroup[0] == "player2":
			firstkey = p2key;
		elif ringGroup[0] == "spectator":
			firstkey = s1key
		else:
			print "Signature label unknown: " + ringGroup[1]
		
		if ringGroup[1] == "player1":
			secondkey = p1key;
		elif ringGroup[1] == "player2":
			secondkey = p2key;
		elif ringGroup[1] == "spectator":
			secondkey = s1key
		else:
			print "Signature label unknown: " + ringGroup[1]
			
		testring = Ring([firstkey, secondkey], 2048)
		
		verify = testring.verify(sha256, ringsignature[ringsignature.keys()[0]] )

		if (verify):
			added = False
			for (k, r) in self.validrings:
				if k == ringGroupStr:
					added = True
			
			if not added:
				ring['result'] = result;
				self.validrings.append((ringGroupStr, ring))
		else:
			print "Ring verification failed "
			self.webclient.sendMessage(WebSocketMessage.create("local","TTTS_GAME_OVER_MSGS","Verification of a ring failed"))
		
		verif = str(len(self.validrings)) + " rings verified"
		print verif
		self.webclient.sendMessage(WebSocketMessage.create("local","TTTS_GAME_OVER_MSGS", verif))
		self.storeifthree()
예제 #22
0
from threading import Thread
from node import Node
from ring import Ring
from config import bootstrap_ip, bootstrap_port, K_replicas, type_replicas
from utils import (
    insert_node_to_ring, get_data_from_next_node,
    get_node_hash_id, between, hashing, hexToInt,
    call_update_data, forward_replicas_to_next_node,
    delete_replicas_in_next_nodes
)
import requests
import argparse

app = Flask(__name__)

ring = Ring(bootstrap_ip, bootstrap_port)
node = Node()


@app.route('/insert', methods=['POST'])
def insert():
    """
    This is a route for ALL NODES.

    The client sends POST requests to this route so that new key-value pairs
    are inserted.

    In the case of "eventual consistency", the client gets a response to the
    request after the primary replica of the key-value pair is inserted. The
    other replicas are inserted by a thread, without blocking the response
    to the client.
예제 #23
0
파일: campaign.py 프로젝트: eliot2/RGB
def campaign(c, background, stock, store):

    debug(c.DEBUG, "ENTERING: campaign")
    load_song(c, "It's Melting.ogg")

    versionID = stock.getVersion()

    #    pygame.key.set_repeat(0, 0)

    allSprites = pygame.sprite.Group()
    ringSprite = pygame.sprite.GroupSingle()
    circSprites = pygame.sprite.LayeredUpdates()
    buttonSprites = pygame.sprite.Group()  # @UnusedVariable
    starSprites = pygame.sprite.LayeredUpdates()
    caughtSprite = pygame.sprite.GroupSingle()
    dieingSprites = pygame.sprite.GroupSingle()
    scoreSprite = pygame.sprite.GroupSingle()
    pBox = playBox()  # a jukebox for handling music settings.

    ring = Ring(c.CENTER, stock.campaign["Ring"], stock.campaign["Ring Glow"],
                c.FULLSCREEN)
    '''CREATE IMAGES'''
    ring.add(ringSprite, allSprites)
    scoreboard = Scoreboard(c.DISPLAY_W, c.DISPLAY_H)
    scoreboard.add(scoreSprite, allSprites)
    box_img = stock.campaign["RGB Light"]
    background_rect = background.get_rect()
    background_rect.center = c.CENTER
    OGBackground = background.copy()
    '''INSTANTIATING OTHER VARIABLES'''
    rotAngle = 0  # background rotation angle
    waitCounterCirc = 0
    waitCounterStar = 0
    circleWaitStart = 0
    circleWaitMade = 0
    starWaitStart = 0
    starWaitMade = 0
    finishedCircleActions = False
    finishedStarActions = False
    circleAction = '_'
    starAction = '_'
    counter = 0
    starWaiting = False
    circleWaiting = False
    pauseStartTime = None  #datetime variable
    pauseEndTime = None  #datetime variable
    r = 0
    g = 0
    b = 0
    pause_selection = 0
    gamePaused = False
    total_input = 0
    fpsList = []
    toggle_color_r = False
    toggle_color_g = False
    toggle_color_b = False
    display_sprites = True
    controls = c.CONTROL_LIST
    leftHold = False
    rightHold = False
    upHold = False
    downHold = False
    #quitGame = False  # if user returns a True from pause, we quit game, etc.
    startTime = 0
    genList = os.path.join(c.DATA_DIR, 'campaign_commands/genCommands.txt')
    circleList = os.path.join(c.DATA_DIR,
                              'campaign_commands/circleCommands.txt')
    starList = os.path.join(c.DATA_DIR, 'campaign_commands/starCommands.txt')
    genList, circleList, starList = commander(c, genList, circleList,
                                              starList)  # commander takes the
    #                     commands.txt and converts it into a formatted list.
    circleList, starList = iter(circleList), iter(starList)

    # take in the genList parameters now, before the level begins.
    for loop in range(len(genList)):
        setting = genList[loop]
        if setting[0] == 'B':
            # if the command is BPM, set the proper variables.
            pBox.cWait = setting[1]
            pBox.fWait = setting[2]
            pBox.cSpeed = setting[3]
            pBox.fSpeed = setting[4]
        elif setting[0] == 'J':
            __startTime = setting[1]  #different startTime, unused
        # change the general speed for circles/stars
        elif setting[0][0] == 'W':
            if setting[0] == 'WG':
                pBox.cWait = setting[1]
                pBox.fWait = setting[1]
            elif setting[0] == 'WC':
                pBox.cWait = setting[1]
            elif setting[0] == 'WF':
                pBox.fWait = setting[1]
    """BUTTON / SPRITE RENDERING"""
    r_letter = c.FONT_LARGE.render('R', True, c.RED)
    r_letter.scroll(2, 0)
    r_letter_rect = r_letter.get_rect()
    r_letter_rect.center = (c.CENTER_X - 50, (c.CENTER_Y * 2) - 20)
    box_rectR = r_letter_rect

    g_letter = c.FONT_LARGE.render('G', True, c.GREEN)
    g_letter.scroll(1, 0)
    g_letter_rect = g_letter.get_rect()
    g_letter_rect.center = (c.CENTER_X, (c.CENTER_Y * 2) - 20)
    box_rectG = g_letter_rect

    b_letter = c.FONT_LARGE.render('B', True, c.BLUE)
    b_letter.scroll(2, 0)
    b_letter_rect = b_letter.get_rect()
    b_letter_rect.center = (c.CENTER_X + 50, (c.CENTER_Y * 2) - 20)
    box_rectB = b_letter_rect

    debug(c.DEBUG, "Variable and object instantiating successful.")
    showSplashScreen(c, stock)
    songLength = store.music["Spicy Chips"].get_length()
    #pygame.mixer.music.set_endevent(USEREVENT)
    debug(c.DEBUG, "Song loading successful, main game loop about to begin.")
    # --Main Game Loop//--
    playing_campaign = True
    startTime = datetime.datetime.now()
    pygame.mixer.music.play()
    while playing_campaign:
        counter += 1
        waitCounterCirc += 1
        waitCounterStar += 1
        # Paint the background
        c.DISPLAYSURFACE.fill((0, 0, 0))
        #c.DISPLAYSURFACE.blit(background, background_rect)
        #if not c.FULLSCREEN:
        #   if counter%2 == 0:
        #      background, background_rect, rotAngle = \
        #     rotateBackground(c.CENTER, OGBackground, counter, rotAngle)
        """LOGGING output information: FPS, event info, AA, etc."""
        # for every 30 or FPS number of frames, print an average fps.
        fpsList.append(c.FPSCLOCK.get_fps())
        if counter == (c.FPS):
            AverageFPS = mean(fpsList)
            debug(c.DEBUG, ("Average FPS: {0}".format(AverageFPS)))
            debug(c.DEBUG,
                  ("Current Score: {0}".format(scoreboard.scoreString)))
            counter = 0
            pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList)))
            fpsList = []

            #===================================================================
            # this includes other things that i feel like should only be done
            # once a second, to save computation time, such as song ending check
            #===================================================================
            # test real quick to see if the song is over.
            deltaTime = (datetime.datetime.now() - startTime).total_seconds()
            if deltaTime > songLength:
                timeMessage = "SongTime: {0}, GameTIme: {1}".format(
                    songLength, deltaTime)
                debug(c.DEBUG, timeMessage)
                pygame.mixer.music.stop()
                playing_campaign = False
                debug(c.DEBUG, "MUSIC ENDED, CAMPAIGN SESSION OVER")
        """TAKE ACTION COMMAND LIST"""
        # for every new action, if the wait was long enough, perform the action
        if not circleWaiting:
            if not finishedCircleActions:
                try:
                    circleAction = circleList.next()
                except:
                    finishedCircleActions = True
            # if the circleAction is to spawn a circle/star, gotta que it up.
            if circleAction[0] == 'C':
                circleWaiting = True
            # change the general speed for circles/stars
            elif circleAction[0] == 'CS':
                if circleAction[0] == 'CS':
                    pBox.cSpeed = circleAction[1]
            elif circleAction[0][0] == 'W':
                if circleAction[0] == 'W':
                    circleWaitStart = datetime.datetime.now()
                    circleWaiting = True
                    circleWaitMade = datetime.datetime.now(
                    )  # time started waiting
                elif circleAction[0] == 'WC':
                    pBox.cWait = circleAction[1]
            elif circleAction[0] == 'S':
                pygame.mixer.music.stop()
                playing_campaign = False
        if circleWaiting:
            # All main actions have to wait before they can be performed,
            # so once an action is read, waiting becomes True, and we test to
            # see if the time passed is valid for the given wait time.
            if circleAction[0] == 'C':
                if waitCounterCirc >= pBox.cWait:
                    if circleAction[2] == '':
                        # if there is no given speed, then it's the global
                        # speed. . .
                        tempSpeed = pBox.cSpeed
                    else:
                        tempSpeed = circleAction[2]
                    tempColor = circleAction[1]
                    debug(c.DEBUG,
                          ("{0}'s speed: {1}".format(tempColor, tempSpeed)))
                    tempCirc = Circle(stock.campaign['Circle'], c.CENTER,
                                      tempSpeed, tempColor, pBox.layer)
                    tempCirc.add(circSprites, allSprites)
                    circMade = datetime.datetime.now()  #for debugging
                    pBox.layer += 1  #determines which get drawn on top
                    circleWaiting = False
                    waitCounterCirc = 0
            elif circleAction[0] == 'W':
                change = datetime.datetime.now() - circleWaitStart
                # if the action is to JUST wait x amount of time
                if change.total_seconds() >= circleAction[1] / c.FPS:
                    circleWaiting = False
                    totalWaitTime = datetime.datetime.now() - circleWaitMade
                    debug(c.DEBUG,
                          ("Wait Time: ", totalWaitTime.total_seconds()))
                    waitCounterCirc = 0

        if not starWaiting:
            if not finishedStarActions:
                try:
                    starAction = starList.next()
                except:
                    finishedStarActions = True
            if starAction[0] == 'F':
                starWaiting = True
            # change the general speed for circles/stars
            elif starAction[0] == 'FS':
                pBox.fSpeed = starAction[1]
            elif starAction[0][0] == 'W':
                if starAction[0] == 'W':
                    starWaitStart = datetime.datetime.now()
                    starWaiting = True
                    starWaitMade = datetime.datetime.now(
                    )  # for debug purposes
                elif starAction[0] == 'WF':
                    pBox.fWait = starAction[1]
            elif starAction[0] == 'S':
                pygame.mixer.music.stop()
                playing_campaign = False
        if starWaiting:
            if starAction[0] == 'F':
                if waitCounterStar >= pBox.fWait:
                    if starAction[2] == '':
                        tempSpeed = pBox.fSpeed
                    else:
                        tempSpeed = starAction[2]
                    tempAngle = starAction[1]
                    images = (stock.campaign['Star Lit'],
                              stock.campaign['Star Unlit'])
                    tempStar = Star(images, c.CENTER, tempSpeed, tempAngle)
                    tempStar.add(starSprites, allSprites)
                    # no longer waiting, bring on the next starAction!
                    starWaiting = False
                    waitCounterStar = 0
            elif starAction[0] == 'W':
                change = datetime.datetime.now() - starWaitStart
                # if the starAction is to JUST wait x amount of time
                if change.total_seconds() >= starAction[1] / c.FPS:
                    starWaiting = False
                    totalWaitTime = datetime.datetime.now() - starWaitMade
                    debug(c.DEBUG,
                          ("Wait Time: ", totalWaitTime.total_seconds()))
                    waitCounterStar = 0
                    # we must also set the wait for the next starAction to 0,
                    # or else the wait would be Wx + Wcircle/star.
        """EVENT HANDLING INPUT"""
        # grab all the latest input
        latest_events = pygame.event.get()
        for event in latest_events:
            if event.type == QUIT:
                playing_campaign = False
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                if c.DEBUG:
                    # quit game
                    playing_campaign = False
                    pygame.mixer.music.stop()
                else:
                    # have to time how long pause takes, for the wait.
                    pauseStartTime = datetime.datetime.now()
                    pause_selection = pause(c, stock, c.DISPLAYSURFACE)
                    pauseEndTime = datetime.datetime.now()
                    pauseTotalTime = (pauseEndTime - pauseStartTime)
                    starWaitStart += pauseTotalTime
                    circleWaitStart += pauseTotalTime
            # --game-play events//--
            elif event.type == KEYDOWN and event.key == controls[0]:
                r = 255
                toggle_color_r = True
                total_input += 1
                ring.glowColor((r, g, b))
            elif event.type == KEYUP and event.key == controls[0]:
                r = 0
                toggle_color_r = False
                total_input += -1
                ring.glowColor((r, g, b))
            elif event.type == KEYDOWN and event.key == controls[1]:
                g = 255
                toggle_color_g = True
                total_input += 1
                ring.glowColor((r, g, b))
            elif event.type == KEYUP and event.key == controls[1]:
                g = 0
                toggle_color_g = False
                total_input += -1
                ring.glowColor((r, g, b))
            elif event.type == KEYDOWN and event.key == controls[2]:
                b = 255
                toggle_color_b = True
                total_input += 1
                ring.glowColor((r, g, b))
            elif event.type == KEYUP and event.key == controls[2]:
                b = 0
                toggle_color_b = False
                total_input += -1
                ring.glowColor((r, g, b))
            # Ring Spinning
            elif event.type == KEYDOWN and event.key == controls[5]:
                leftHold = True
                if upHold:
                    ring.spin('upleft')
                elif downHold:
                    ring.spin('downleft')
                else:
                    ring.spin('left')
            elif event.type == KEYUP and event.key == controls[5]:
                leftHold = False
            elif event.type == KEYDOWN and event.key == controls[6]:
                rightHold = True
                if upHold:
                    ring.spin('upright')
                elif downHold:
                    ring.spin('downright')
                else:
                    ring.spin('right')
            elif event.type == KEYUP and event.key == controls[6]:
                rightHold = False
            elif event.type == KEYDOWN and event.key == controls[3]:
                upHold = True
                if leftHold:
                    ring.spin('upleft')
                elif rightHold:
                    ring.spin('upright')
                else:
                    ring.spin('up')
            elif event.type == KEYUP and event.key == controls[3]:
                upHold = False
            elif event.type == KEYDOWN and event.key == controls[4]:
                downHold = True
                if leftHold:
                    ring.spin('downleft')
                elif rightHold:
                    ring.spin('downright')
                else:
                    ring.spin('down')
            elif event.type == KEYUP and event.key == controls[4]:
                downHold = False

            #====================================
            # --non-game-play events//--
            #====================================
            # if O is pressed, toggle context display -------TO BE REMOVED SOON
            elif event.type == KEYDOWN and event.key == K_o:
                if display_sprites == True:
                    display_sprites = False
                else:
                    display_sprites = True
            # if P is pressed, pause game.
            elif event.type == KEYUP and event.key == controls[7]:
                gamePaused = True
            """LOGGING of inputs"""
            if event.type == KEYDOWN or event.type == KEYUP:
                debug(c.DEBUG,
                      (pygame.event.event_name(event.type), event.dict))

        if pause_selection == 3:
            pygame.mixer.music.stop()
            playing_campaign = False
            return
        """CATCH CIRCLES MATCHING COLORS"""
        # catch matching circles!!
        for circle in circSprites.sprites():
            if circle.catchable:
                # catchable becomes true when the circle comes in contact
                # with the ring.
                debug(c.DEBUG, (circle.color, (r, g, b)))
                circle.add(caughtSprite)
                circle.remove(circSprites)
                circle.catch()
                totalCircTime = datetime.datetime.now() - circMade
        """REPEATED POINTS HOLDING COLORS CAUGHT"""
        # every .1 seconds should add or remove points based on accuracy
        if not (caughtSprite.sprite is None):
            for circle in caughtSprite.sprites():
                if circle.color == (r, g, b) and not (circle.dieing):
                    debug(c.DEBUG,
                          ("CIRCTIME: ", totalCircTime.total_seconds()))
                    #if the circle is more than 1 color, than we give bonus
                    if circle.color[0] + circle.color[1] + circle.color[
                            2] > 255:
                        scoreboard.addScore(40)
                    else:
                        scoreboard.addScore(20)
                    circle.remove(caughtSprite)
                    circle.add(dieingSprites)
                else:
                    circle.remove(caughtSprite)
                    circle.add(dieingSprites)
                    scoreboard.addScore(-10)

        # a circle begins in circSprites, then hits the ring, gets caught, and
        # goes into "caughtSprite" group. From there, it tries to match with
        # the user's input, then dies and goes into the "dieingCircs" group.
        # the purpose of the last group is just to have it animate the fading
        # or "dieing" sequence before disappearing.
        for circle in dieingSprites.sprites():
            circle.death()
        """DELETE FREE STARS SHOOTING"""
        for star in starSprites.sprites():

            if star.travDist >= (264 - star.speed) and not (star.shooting):
                # this tests the stars' distance, once it's close enough. . .
                if not ((ringSprite.sprite.angle) % 360
                        == (star.angleDeg) % 360):
                    debug(c.DEBUG, "Star Died at:")
                    debug(c.DEBUG, ("Ring Angle: ", ringSprite.sprite.angle))
                    debug(c.DEBUG, ("Star Angle: ", star.angleDeg))
                    star.kill()
                    scoreboard.addScore(-30)
                else:
                    debug(c.DEBUG, "Star Made it at:")
                    debug(c.DEBUG, ("Ring Angle: ", ringSprite.sprite.angle))
                    debug(c.DEBUG, ("Star Angle: ", star.angleDeg))
            if star.shooting:
                #                 debug(c.DEBUG, 'I AM SHOOTING1!')
                # if the star has gone off the screen in the x or y direction
                # kill it and add points!!
                if star.pos[0] > c.DISPLAY_W or star.pos[0] < 0:
                    star.kill()
                    #                     debug(c.DEBUG, 'KILLED A STAR')
                    scoreboard.addScore(50)
                elif star.pos[1] > c.DISPLAY_H or star.pos[1] < 0:
                    star.kill()
                    #                     debug(c.DEBUG, 'KILLED A STAR')
                    scoreboard.addScore(50)


#         debug(c.DEBUG, ('Stars #: {0}'.format(len(starSprites.sprites())))
        """DISPLAY SPRITE TOGGLE"""
        allSprites.update()
        if display_sprites == True:
            dieingSprites.draw(c.DISPLAYSURFACE)
            caughtSprite.draw(c.DISPLAYSURFACE)
            circSprites.draw(c.DISPLAYSURFACE)
            starSprites.draw(c.DISPLAYSURFACE)
            ringSprite.draw(c.DISPLAYSURFACE)
            if toggle_color_r:
                c.DISPLAYSURFACE.blit(r_letter, r_letter_rect)
            if toggle_color_g:
                c.DISPLAYSURFACE.blit(g_letter, g_letter_rect)
            if toggle_color_b:
                c.DISPLAYSURFACE.blit(b_letter, b_letter_rect)
            c.DISPLAYSURFACE.blit(box_img, box_rectR)
            c.DISPLAYSURFACE.blit(box_img, box_rectG)
            c.DISPLAYSURFACE.blit(box_img, box_rectB)
            scoreSprite.draw(c.DISPLAYSURFACE)
            c.DISPLAYSURFACE.blit(versionID, (0, 0))
        """DELAY"""
        c.FPSCLOCK.tick_busy_loop(c.FPS)
        """UPDATE"""
        pygame.display.flip()  # update()

        # have to time how long pause takes, for the wait.
        if gamePaused:
            pauseStartTime = datetime.datetime.now()
            pause_selection = pause(c, stock, pygame.display.get_surface())
            pauseEndTime = datetime.datetime.now()
            pauseTotalTime = (pauseEndTime - pauseStartTime)
            starWaitStart += pauseTotalTime
            circleWaitStart += pauseTotalTime
            gamePaused = False

    return
예제 #24
0
                r.split_colors(Colors.RED,Colors.WARMWHITE, start)
            elif cols == 4:
                r.split_colors(Colors.BLUE,Colors.WARMWHITE, start)
            elif cols == 5:
                r.split_colors(Colors.RED,Colors.GREEN, start)
            elif cols == 6:
                r.split_colors(Colors.RED,Colors.BLUE, start)
            elif cols == 7:
                r.split_colors(Colors.RED,Colors.YELLOW, start)
            elif cols == 8:
                r.split_colors(Colors.BLUE,Colors.YELLOW, start)
            elif cols == 9:
                r.split_colors(Colors.ORANGE,Colors.GREEN, start)
            else:
                r.split_colors(Colors.BLUE,Colors.BLACK, start)
            r.set_brightness(get_value(pot1)*.7)
        elif mode == 4:
            r.fill(Colors.wheel(get_byte_value(pot2)))
            r.set_brightness(get_value(pot1)*.7)
        elif mode == 5:
            col1 = Colors.wheel(get_byte_value(pot2))
            col2 = Colors.wheel(get_byte_value(pot3))
            r.blend_colors(col1,col2)
            r.set_brightness(get_value(pot1)*.7)
        else:
            r.fill(Colors.BLACK)

if __name__ == '__main__':
    r = Ring(60)
    #ready()
    main()
예제 #25
0
 def set_rings(self, number_of_rings):
     RING_RANGE = range(number_of_rings + 1, 1, -1)
     pinOne = self.pins[0]
     for ring_size in RING_RANGE:
         ring = Ring(ring_size)
         pinOne.insert_ring(ring)
예제 #26
0
def test():
    a = Ring(4)
    a.append([1, 2])
    assert np.all(a.raw == [1, 2, 0, 0])
    a.append([3, 4])
    assert np.all(a.raw == [1, 2, 3, 4])
    a.append([5])
    assert np.all(a.raw == [5, 2, 3, 4])
    a.append([6, 7])
    a.append([8, 9])
    assert np.all(a.raw == [9, 6, 7, 8])
    a.append([10, 11])
    assert np.all(a.raw == [9, 10, 11, 8])

    # test getitem
    a = Ring(4)
    a.append([0, 1, 2, 3])
    assert a[0] == 3
    assert a[-1] == 2
    a.append([4])
    assert (np.all(a.raw == [4, 1, 2, 3]))
    assert (a[0] == 4)
    assert (a[-1] == 3)
    assert (np.all(a.recent(0) == []))
    assert (np.all(a.recent(1) == [4]))
    a.append([5])
    assert (np.all(a.recent(2) == [4, 5]))
    # test wrap around
    assert (np.all(a.recent(3) == [3, 4, 5]))

    # test RingPosition
    a = Ring(8)
    p = a.create_tap()

    assert p.valid_buffer_length == 1
    a.append(np.arange(4))
    assert p.valid_buffer_length == 5
    p.advance(1)
    assert p.valid_buffer_length == 4
    assert p.index == 0

    assert np.all(p.get_samples(4) == [0, 1, 2, 3])
    p.advance(2)
    assert np.all(p.get_samples(2) == [2, 3])
    a.append([4, 5, 6, 7, 8])

    p.advance(4)

    assert np.all(p.get_samples(2) == [6, 7])
    # test wraping
    assert np.all(p.get_samples(3) == [6, 7, 8])
    p.advance(2)
    assert (p.valid)
    assert (a.raw[p.index] == 8)

    # Ensure that we throw when breaking a ring pointer
    a = Ring(8)
    a.append(np.arange(8))
    p = a.create_tap()
    assert (p.get_samples(1)[0] == 7)
    # pointing to the last item in the sample
    a.append(np.arange(7))
    try:
        a.append([99])
    except RingPointerWarning as e:
        pass
    assert p.valid is False

    a = Ring(8)
    p = a.create_tap()
    try:
        p.advance(2)
    except RingPointerWarning as e:
        pass
    assert p.valid is False
    return a, p

    # test rewinding pointer
    a = Ring(5)
    a.append(np.arange(2))
    assert a.pointer == 2
    a.rewind(1)
    assert a.p == 1
    a.rewind(3)
    assert a.p == 3
예제 #27
0
 def __init__(self, x, y, t, sp):
     self.ovoid = Egg(x, y, t, sp)
     self.circle = Ring()
     self.circle.start(x, y - sp / 2)
예제 #28
0
def identify_rings(mol):
    """
	Identify the rings in the system with Zamora's SSSR ring perception
	algorithm. 
	TODO: Further Documentation.
	"""
    def zamora_connectivity(mol):
        """
		Zamora defines a connectivity index for each atom in a 
		molecular graph. This numerical index determines how crowded or
		connected each atom is, allowing us to start later processing
		with more central atoms. 
		"""
        # Mapping of number of neighbors to connectivity values
        # This is a huristic value assigned to each atom.
        # TODO: Valency > 4 is not handled by Zamora
        ki_values = {
            0: 0,
            1: 0,
            2: 1,
            3: 8,
            4: 64,
        }

        # Calculate each atom's connectivity
        ki = [0 for x in range(mol.size)]
        for atom in range(mol.size):
            n = len(mol.alphaAtoms[atom])
            ki[atom] = ki_values[n]

        # Now calculate each atom's neighborhood.
        # The congestedness of an atom's neighborhood yeilds higher
        # values for li.
        li = [0 for x in range(mol.size)]
        for atom in range(mol.size):
            ksum = 0
            for neighbor in mol.alphaAtoms[atom]:
                ksum += ki[neighbor]

            li[atom] = ksum  # Final heuristic score is the sum of ki and li.

        # However, ki is given an additional weight.
        ci = [0 for x in range(mol.size)]
        for atom in range(mol.size):
            ci[atom] = 64 * ki[atom] + li[atom]

        return ci

    def phase1(mol):
        """
		Phase One processing takes care of "Type One" ring systems, as
		well as ring systems that can be reduced to Type One. 
		TODO: Documentation.
		"""

        # Connectivity index for each atom
        connectivity = zamora_connectivity(mol)

        # List of unused atom labels. (Elements deleted as used.)
        unusedAtoms = range(mol.size)  # XXX: May not be best approach.

        rings = []
        while len(unusedAtoms) > 0:
            # Find the unused atom with the highest connectivity, then the
            # smallest (and best) ring that contains it.
            # TODO/FIXME/XXX: Absolutely need to implement Zamora's heuristics
            startAtom = connectivity.index(max(connectivity))
            ring = _find_smallest_ring(mol, startAtom)

            if len(ring) < 1:
                # Atom is not in a ring system.
                unusedAtoms.remove(startAtom)
                connectivity[startAtom] = -1
                continue

            rings.append(ring)

            # Remove used atoms.
            unusedAtoms = filter(lambda x: x not in ring, unusedAtoms)

            # Negate connectivity for used atoms.
            for i in range(len(connectivity)):
                if i not in unusedAtoms:
                    connectivity[i] = -1

        return rings

    # TODO: Implement phase two and three.
    rings = phase1(mol)

    # Return Ring objects.
    for i in range(len(rings)):
        rings[i] = Ring(rings[i])

    return tuple(rings)
예제 #29
0
def creative(c, background):

    debug(c.DEBUG, "ENTERING: creative")
    
    # display the version ID
    font_renderObj = c.FONT_SMALL.render(c.VERSION, False, c.BLACK, c.WHITE)
    versionID_SurfaceObj = font_renderObj
    versionID_RectObj = versionID_SurfaceObj.get_rect()
    versionID_RectObj.topleft = (0, 0)

#    pygame.key.set_repeat(0, 0)

    allSprites = pygame.sprite.Group()
    ringSprite = pygame.sprite.GroupSingle()
    scoreSprite = pygame.sprite.GroupSingle()
    '''CREATE IMAGES'''
    ring = Ring(c, c.CENTER)
    ring.add(ringSprite, allSprites)
    scoreboard = Scoreboard(c.DISPLAY_W, c.DISPLAY_H)
    scoreboard.add(scoreSprite, allSprites)
    box_img, _box_rect = load_image(c, 'letter_box.png')
    background_rect = background.get_rect()
    background_rect.center = c.CENTER
    OGBackground = background.copy()
    logging = False

    '''INSTANTIATING OTHER VARIABLES'''
    dataDir = os.path.join(c.DATA_DIR, 'newCommands.txt')
    frameCount = 0      # tracks the number of frames passed.
    bgRotAngle = 0      # background rotation angle
    logFile = file
    testFrame = 0
    newAction = True
    r = 0
    g = 0
    b = 0
    paused = False
    fpsList = []
    toggle_color_r = False
    toggle_color_g = False
    toggle_color_b = False
    display_sprites = True
    controls = c.CONTROL_LIST
    leftHold = False
    rightHold = False
    upHold = False
    downHold = False
    quitGame = False  # if user returns a True from pause, we quit game, etc.
    firstAction = True

    """BUTTON / SPRITE RENDERING"""
    r_letter = c.FONT_LARGE.render('R', True, c.RED)
    r_letter.scroll(2, 0)
    r_letter_rect = r_letter.get_rect()
    r_letter_rect.center = (c.CENTER_X - 50, (c.CENTER_Y * 2) - 20)
    box_rectR = r_letter_rect

    g_letter = c.FONT_LARGE.render('G', True, c.GREEN)
    g_letter.scroll(1, 0)
    g_letter_rect = g_letter.get_rect()
    g_letter_rect.center = (c.CENTER_X, (c.CENTER_Y * 2) - 20)
    box_rectG = g_letter_rect

    b_letter = c.FONT_LARGE.render('B', True, c.BLUE)
    b_letter.scroll(2, 0)
    b_letter_rect = b_letter.get_rect()
    b_letter_rect.center = (c.CENTER_X + 50, (c.CENTER_Y * 2) - 20)
    box_rectB = b_letter_rect




    # throw down splash screen before beginning
    splashInfo, splashInfo_rect = load_image(c, 'splashInfo.png')
    # adjusting image cuz i can't make images.
    splashInfo_rect.center = (c.CENTER_X - 50, c.CENTER_Y)

    # fade info in and out
    fade = 0
    pgext.color.setAlpha(splashInfo, fade, 1)
    pygame.event.clear()
    # fade in
    inInfoScreen = True
    for fade in range(255):
        c.DISPLAYSURFACE.fill((0, 0, 0))
        c.DISPLAYSURFACE.blit(splashInfo, splashInfo_rect)
        pgext.color.setAlpha(splashInfo, fade, 1)
        c.DISPLAYSURFACE.blit(versionID_SurfaceObj, versionID_RectObj)
        pygame.display.flip()
        if pygame.event.poll().type != NOEVENT:
            inInfoScreen = False
            break
    # if the info is still being read/no button pressed, just wait.
    while inInfoScreen:
        if pygame.event.poll().type != NOEVENT:
            inInfoScreen = False
    fade = 255
    pgext.color.setAlpha(splashInfo, fade, 1)
    load_song(c, "It's Melting.ogg")  # stops other music from playing too
    cmdFile = open(dataDir, 'w')
    cmdFile.write("BPM60 Play:")

    # --Main Game Loop//--
    going = True
    while going:
        

        # Paint the background
        c.DISPLAYSURFACE.fill((0,0,0))
        c.DISPLAYSURFACE.blit(background, background_rect)
        """ROTATION TESTING"""
        # rotate the background, but only 15 times/second, not 30.
        # if the frame rate is 30/sec, then rotate when its an odd frame.
        if frameCount%3 == 0:
            bgRotAngle += .03
            background = pygame.transform.rotozoom(OGBackground, bgRotAngle%360 , 1)
            background_rect = background.get_rect()
            background_rect.center = c.CENTER
        frameCount += 1


        """LOGGING output information: FPS, event info, AA, etc."""
        # for every 30 or FPS number of frames, print an average fps.
        fpsList.append(c.FPSCLOCK.get_fps())
        if testFrame == c.FPS:
            debug(c.DEBUG, ("Average FPS: {0}".format(mean(fpsList))))
            debug(c.DEBUG, ("Current Score: {0}".format(scoreboard.scoreString)))
            testFrame = 0
            pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList)))
            fpsList = []

        """Start the Song!"""
        beginning = True
        if beginning:
            pygame.mixer.music.play()
            beginning = False
            # record the beginning, since no action causes a new time recording
            counter.setTime(1)
        

        """EVENT HANDLING INPUT"""
        # grab all the latest input
        latest_events = pygame.event.get()
        for event in latest_events:
            if (event.type == KEYDOWN or event.type == KEYUP) and \
                (event.key in controls) and firstAction:
                # this is the very first action, and its a correct input,
                # we put a Wait action in, since there was nothing before the 
                # first action to tell us otherwise.
                cmdFile.write(' W%d'%counter.getDelta(True))
                # so we write how long it took to do the action above
                counter.setTime(1)
                # if any button is pressed, a change must be written in. . .
                firstAction = False
            if event.type == QUIT:
                going = False
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                if c.DEBUG:
                    going = False
                else:
                    paused = True
            # --game-play events//--
            elif event.type == KEYDOWN and event.key == controls[0]:
                # default key is R
                r = 255
                toggle_color_r = True
            elif event.type == KEYUP and event.key == controls[0]:
                r = 0
                toggle_color_r = False
            elif event.type == KEYDOWN and event.key == controls[1]:
                # default key is G
                g = 255
                toggle_color_g = True
            elif event.type == KEYUP and event.key == controls[1]:
                g = 0
                toggle_color_g = False
            elif event.type == KEYDOWN and event.key == controls[2]:
                # default key is B
                b = 255
                toggle_color_b = True
            elif event.type == KEYUP and event.key == controls[2]:
                b = 0
                toggle_color_b = False
            # Ring Spinning
            elif event.type == KEYDOWN and event.key == controls[5]:
                leftHold = True
                if upHold:
                    ring.spin('upleft')
                elif downHold:
                    ring.spin('downleft')
                else:
                    ring.spin('left')
            elif event.type == KEYUP and event.key == controls[5]:
                leftHold = False
            elif event.type == KEYDOWN and event.key == controls[6]:
                rightHold = True
                if upHold:
                    ring.spin('upright')
                elif downHold:
                    ring.spin('downright')
                else:
                    ring.spin('right')
            elif event.type == KEYUP and event.key == controls[6]:
                rightHold = False
            elif event.type == KEYDOWN and event.key == controls[3]:
                upHold = True
                if leftHold:
                    ring.spin('upleft')
                elif rightHold:
                    ring.spin('upright')
                else:
                    ring.spin('up')
            elif event.type == KEYUP and event.key == controls[3]:
                upHold = False
            elif event.type == KEYDOWN and event.key == controls[4]:
                downHold = True
                if leftHold:
                    ring.spin('downleft')
                elif rightHold:
                    ring.spin('downright')
                else:
                    ring.spin('down')
            elif event.type == KEYUP and event.key == controls[4]:
                downHold = False

            #====================================
            # --non-game-play events//--
            #====================================
            # if O is pressed, toggle context display -------TO BE REMOVED SOON
            elif event.type == KEYDOWN and event.key == K_o:
                if display_sprites == True:
                    display_sprites = False
                else:
                    display_sprites = True
            # if P is pressed, pause game.
            elif event.type == KEYUP and event.key == controls[7]:
                paused = True

            """LOGGING of inputs"""
            if event.type == KEYDOWN or event.type == KEYUP:
                debug(c.DEBUG, event.dict)

        """DISPLAY SPRITE TOGGLE"""
        allSprites.update()
        if display_sprites == True:
            if toggle_color_r:
                c.DISPLAYSURFACE.blit(r_letter, r_letter_rect)
            if toggle_color_g:
                c.DISPLAYSURFACE.blit(g_letter, g_letter_rect)
            if toggle_color_b:
                c.DISPLAYSURFACE.blit(b_letter, b_letter_rect)
            c.DISPLAYSURFACE.blit(box_img, box_rectR)
            c.DISPLAYSURFACE.blit(box_img, box_rectG)
            c.DISPLAYSURFACE.blit(box_img, box_rectB)
            scoreSprite.draw(c.DISPLAYSURFACE)
            c.DISPLAYSURFACE.blit(versionID_SurfaceObj, versionID_RectObj)

        """DELAY"""
        c.FPSCLOCK.tick_busy_loop(c.FPS)

        """PAUSE UNPAUSE"""
        if paused:
            pygame.mixer.music.pause()
            quitGame = pauseScreen(c)
            if quitGame == 3:
                going = False
            pygame.mixer.music.unpause()
            paused = False

        """UPDATE"""
        pygame.display.flip()  # update()

    try:
        cmdFile.close()
    except Exception:
        debug(c.DEBUG, "File never opened")
    return
예제 #30
0
from neuron import h
from neuron.units import ms, mV
import matplotlib.pyplot as plt
from ring import Ring

ring = Ring()

pc = h.ParallelContext()
pc.set_maxstep(10 * ms)

t = h.Vector().record(h._ref_t)
h.finitialize(-65 * mV)
pc.psolve(100 * ms)

# send all spike time data to node 0
local_data = {cell._gid: list(cell.spike_times) for cell in ring.cells}
all_data = pc.py_alltoall([local_data] + [None] * (pc.nhost() - 1))

if pc.id() == 0:
    # combine the data from the various processes
    data = {}
    for process_data in all_data:
        data.update(process_data)
    # plot it
    plt.figure()
    for i, spike_times in data.items():
        plt.vlines(spike_times, i + 0.5, i + 1.5)
    plt.show()

pc.barrier()
pc.done()