示例#1
0
    def main(self):
        self.clear_screen()  #erase all objects from screen
        self.ship.update()

        for enemy in self.enemies:  #for all the enemies on the screen
            enemy.update()

        finished = []  #list of shots to delete

        for i, shot in enumerate(self.shots):  #for all shots on screen
            if not shot.update():  #if shot no longer on screen
                finished.append(i)  #add to list of shots to delete
            shot.hit_any_enemy(
                self.enemies
            )  #check if it has hit any of the remaining enemies

        for i in reversed(finished):  #for shots off screen
            del self.shots[i]  #delete shots

        if not self.enemies and not self.scheduled_enemies:  #if all enemies dead and no enemies planned to recreate
            self.scheduled_enemies = True  #planning to repopulate enemies
            timer.set_timeout(self.populate_enemies,
                              2000)  #repopulate enemies after 2 seconds

        self.display_score()

        if not self.game_over_marker:  #if game is still going
            timer.set_timeout(self.main, 30)  #update game in 3/100 of a second
        else:
            self.display_game_over()  #otherwise display game over message
示例#2
0
def __timer__():
    global CANVAS
    global NOANSWER

    _started = time.time() # Хоть как-то минимизируем дрифт... Плохо всё...
    # print (CANVAS)
    # print (NOANSWER)

    for operator_id, canvas in CANVAS.items():
        # calls = DOM.getElementById(operator_id).getElementsByClassName('call-brick')
        if canvas.to_delete:
            DOM.getElementById('content').removeChild(DOM.getElementById(operator_id))
            del CANVAS[operator_id]
        else:
            canvas.__timer__()

    for caller_id, canvas in NOANSWER.items():
        # calls = DOM.getElementById(caller_id).getElementsByClassName('noanswered-brick')
        if canvas.to_delete:
            DOM.getElementById('noanswered_calls').removeChild(DOM.getElementById(caller_id))
            del NOANSWER[caller_id]
        else:
            canvas.__timer__()

    timer.set_timeout(__timer__, 1000-(time.time()-_started)*1000)
示例#3
0
def create_token(token, *_):
    """
    Called when a new token is created
    :param token: Token-like dictionary
    """
    real_token = window.canvas.tokens.get(token._id)  # noqa
    timer.set_timeout(paint_dmg_token, 2000, real_token)
示例#4
0
def reset(clear_console=True):
    return
    try:
        PynodeCoreGlobals.GLOBAL_USER_ID = 0
        if clear_console: window.writeOutput("", False)
        pynode_graphlib.graph._reset()
        window.js_clear()
        if PynodeCoreGlobals.event_timer is not None:
            timer.clear_timeout(PynodeCoreGlobals.event_timer)
        if PynodeCoreGlobals.update_timer is not None:
            timer.clear_timeout(PynodeCoreGlobals.update_timer)
        PynodeCoreGlobals.event_queue = [EventPause(100)]
        PynodeCoreGlobals.fix_layout = True
        PynodeCoreGlobals.did_fix_layout = False
        PynodeCoreGlobals.did_update_layout = False
        PynodeCoreGlobals.has_ended = False
        PynodeCoreGlobals.delay_type = {}
        PynodeCoreGlobals.positioning_counter = 0
        PynodeCoreGlobals.error = ""
        PynodeCoreGlobals.click_listener_func = {"f": None}
        window.set_layout_type()
        window.registerClickListener(node_click)
        window.clickListenerFunc = None
    except:
        timer.set_timeout(reset, 20)
示例#5
0
def update_account(accs):
    _dict = {}
    _dict['action'] = EVENT_CTPUPDATE
    _dict['data'] = accs
    _rs = json.dumps(_dict)
    ws.send(_rs)
    timer.set_timeout(reload,1000)
示例#6
0
def update_account(accs):
    _dict = {}
    _dict['action'] = EVENT_CTPUPDATE
    _dict['data'] = accs
    _rs = json.dumps(_dict)
    ws.send(_rs)
    timer.set_timeout(reload,1000)
示例#7
0
	def displayLayout(self):
		'''Go through the cards on the board object and lay them
		out on the canvas.  Translation of the Card object to its
		corresponding CardImg object is done through the given
		card2ImgDict dictionary.
		'''

		# return the closure so it can be called with no parameters
		# from set_timeout() below.
		def displayCard(cardimg, x, y):
			def inner():
				cardimg.drawOnCanvas(x, y)
			return inner

		delay_time = 100
		for ridx in range(4):
			for cidx in range(13):
				card = self._board.getCardAt(ridx, cidx)
				if card is None:
					continue

				cardimg = self._card2ImgDict[id(card)]
				x = CARD_PADDING + cidx * CARD_AREA_WIDTH
				y = CARD_PADDING + ridx * CARD_AREA_HEIGHT
				timer.set_timeout(displayCard(cardimg, x, y), delay_time)
				delay_time += 20
示例#8
0
	def nextRound(self, ev):
		'''Callback for when the user clicks the "Next Round" button.
		Increment the round number counter;
		Remove the cards from the board that are not in the correct place;
		Add those cards, and the aces, back to the deck; shuffle it;
		Update the display to show the good cards only, for 1 second;
		Register nextRoundContined() to be called.
		'''

		self.disableNewGameButton()

		# No cards placed yet in this round
		self._cardsPlacedPerRound.append(0)
		self._roundNum += 1
		self.updateRoundNum()
		discarded = self._board.removeIncorrectCards()
		self._deck.addCards(discarded)
		# Add the aces back to the deck.
		for card in self._removedAces:
			self._deck.addCard(card)
		self._deck.shuffle()

		# display the board with only "good cards" for 1 second.
		for card in discarded:
			cardimg = self._card2ImgDict[id(card)]
			cardimg.erase()
		self.updateScore()

		self.setStatus("Cards placed this round: " +
					   str(self._cardsPlacedPerRound[self._roundNum - 1]))

		timer.set_timeout(self.nextRoundContinued, 1000)
示例#9
0
def draw_chunks(data, date_jul, marker_opts, marker_layer, mkl, marker_dated):
    todo = data.copy()
    chunksize = 200
    chunkdelay = 100

    mkl = leaflet.LayerGroup.new()

    def dotask():
        items = todo[0:chunksize]

        for spot in items:
            m = draw_one_marker(spot)
            m.addTo(mkl)

        del todo[0:chunksize]

        if len(todo) > 0:
            timer.set_timeout(dotask, chunkdelay)
            load_percent = 1 - (len(todo) / len(data))
            load_str = "{:.1%}".format(load_percent)
            #document['progress-bar-v'].style.width = load_str
            document['hotspot-info'].text = load_str
        else:
            enable_input(True)
            document['hotspot-info'].text = ''

    timer.set_timeout(dotask, chunkdelay)
    mkl.addTo(marker_layer)
    marker_layer.addTo(lmap)
示例#10
0
文件: dashboard.py 项目: Enforcer/PAW
def hide_modal(event=None):
    document['modal-mask'].style.opacity = 0.0
    document['modal'].style.opacity = 0.0
    def _hide():
        document['modal-mask'].style.display = 'none'
        document['modal'].style.display = 'none'
    timer.set_timeout(_hide, 500)
示例#11
0
def change(event):
    global canMouse
    canMouse = False
    
    global zz,qq,boxList,generator,doubles
    zz=kl.KillerSudoku(boardSize)
    try:
        for (n,idList) in boxList:
            print ( "(",n,",",list(map(id2tuple,idList)),"),")
        zz.load([ (n,list(map(id2tuple,idList)))  for (n,idList) in boxList])
        generator=kl.doit(zz)
    except Exception as e:
        myAlert(" ".join(map(str,e.args)) )
        canMouse=True
        return
    
    document["progress"].text=""

    for s in gridDict.keys():
        b=gridDict[s]
        itm=document[b.id]
        itm.text=""
    
    document["button1"].textContent = "thinking"
    
    timer.set_timeout(ongoing,0)
示例#12
0
 def turno(self):
     carta_corrente = self.baralho.descarta()
     if (not carta_corrente) or (carta_corrente in self.salas):
         carta_corrente.entra(self.labirinto)
         timer.clear_interval(self.interval)
         if self.rodada_corrente < 5:
             timer.set_timeout(self.rodada, 2000)
         return False
     jogadores_saindo = []
     self.apresenta(carta_corrente)
     ativos = len(self.jogadores_ativos)
     for jogador in self.jogadores_ativos:
         for carta in self.salas:
             carta.premia(jogador, ativos)
     self.atualiza()
     for jogador in self.jogadores_ativos:
         if jogador.decide() == DESISTE:
             self.jogadores_ativos.remove(jogador)
             jogadores_saindo.append(jogador)
     carta_corrente.atualiza_saldo(ativos)
     carta_corrente.divide(jogadores_saindo, self.salas)
     if not self.jogadores_ativos:
         timer.clear_interval(self.interval)
         if self.rodada_corrente < 5:
             timer.set_timeout(self.rodada, 2000)
示例#13
0
def victory():
    t = Text('Victory')
    timer.set_timeout(timeout=3)
    for i in buttons:
        i.color = color.dark_gray
        i.text = ''
    t.text = ''
示例#14
0
    def show(self, frame):
        """"""
        self.stimuli = False

        if frame == 'primary':
            a1, a2 = 'expand', 'contract'
            w1, w2 = '85%', '15%'
            for item in self.secondary_area.select(f'.secondary'):
                item.style = {'opacity': 0.2}
            for item in self.primary_area.select(f'.primary'):
                item.style = {'opacity': 1}

        elif frame == 'secondary':
            a2, a1 = 'expand', 'contract'
            w2, w1 = '85%', '15%'

            for item in self.secondary_area.select(f'.secondary'):
                item.style = {'opacity': 1}
            for item in self.primary_area.select(f'.primary'):
                item.style = {'opacity': 0.2}

        self.frame = frame
        self.primary_area.class_name = f'area primary-area {a1}'
        self.secondary_area.class_name = f'area secondary-area {a2}'
        self.primary_area.style = {'width': w1}
        self.secondary_area.style = {'width': w2}

        timer.set_timeout(lambda: setattr(self, 'stimuli', True), 2000)
示例#15
0
    def main(self):
        self.clear_screen()
        self.ship.update()

        for enemy in self.enemies:
            enemy.update()

        finished = []

        for i, shot in enumerate(self.shots):
            if not shot.update():
                finished.append(i)
            shot.hit_any_enemy(self.enemies)

        for i in reversed(finished):
            del self.shots[i]

        if not self.enemies and not self.scheduled_enemies:
            self.scheduled_enemies = True
            timer.set_timeout(self.populate_enemies, 2000)

        self.display_score()

        if not self.game_over_marker:
            timer.set_timeout(self.main, 30)
        else:
            self.display_game_over()
示例#16
0
 def sai(*_):
     cat.entra(cena)
     cat.x = cart.x + 10
     cat.y = cart.y + 20
     cat.elt.style.transition = "all 1s"
     cat.vai = lambda *_: None
     timer.set_timeout(saiu, 1)
示例#17
0
    def toast(event):
        new = DIV(event.path[2].id + " / " + event.path[1].id, Class='toast')
        document['desenv'] <= new

        def hidden():
            new.style.display = 'none'

        timer.set_timeout(hidden, 3000)
示例#18
0
def step_two():
    add_log("确认帐户信息")
    document["marketdata"].clear()
    document["account"].clear()
    document["position"].clear()
    document["trade"].clear()
    document["order"].clear()
    timer.set_timeout(step_three, 1000)
示例#19
0
文件: main.py 项目: kwarwp/evelyn
 def shuffle_face(self, *_):
     faces = self.perf
     shuffle(faces)
     self.per.img.src = ACTIVE + faces[0] + POS
     if self.per_time < 500:
         self.per_time *= 1.2
         timer.set_timeout(self.shuffle_face, self.per_time)
     else:
         self.per_time = 10
示例#20
0
文件: main.py 项目: kwarwp/evelyn
 def shuffle_place(self, *_):
     places = self.lugf
     shuffle(places)
     self.lug.img.src = ACTIVE + places[0] + POS
     if self.lug_time < 500:
         self.lug_time *= 1.2
         timer.set_timeout(self.shuffle_place, self.lug_time)
     else:
         self.lug_time = 10
示例#21
0
def on_log_out(request):
    json_response = json.loads(request.text)

    if not json_response['success']:
        show_toast(json_response['message'], 'log out', 'server')
    else:
        show_toast(json_response['message'], 'log out', 'success')

        timer.set_timeout(go_to_splash, 1000)
示例#22
0
def step_one():
    if "ctp_account" in storage:
        _acc = json.loads(storage["ctp_account"])
        if _acc:
            ws.send("ws_ctpaccount=" + storage["ctp_account"])
            timer.set_timeout(step_two, 1000)
        else:
            add_log(html.A("请先设置ctp信息", href="settings.html"))
    else:
        add_log(html.A("请先设置ctp信息", href="settings.html"))
示例#23
0
def startVideo():
    global vids, endTime
    if not vids:
        window.player.stopVideo()
        return
    vidId, start, endTime = vids.pop(0)
    window.player.loadVideoById(vidId, start)
    window.player.setPlaybackQuality("hd720")
    window.player.playVideo()
    timer.set_timeout(finishedYet, 1000)
示例#24
0
文件: event.py 项目: rieseted/pygjs
def wait():
    global _queue

    pygame.locals.IDLE = True

    if _queue:
        pygame.locals.IDLE = False
        wait.event = poll()
    else:
        timer.set_timeout(wait, 100)
示例#25
0
def onmessage(e):
    #alert("Message received from executor:" + str(e.data));
    if e.data[0].lower() == "reveal":
        # successful

        graphics_main.commands = e.data[1]
        graphics_main.execute_commands()

        # now wait 1 frame before continuing the code execution in the worker thread
        timer.set_timeout(graphics_main.next_frame, 16)
示例#26
0
async def test_async_future_exc():
    """Future is raising exception from set_exception"""
    fut = aio.Future()
    timer.set_timeout(lambda: fut.set_exception(ValueError("EXPECTED_ERROR")),
                      10)
    try:
        await fut
    except ValueError as e:
        assert str(e) == "EXPECTED_ERROR"
        return
    assert False, "Error has not been raised"
示例#27
0
    def start(self) -> None:
        """Start the run.

        A run consist in a consecutive pipeline trials execution.
        """
        if w.get_value('record'):
            self.start_record()

        self.build_trials()
        timer.set_timeout(
            lambda: self.run_pipeline(self.pipeline_trial, self.trials), 2000)
示例#28
0
def sleepTime(time):
    timeLock = False

    def someFunction():
        timeLock = True

    timer.set_timeout(sleepTime, 3000)
    while timeLock == False:
        continue

    print("Finished after 3 seconds")
示例#29
0
 def move(self):
     forces = zip(*[
         b.force(self.x, self.y, self) for b in Button.BUTTONS if b != self
     ])
     dx, dy = [sum(force) for force in forces]
     self.x += int(dx)
     self.y += int(dy)
     # Button.SHOW._code.text = f"{dx} {dy} {self.x} {self.y}"
     self.elt.style.left, self.elt.style.top = self.x, self.y
     if abs(dx) > 1 or abs(dy) > 1:
         timer.set_timeout(self.move, 2)
示例#30
0
def js_update(layout=True):
    if PynodeCoreGlobals.do_update:
        try:
            if layout:
                PynodeCoreGlobals.update_timer = timer.set_timeout(update_instant_layout, 50)
                window.updateLayout()
            else:
                PynodeCoreGlobals.update_timer = timer.set_timeout(update_instant, 50)
                window.greuler_instance.update({"skipLayout": True})
        except:
            pass
示例#31
0
 def _complete(request):
     if request.status == 200:
         self.timeline.extend(json.loads(request.responseText))
         self.current_batch += 1
         self._timer_id = timer.set_timeout(self._do_next, 0)
         favorites.loading_text.style.display = 'none'  # On first update we hide it.
     elif request.status == 404:
         self._timer_id = timer.set_timeout(self._do_next, self.delay)
         pass
     else:
         raise NotImplementedError
示例#32
0
def wait(ms):
    global DELAYED

    DELAYED = True

    def undelay():
        global DELAYED

        DELAYED = False

    timer.set_timeout(undelay, ms)
def shoot():
    canvas.save()
    canvas.strokeStyle = "#FFFF00"
    canvas.beginPath()

    canvas.moveTo(190 + xOff, 140 + yOff)
    canvas.lineTo(250 + xOff, 200 + yOff)
    canvas.closePath()
    canvas.stroke()
    canvas.restore()
    timer.set_timeout(drawCanvas, 100)
示例#34
0
def on_log_in(request):
    log_in_progress.style.display = 'none'

    json_response = json.loads(request.text)

    if not json_response['success']:
        show_toast(json_response['message'], "log in", "server")
    else:
        show_toast(json_response['message'], "log in", "success")

        timer.set_timeout(go_to_home, 1000)
def shoot():
    canvas.save()
    canvas.strokeStyle = "#FFFF00"
    canvas.beginPath()
    
    canvas.moveTo(190+xOff, 140+yOff)
    canvas.lineTo(250+xOff, 200+yOff)
    canvas.closePath()
    canvas.stroke()
    canvas.restore()
    timer.set_timeout(drawCanvas,100)
	def ambientAudioTrigger2(evt):
		
		def stopPlaying():
			ambientDiv.fill = "url(#ambientAudio)"
			stopAmbientAudio()
			
		
		if(ambientDiv.fill == "url(#ambientAudioPlaying)"):
			stopPlaying()
		else:	
			hold = 10
			timer.set_timeout(stopPlaying,hold*1000)
			
			ambientDiv.fill = "url(#ambientAudioPlaying)"
			show_loading()
			playAmbientAudio(room.aAudio,hold,hide_loading)
示例#37
0
 def set_timeout(self, seconds, func):
     def callback():
         self.xmlhttp.abort()
         timer.clear_timeout(self.timer)
         self.timer = None
         func()
     self.timer = timer.set_timeout(callback, seconds*1000)
示例#38
0
 def resume(self):
     if not self._finished and not self._timeout:
         tm = time.time()
         if tm >= self._when:
             delay = 0
         else:
             delay = (self._when-tm)*1000
         self._timeout = timer.set_timeout(self._cb, delay)
示例#39
0
def start_stop(ev):
    global is_active, tick_delay
    if is_active:
        is_active = False
        document["btn_start_stop"].text = "Start"

        document["btn_start_stop"].disabled = ""
        document["btn_tick"].disabled = ""
        document["btn_clear"].disabled = ""
    else:
        tick_delay = int(document["edt_delay"].value)
        is_active = True
        document["btn_start_stop"].text = "Stop"

        document["btn_start_stop"].disabled = ""
        document["btn_tick"].disabled = "disabled"
        document["btn_clear"].disabled = "disabled"

        tick()
        timer.set_timeout(tick, tick_delay)
示例#40
0
 def loop(self):
     '''The game loop is the heart of the program'''
     try:
         self.display.clear_main()
         for obj in self.objects:
             obj.update()
         self.handle_collisions()
         if self.next_frame():
             for obj in self.objects:
                 obj.draw()
             self.show_fps()
             self.frame_id = set_timeout(self.loop, self.time_between_frames)
     except:
         print_exc()
         notify("blue")
示例#41
0
 def call_soon(self, callback, *args):
     return BrythonEventLoop.Handle(timer.set_timeout(lambda: callback(*args), 1))
示例#42
0
def tick(ev=None):
    global in_tick, alive, dead, tick_count

    if in_tick:
        return

    in_tick = True

    alive = 0
    dead = 0

    #because slicing does not copy if a list is contained in a list !
    old_grid = deepcopy(grid)
    
    _sr, _br = rule.split('/')
    _sr = [int(x) for x in _sr]
    _br = [int(x) for x in _br]

    for rw in range(rows):
        for cl in range(cols):
            n_alive = 0

            for x in range(-1, 2):
                nx = cl + x
                if nx < 0:
                    nx = cols - 1
                elif nx >= cols:
                    continue

                for y in range(-1, 2):
                    ny = rw + y

                    if ny < 0:
                        ny = rows - 1

                    if (ny < rows) and ((x != 0) or (y != 0)):
                        if old_grid[ny][nx] == 1:
                            n_alive += 1

            if grid[rw][cl] == 1:
                #if cell is alive !
                if not(n_alive in _sr):
                    grid[rw][cl] = 0
                    dead += 1
                    x1 = cl * size
                    y1 = rw * size
                    ctx.fillStyle = dead_cell_color
                    fillRect(x1, y1, size, size)
            else:
                if n_alive in _br:
                    grid[rw][cl] = 1
                    x1 = cl * size
                    y1 = rw * size
                    ctx.fillStyle = alive_cell_color
                    fillRect(x1, y1, size, size)
                else:
                    dead += 1

    alive = (rows * cols) - dead
    in_tick = False
    tick_count += 1

    update_labels()

    if is_active:
        timer.set_timeout(tick, tick_delay)
示例#43
0
文件: monitor.py 项目: Raxxor/web_ctp
def ws_disconnected():
    add_log("服务器端断开连接,3秒后尝试重连")
    idTimer = timer.set_timeout(reconnect, 3000)
示例#44
0
def step_three():
    add_log("启动循环消息")
    timer.set_timeout(loop, 1000)
示例#45
0
def ws_open():
    add_log("连接服务器端")
    timer.set_timeout(step_one, 1000)
示例#46
0
文件: player.py 项目: labase/eica
 def play(self, time, carta=None, casa=None):
     self.carta = carta if carta else self.carta
     self.casa = casa if casa else self.casa
     timer.set_timeout(self._play, time)
def playSong(state):
	
	global Pitches

	puzzle = state["Music_Puzzles"][state["Selected_Music"]]
	
	# Music Settings
	tempo = 1.0
	pitchChange = 0.0
	
	notes = puzzle.notes
	
	# Secondary list of notes for permutation based transformations.
	notes2 = []
	
	# Apply transformations
	for transform in puzzle.transformList:
	
		if(transform == "increasePitch"):
			pitchChange = pitchChange + 10.0
			
		if(transform == "decreasePitch"):
			pitchChange = pitchChange - 10.0
			
		if(transform == "increaseTempo"):
			tempo = tempo - 0.5
			
		if(transform == "decreaseTempo"):
			tempo = tempo + 0.5
			
		if(transform == "shuffleNotes"):
			
			# Temp storage array
			notes2 = []
			
			# Group the notes into chords so shuffling doesn't break up chords
			notes = groupIntoChords(notes)
			n = len(notes)
			
			# Shuffle chords/notes of notes2
			# Pad to next odd number for invertibility
			if(n%2==0):
				notes.append([])
				n = n + 1
			for j in range(n):
				notes2.append(notes[(2*j)%(n)])
			
			# Read temp back into original notes array
			notes = readChords(notes2)	
			
		if(transform == "reverseNotes"):
		
			# Temp storage array
			notes2 = []
			
			notes = groupIntoChords(notes)
			n = len(notes) - 1
			
			for i in range(n,-1,-1):
				notes2.append(notes[i])
			
			# Read notes2 back into original notes
			notes = readChords(notes2)

	
	# Play transformed notes
	wait = 0
	timeLimit = 10
	i = 0
	length = len(notes)
	while(i < length):
		note = notes[i]
		wait = note["wait"] * tempo + wait 
		pitch = Pitches[note["pitch"]] + pitchChange
		hold = float(note["hold"]) 

		piano.play({
			'wait' : wait,
			'pitch' : pitch,
			'env' : {'hold' : hold},
			filter : { 'q' : 15 } 
		})
		
		i = i + 1
		
		# Stops the song from playing overtime
		if(wait > timeLimit):
			piano.stop()
			i = length
	
	playButton = document.getElementById("playButton")
		
	if(wait > timeLimit):
		alert("Song cannot be more than " + str(timeLimit) + " seconds long.")
		if(playButton is not None):
			playButton.disabled = True
			buttonDisabled = timer.set_timeout(allowPlay,(timeLimit) * 1000)
	else: 
		if(playButton is not None):
			playButton.disabled = True
			buttonDisabled = timer.set_timeout(allowPlay, int(wait+1) * 1000)
示例#48
0
 def call_later(self, delay, callback, *args):
     return BrythonEventLoop.Handle(timer.set_timeout(lambda: callback(*args), delay*1000))
def move(x):
    changeKey(x,1)
    timer.set_timeout(stop,50)