Exemplo n.º 1
0
    def test_itimer_prof(self):
        # Issue 3864, unknown if this affects earlier versions of freebsd also
        if sys.platform == 'freebsd6':
            if test_support.verbose:
                sys.stderr.write('skipping -- itimer not reliable (does not '
                                 'mix well with threading) on freebsd6\n')
            return
        self.itimer = signal.ITIMER_PROF
        signal.signal(signal.SIGPROF, self.sig_prof)
        signal.setitimer(self.itimer, 0.2, 0.2)

        start_time = time.time()
        while time.time() - start_time < 60.0:
            # do some work
            _ = pow(12345, 67890, 10000019)
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break  # sig_prof handler stopped this itimer
        else:  # Issue 8424
            sys.stdout.write("test_itimer_prof: timeout: likely cause: "
                             "machine too slow or load too high.\n")
            return

        # profiling itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEqual(self.hndl_called, True)
Exemplo n.º 2
0
    def test_itimer_prof(self):
        # Issue 3864, unknown if this affects earlier versions of freebsd also
        if sys.platform=='freebsd6':
            if test_support.verbose:
                sys.stderr.write('skipping -- itimer not reliable (does not '
                                 'mix well with threading) on freebsd6\n')
            return
        self.itimer = signal.ITIMER_PROF
        signal.signal(signal.SIGPROF, self.sig_prof)
        signal.setitimer(self.itimer, 0.2, 0.2)

        start_time = time.time()
        while time.time() - start_time < 60.0:
            # do some work
            _ = pow(12345, 67890, 10000019)
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break # sig_prof handler stopped this itimer
        else: # Issue 8424
            sys.stdout.write("test_itimer_prof: timeout: likely cause: "
                             "machine too slow or load too high.\n")
            return

        # profiling itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEqual(self.hndl_called, True)
Exemplo n.º 3
0
    def test_itimer_virtual(self):
        self.itimer = signal.ITIMER_VIRTUAL
        signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
        signal.setitimer(self.itimer, 0.3, 0.2)

        for i in xrange(100000000):
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break # sig_vtalrm handler stopped this itimer

        # virtual itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEquals(self.hndl_called, True)
    def test_itimer_virtual(self):
        self.itimer = signal.ITIMER_VIRTUAL
        signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
        signal.setitimer(self.itimer, 0.3, 0.2)

        for i in range(100000000):
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break # sig_vtalrm handler stopped this itimer

        # virtual itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEquals(self.hndl_called, True)
    def test_itimer_prof(self):
        self.itimer = signal.ITIMER_PROF
        signal.signal(signal.SIGPROF, self.sig_prof)
        signal.setitimer(self.itimer, 0.2, 0.2)

        for i in range(100000000):
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break # sig_prof handler stopped this itimer

        # profiling itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEqual(self.hndl_called, True)
Exemplo n.º 6
0
    def test_itimer_prof(self):
        self.itimer = signal.ITIMER_PROF
        signal.signal(signal.SIGPROF, self.sig_prof)
        signal.setitimer(self.itimer, 0.2, 0.2)

        for i in xrange(100000000):
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break # sig_prof handler stopped this itimer

        # profiling itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEqual(self.hndl_called, True)
Exemplo n.º 7
0
 def test_itimer_prof(self):
     self.itimer = signal.ITIMER_PROF
     signal.signal(signal.SIGPROF, self.sig_prof)
     signal.setitimer(self.itimer, 0.2, 0.2)
     start_time = time.monotonic()
     while time.monotonic() - start_time < 60.0:
         _ = pow(12345, 67890, 10000019)
         if signal.getitimer(self.itimer) == (0.0, 0.0):
             break
     else:
         self.skipTest(
             'timeout: likely cause: machine too slow or load too high')
     self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
     self.assertEqual(self.hndl_called, True)
Exemplo n.º 8
0
    def test_itimer_virtual(self):
        self.itimer = signal.ITIMER_VIRTUAL
        signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
        signal.setitimer(self.itimer, 0.3, 0.2)

        for i in xrange(100000000):
            # use up some virtual time by doing real work
            _ = pow(12345, 67890, 10000019)
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break  # sig_vtalrm handler stopped this itimer

        # virtual itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEquals(self.hndl_called, True)
Exemplo n.º 9
0
 def restore(self, ended=False):
     """ this method restores the original alarm signal handler, or sets up
         the next timer on the pushdown stack. It takes a single argument
         indicating whether the with block is exiting (so it can know when
         to short-circuit the pushdown stack).
     """
     if not ended and signal.getitimer(signal.ITIMER_REAL)[0] > 0:
         log.debug("timer running, blocking timer stack restore")
         return
     while self.prev and self in self.prev:
         self.prev.pop()
     if self.prev:
         prev = self.prev[-1]
         time_diff = time.time() - prev.started
         time_remaining = prev.timeout - time_diff
         if time_remaining > 0:
             log.debug(
                 "time remaining on previous timer %s tr=%f, restarting itimer",
                 repr(prev), time_remaining)
             signal.signal(signal.SIGALRM, prev.fire_timer)
             signal.setitimer(signal.ITIMER_REAL, time_remaining)
         else:
             prev.restore()
     else:
         log.debug("timer stack empty after %s, resetting signals/itimers",
                   repr(self))
         signal.setitimer(signal.ITIMER_REAL, 0)
         signal.signal(signal.SIGALRM, signal.SIG_DFL)
Exemplo n.º 10
0
    def recap_timeout(self, new_timeout):
        """
        Set the new timeout of this Timer, measured from the start of the timer,
        if the new timeout would trigger sooner.

        :param new_timeout: The new timeout to set (0 indicates cancel)
        :return: None
        """
        if new_timeout == 0:
            self.cancel()
            return

        new_time_remaining = self._start_time + new_timeout - time.time()
        if new_time_remaining < 0:
            self.cancel()
            self._end_time = self._start_time + new_timeout
            raise TimeoutError()
        else:
            try:
                if signal.getitimer(
                        signal.ITIMER_REAL)[0] > new_time_remaining:
                    signal.setitimer(signal.ITIMER_REAL, new_time_remaining)
            except AttributeError:
                pass
            self._end_time = self._start_time + new_timeout
Exemplo n.º 11
0
    def timeout(seconds, exception):
        if seconds <= 0:
            raise ValueError('Invalid timeout: %s' % seconds)
        if threading.currentThread().name != 'MainThread':
            raise StateException('Interruptingcow can only be used from the '
                                 'MainThread.')
        set_sighandler()

        depth = len(timers)
        timeleft = signal.getitimer(signal.ITIMER_REAL)[0]
        if not timers or timeleft > seconds:
            try:
                signal.setitimer(signal.ITIMER_REAL, seconds)
                timers.append(Timer(time.time() + seconds, exception))
                yield
            finally:
                if len(timers) > depth:
                    # cancel our timer
                    signal.setitimer(signal.ITIMER_REAL, 0)
                    timers.pop()
                    if timers:
                        # reinstall the parent timer
                        timeleft = timers[-1].expiration - time.time()
                        if timeleft > 0:
                            signal.setitimer(signal.ITIMER_REAL, timeleft)
                        else:
                            # the parent timer has expired, trigger the handler
                            handler()
        else:
            # not enough time left on the parent timer
            yield
Exemplo n.º 12
0
 def __enter__(self):
     self._old_handler = signal.signal(signal.SIGALRM,
                                       self._timeout_handler)
     self._old_timer = math.ceil(signal.getitimer(signal.ITIMER_REAL)[0])
     if self._alarm_fn:
         self._alarm_fn(self._timeout)
     return self
Exemplo n.º 13
0
 def test_itimer_virtual(self):
     self.itimer = signal.ITIMER_VIRTUAL
     signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
     signal.setitimer(self.itimer, 0.3, 0.2)
     start_time = time.monotonic()
     while time.monotonic() - start_time < 60.0:
         # use up some virtual time by doing real work
         _ = pow(12345, 67890, 10000019)
         if signal.getitimer(self.itimer) == (0.0, 0.0):
             break # sig_vtalrm handler stopped this itimer
     else: # Issue 8424
         self.skipTest("timeout: likely cause: machine too slow or load too "
                       "high")
     # virtual itimer should be (0.0, 0.0) now
     self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
     # and the handler should have been called
     self.assertEqual(self.hndl_called, True)
Exemplo n.º 14
0
 def test_itimer_prof(self):
     self.itimer = signal.ITIMER_PROF
     signal.signal(signal.SIGPROF, self.sig_prof)
     signal.setitimer(self.itimer, 0.1, 0.1)
     start_time = time.monotonic()
     while time.monotonic() - start_time < 60.0:
         # do some work
         _ = pow(12345, 67890, 10000019)
         if signal.getitimer(self.itimer) == (0.0, 0.0):
             break # sig_prof handler stopped this itimer
     else: # Issue 8424
         self.skipTest("timeout: likely cause: machine too slow or load too "
                       "high")
     # profiling itimer should be (0.0, 0.0) now
     self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
     # and the handler should have been called
     self.assertEqual(self.hndl_called, True)
Exemplo n.º 15
0
    def test_itimer_prof(self):
        self.itimer = signal.ITIMER_PROF
        signal.signal(signal.SIGPROF, self.sig_prof)
        signal.setitimer(self.itimer, 0.2, 0.2)

        start_time = time.time()
        while time.time() - start_time < 5.0:
            # do some work
            _ = pow(12345, 67890, 10000019)
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break  # sig_prof handler stopped this itimer
        else:
            self.fail('timeout waiting for sig_prof signal')

        # profiling itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEqual(self.hndl_called, True)
Exemplo n.º 16
0
    def test_itimer_virtual(self):
        self.itimer = signal.ITIMER_VIRTUAL
        signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
        signal.setitimer(self.itimer, 0.3, 0.2)

        start_time = time.time()
        while time.time() - start_time < 60.0:
            # use up some virtual time by doing real work
            _ = pow(12345, 67890, 10000019)
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break  # sig_vtalrm handler stopped this itimer
        else:  # Issue 8424
            self.skipTest("timeout: likely cause: machine too slow or load too " "high")

        # virtual itimer should be (0.0, 0.0) now
        self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEqual(self.hndl_called, True)
Exemplo n.º 17
0
    def test_itimer_prof(self):
        self.itimer = signal.ITIMER_PROF
        signal.signal(signal.SIGPROF, self.sig_prof)
        signal.setitimer(self.itimer, 0.2, 0.2)

        start_time = time.time()
        while time.time() - start_time < 5.0:
            # do some work
            _ = pow(12345, 67890, 10000019)
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break # sig_prof handler stopped this itimer
        else:
            self.fail('timeout waiting for sig_prof signal')

        # profiling itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEqual(self.hndl_called, True)
Exemplo n.º 18
0
    def test_itimer_prof(self):
        self.itimer = signal.ITIMER_PROF
        signal.signal(signal.SIGPROF, self.sig_prof)
        signal.setitimer(self.itimer, 0.2, 0.2)

        start_time = time.time()
        while time.time() - start_time < 60.0:
            # do some work
            _ = pow(12345, 67890, 10000019)
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break  # sig_prof handler stopped this itimer
        else:  # Issue 8424
            self.skipTest("timeout: likely cause: machine too slow or load too " "high")

        # profiling itimer should be (0.0, 0.0) now
        self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEqual(self.hndl_called, True)
Exemplo n.º 19
0
def stats():
    require_login()
    usage = resource.getrusage(resource.RUSAGE_SELF)
    stats = ['%-25s (%-10s) = %s' % (desc, name, getattr(usage, name)) for name, desc in [
        ('ru_utime', 'User time'),
        ('ru_stime', 'System time'),
        ('ru_maxrss', 'Max. Resident Set Size') ]] + [
        '%-35s    = %s' % ('Maintainance time', signal.getitimer(signal.ITIMER_REAL)[0])]
    
    return dict(content=stats)
Exemplo n.º 20
0
    def test_itimer_virtual(self):
        self.itimer = signal.ITIMER_VIRTUAL
        signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
        signal.setitimer(self.itimer, 0.3, 0.2)

        start_time = time.time()
        while time.time() - start_time < 5.0:
            # use up some virtual time by doing real work
            _ = pow(12345, 67890, 10000019)
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break  # sig_vtalrm handler stopped this itimer
        else:
            self.fail('timeout waiting for sig_vtalrm signal; '
                      'signal.getitimer(self.itimer) gives: %s' %
                      (signal.getitimer(self.itimer), ))

        # virtual itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEquals(self.hndl_called, True)
Exemplo n.º 21
0
    def test_itimer_virtual(self):
        self.itimer = signal.ITIMER_VIRTUAL
        signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
        signal.setitimer(self.itimer, 0.3, 0.2)

        start_time = time.time()
        while time.time() - start_time < 5.0:
            # use up some virtual time by doing real work
            _ = pow(12345, 67890, 10000019)
            if signal.getitimer(self.itimer) == (0.0, 0.0):
                break # sig_vtalrm handler stopped this itimer
        else:
            self.fail('timeout waiting for sig_vtalrm signal; '
                      'signal.getitimer(self.itimer) gives: %s' %
                       (signal.getitimer(self.itimer),))

        # virtual itimer should be (0.0, 0.0) now
        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
        # and the handler should have been called
        self.assertEquals(self.hndl_called, True)
Exemplo n.º 22
0
def FatalTimeout(max_run_time, display_message=None):
    """ContextManager that exits the program if code is run for too long.

  This implementation is fairly simple, thus multiple timeouts
  cannot be active at the same time.

  Additionally, if the timeout has elapsed, it'll trigger a SystemExit
  exception within the invoking code, ultimately propagating that past
  itself.  If the underlying code tries to suppress the SystemExit, once
  a minute it'll retrigger SystemExit until control is returned to this
  manager.

  Args:
    max_run_time: How long to wait.  May be a number (in seconds, can be
      fractional) or a datetime.timedelta object.
    display_message: Optional string message to be included in timeout
      error message, if the timeout occurs.
  """
    max_run_time = Timedelta(max_run_time).total_seconds()

    # pylint: disable=W0613
    def kill_us(sig_num, frame):
        # While this SystemExit *should* crash it's way back up the
        # stack to our exit handler, we do have live/production code
        # that uses blanket except statements which could suppress this.
        # As such, keep scheduling alarms until our exit handler runs.
        # Note that there is a potential conflict via this code, and
        # RunCommand's kill_timeout; thus we set the alarming interval
        # fairly high.
        _ScheduleTimer(60)

        # The cbuildbot stage that gets aborted by this timeout should be treated as
        # failed by buildbot.
        error_message = ("Timeout occurred- waited %i seconds, failing." %
                         max_run_time)
        if display_message:
            error_message += ' Timeout reason: %s' % display_message
        logging.PrintBuildbotStepFailure()
        logging.error(error_message)
        raise SystemExit(error_message)

    if signal.getitimer(signal.ITIMER_REAL)[0]:
        raise Exception(
            'FatalTimeout cannot be used in parallel to other alarm '
            'handling code; failing')

    original_handler = signal.signal(signal.SIGALRM, kill_us)
    try:
        _ScheduleTimer(max_run_time)
        yield
    finally:
        # Cancel the alarm request and restore the original handler.
        _CancelTimer()
        signal.signal(signal.SIGALRM, original_handler)
Exemplo n.º 23
0
 def print_countdown():
     t = threading.currentThread()
     while getattr(t, "do_run", True):
         try:
             time.sleep(1)
             countdown = int(signal.getitimer(signal.ITIMER_REAL)[0])
             print(countdown + 1, end="..", flush=True)
             if bool(countdown):
                 continue
             return
         except AlarmException:
             return
Exemplo n.º 24
0
def timing_out_itimer(seconds):
    if seconds is None:
        yield
        return
    with raising_signal(signal.SIGALRM, TimeoutError):
        oldval, oldint = signal.getitimer(signal.ITIMER_REAL)
        if oldval != 0.0:
            raise RuntimeError("ITIMER_REAL already in use")
        signal.setitimer(signal.ITIMER_REAL, seconds)
        try:
            yield
        finally:
            signal.setitimer(signal.ITIMER_REAL, 0)
Exemplo n.º 25
0
def timing_out_itimer(seconds):
    if seconds is None:
        yield
        return
    with raising_signal(signal.SIGALRM, TimeoutError):
        oldval, oldint = signal.getitimer(signal.ITIMER_REAL)
        if oldval != 0.0:
            raise RuntimeError("ITIMER_REAL already in use")
        signal.setitimer(signal.ITIMER_REAL, seconds)
        try:
            yield
        finally:
            signal.setitimer(signal.ITIMER_REAL, 0)
Exemplo n.º 26
0
    def timeout(seconds, exception):
        if is_disabled:
            yield
            return

        if threading.currentThread().name != 'MainThread':
            raise StateException('Interruptingcow can only be used from the '
                                 'MainThread.')
        if isinstance(seconds, Quota):
            quota = seconds
        else:
            quota = Quota(float(seconds))
        set_sighandler()
        seconds = quota.remaining()

        depth = len(timers)
        parenttimeleft = signal.getitimer(signal.ITIMER_REAL)[0]
        if not timers or parenttimeleft > seconds:
            try:
                quota._start()
                timers.append(Timer(time.time() + seconds, exception))
                if seconds > 0:
                    signal.setitimer(signal.ITIMER_REAL, seconds)
                    yield
                else:
                    handler()
            finally:
                quota._stop()
                if len(timers) > depth:
                    # cancel our timer
                    signal.setitimer(signal.ITIMER_REAL, 0)
                    timers.pop()
                    if timers:
                        # reinstall the parent timer
                        parenttimeleft = timers[-1].expiration - time.time()
                        if parenttimeleft > 0:
                            signal.setitimer(signal.ITIMER_REAL,
                                             parenttimeleft)
                        else:
                            # the parent timer has expired, trigger the handler
                            handler()
        else:
            # not enough time left on the parent timer
            try:
                quota._start()
                yield
            finally:
                quota._stop()
Exemplo n.º 27
0
    def timeout(seconds, exception):
        if threading.currentThread().name != "MainThread":
            raise StateException(
                "Interruptingcow can only be used from the " "MainThread."
            )
        if isinstance(seconds, Quota):
            quota = seconds
        else:
            quota = Quota(float(seconds))
        set_sighandler()
        seconds = quota.remaining()

        depth = len(timers)
        parenttimeleft = signal.getitimer(signal.ITIMER_REAL)[0]
        if not timers or parenttimeleft > seconds:
            try:
                quota._start()
                timers.append(Timer(time.time() + seconds, exception))
                if seconds > 0:
                    signal.setitimer(signal.ITIMER_REAL, seconds)
                    yield
                else:
                    handler()
            finally:
                quota._stop()
                if len(timers) > depth:
                    # cancel our timer
                    signal.setitimer(signal.ITIMER_REAL, 0)
                    timers.pop()
                    if timers:
                        # reinstall the parent timer
                        parenttimeleft = timers[-1].expiration - time.time()
                        if parenttimeleft > 0:
                            signal.setitimer(signal.ITIMER_REAL, parenttimeleft)
                        else:
                            # the parent timer has expired, trigger the handler
                            handler()
        else:
            # not enough time left on the parent timer
            try:
                quota._start()
                yield
            finally:
                quota._stop()
Exemplo n.º 28
0
def main_game():
	global sec
	global minutes
	global lvl_structure
	global wincol
	global winlin
	global start_time
	global Monsters
	global gracz
	global outranked
	winlin, wincol =  stdscr.getmaxyx()
	
	#Wczytanie pliku level'u
	lvl_structure=[]
	tmp = []
	for line in xrange(1,len(open(file_name, 'rU').readlines())+1):
		tmp = []
		for char in linecache.getline(file_name, line):
			if char != '\n':
				tmp.append(char)
		lvl_structure.append(tmp)
	
	gracz = player()
	#Sprawdzanie czy level nie wystaje poza okno terminala
	lvl_sizey=len(lvl_structure)+10
	a=0
	lvl_sizex=0
	for i in xrange(0,len(lvl_structure)):
		a=len(lvl_structure[i])
		if a>lvl_sizex: lvl_sizex=a
	if lvl_sizex<50: lvl_sizex=50

	while lvl_sizex>wincol or lvl_sizey>winlin:
		stdscr.clear()
		winlin, wincol =  stdscr.getmaxyx()
		xx=(wincol/2)
		yy=winlin/2
		stdscr.addstr(yy-1,xx-7,'Resize window,',curses.A_BOLD)
		stdscr.addstr(yy,xx-9,'in order to play!',curses.A_BOLD)
		stdscr.refresh()

	#Rysowanie poziomu
	stdscr.clear()
	stdscr.addstr(0,0,'\nLevel'+' '+str(sorted(os.listdir(dirs_with_lvl[choose-1])).index(level)+1)+' ('+level+')\n\n', curses.color_pair(5))
	
	stdscr.addstr(3,0,'')
	Monsters = []
	MonX = -1
	MonY = 0
	for char in open(file_name).read():
		MonX += 1
		if char == 'X':
			stdscr.addstr( "#", curses.color_pair(1) )
		elif char == ' ':
			stdscr.addstr( " ", curses.color_pair(1) )
		elif char == '*':
			stdscr.addstr( " ", curses.color_pair(1) )
		elif char == 's':
			stdscr.addstr( " ", curses.color_pair(2) )
		elif char == 'P':
			stdscr.addstr( "@", curses.color_pair(2) )
		elif char == 'F':
			stdscr.addstr( "^", curses.color_pair(3) )
		elif char == 'C':
			stdscr.addstr( "$", curses.color_pair(4) )
		elif char == 'D':
			stdscr.addstr( "=", curses.color_pair(1) )
		elif char == 'K':
			stdscr.addstr( "F", curses.color_pair(1) )
		elif char == 'G':
			stdscr.addstr( "=", curses.color_pair(8) )
		elif char == 'g':
			stdscr.addstr( "F", curses.color_pair(8) )
		elif char == 'R':
			stdscr.addstr( "=", curses.color_pair(7) )
		elif char == 'r':
			stdscr.addstr( "F", curses.color_pair(7) )
		elif char == 'Y':
			stdscr.addstr( "=", curses.color_pair(4) )
		elif char == 'y':
			stdscr.addstr( "F", curses.color_pair(4) )
		elif char == 'B':
			stdscr.addstr( "=", curses.color_pair(3) )
		elif char == 'b':
			stdscr.addstr( "F", curses.color_pair(3) )
		elif char == 'Z':
			stdscr.addstr( "X", curses.color_pair(9) )
		elif char == 'M':
			stdscr.addstr( "@", curses.color_pair(11)+curses.A_BOLD )
			#for i in lvl_structure:
			#	try:
			#		monX=lvl_structure[lvl_structure.index(i)].index('M')
			#		monY=lvl_structure.index(i)
			#	except:
			#		pass
			lvl_structure[MonY][MonX] = 'm'
			Monsters.append( monster(MonY,MonX) )
		elif char == '\n':
			MonY+=1
			MonX = -1
			stdscr.addstr( "\n", curses.color_pair(1) )
			line+=1
		stdscr.refresh()

	must_reset = False
	while gracz.finish == False:
		winlin, wincol =  stdscr.getmaxyx()
		stdscr.addstr(winlin-2,0,'Coins:', curses.color_pair(6) )
		stdscr.addstr(winlin-2,9,str(gracz.coins)+'/'+str(gracz.coinsMAX), curses.color_pair(10) )

		now_time=time.time()
		now_time=int(now_time)
		sec=now_time-start_time
		minutes=sec/60
		sec=sec%60
		sec=str(sec)
		minutes=str(minutes)
		if len(sec)==1: sep='0'
		else: sep=''
		stdscr.addstr(winlin-2,16,'Time:', curses.color_pair(6) )
		stdscr.addstr(winlin-2,24,minutes+':'+sep+sec, curses.color_pair(10) )
		if (lvl_structure[gracz.y][gracz.x-1]=='Z' and lvl_structure[gracz.y][gracz.x-2] == 'C' and (lvl_structure[gracz.y-1][gracz.x-1] in gracz.solid or lvl_structure[gracz.y+1][gracz.x-1] in gracz.solid) and  lvl_structure[gracz.y-1][gracz.x-2] in gracz.solid and lvl_structure[gracz.y+1][gracz.x-2] in gracz.solid and lvl_structure[gracz.y][gracz.x-3] in gracz.solid) or (lvl_structure[gracz.y][gracz.x+1]=='Z' and lvl_structure[gracz.y][gracz.x+2] == 'C' and (lvl_structure[gracz.y-1][gracz.x+1] in gracz.solid or lvl_structure[gracz.y+1][gracz.x+1] in gracz.solid) and  lvl_structure[gracz.y-1][gracz.x+2] in gracz.solid and lvl_structure[gracz.y+1][gracz.x+2] in gracz.solid and lvl_structure[gracz.y][gracz.x+3] in gracz.solid) or (lvl_structure[gracz.y-1][gracz.x]=='Z' and lvl_structure[gracz.y-2][gracz.x] == 'C' and (lvl_structure[gracz.y-1][gracz.x-1] in gracz.solid or lvl_structure[gracz.y-1][gracz.x+1] in gracz.solid) and  lvl_structure[gracz.y-2][gracz.x-1] in gracz.solid and lvl_structure[gracz.y-2][gracz.x+1] in gracz.solid and lvl_structure[gracz.y-3][gracz.x] in gracz.solid) or (lvl_structure[gracz.y+1][gracz.x]=='Z' and lvl_structure[gracz.y+2][gracz.x] == 'C' and (lvl_structure[gracz.y+1][gracz.x-1] in gracz.solid or lvl_structure[gracz.y+1][gracz.x+1] in gracz.solid) and lvl_structure[gracz.y+2][gracz.x-1] in gracz.solid and lvl_structure[gracz.y+2][gracz.x+1] in gracz.solid and lvl_structure[gracz.y+3][gracz.x] in gracz.solid):
			must_reset = True
		if must_reset:	
			stdscr.addstr(winlin-2,39,'R - restart',curses.A_BLINK+curses.A_BOLD)
		else:
			stdscr.addstr(winlin-2,39,'R - restart',curses.A_NORMAL+curses.A_BOLD)

		for i in xrange(0,wincol-1):
			stdscr.addstr(winlin-1,i,' ')
			stdscr.addstr(winlin-3,i,' ')
			stdscr.addstr(winlin-4,i,' ')
			stdscr.addstr(winlin-5,i,' ')

		signal.signal(signal.SIGALRM,update_monsters)
		if signal.getitimer(signal.ITIMER_REAL)[0] == 0: signal.setitimer(signal.ITIMER_REAL,0.5)
		key = stdscr.getch()
		if key == curses.KEY_UP or key == ord('w'):	gracz.goUP()
		elif key == curses.KEY_DOWN or key == ord('s'): gracz.goDOWN()
		elif key == curses.KEY_LEFT or key == ord('a'): gracz.goLEFT()
		elif key == curses.KEY_RIGHT or key == ord('d'): gracz.goRIGHT()
		elif key == ord('r'):
			main_game()
			break
		elif key == ord('q'):
			outranked = True
			end_game()
			break
Exemplo n.º 29
0
    data_size = len(data)

    last_ack = math.ceil(data_size / MSS)

    frame_data = bytearray()

    while (True):
        byte = rdt_send()
        if ((done and len(frame_data) > 0) or len(frame_data) == MSS):
            checksum = getchecksum(copy.copy(frame_data))
            header = Header(SEQ_NO, checksum, DATA)
            frame = Frame(header, frame_data)
            storeframe(frame)
            sendframe(frame)

            if (signal.getitimer(timer)[0] == 0):
                signal.setitimer(timer, RTO)

            frame_data = bytearray()
        if not done:
            frame_data += bytearray([byte])
            continue
        if (done):
            break

    while not_sent_all:
        if (signal.getitimer(timer)[0] == 0):
            signal.setitimer(timer, RTO)

    r.join()
Exemplo n.º 30
0
def play():
    """消しマスをコマンドライン上でプレイ"""
    print("問題のリストを表示します.")
    question_list()

    while True:
        try:
            inputs = tuple(input("作者とタグを入力し問題を選択してください. >>\n").split(' '))

            # 書式は "作者名 問題タグ"
            if len(inputs) != 2:
                raise InputError("不適切な入力です. '[作者] [タグ]'の形式で入力してください.")

            # ファイルを開く
            with open('questions_data.bin', 'rb') as f:
                keshimasu_list = pickle.load(f)

            # 問題集の(作者, タグ)リスト
            author_tags = [(k.author, k.tag) for k in keshimasu_list]

            if inputs in author_tags:
                # 該当問題がリストにある場合 -> 該当問題が何問目かを検索し取得
                idx = author_tags.index(inputs)
                keshimasu = keshimasu_list[idx]
                print("問題を読み込みました.")
                break
            else:
                print("該当する問題が見つかりませんでした.")
        except InputError as e:
            print(e)

    ################
    # ゲーム開始準備 #
    ################

    #
    # よく使う変数のリネーム
    #

    hei = keshimasu.hei  # 盤面を表示する高さ
    tate = keshimasu.shape[0]  # 盤面の縦の長さ
    yoko = keshimasu.shape[1]  # 盤面の横の長さ

    #
    # コマンドライン表示
    #

    print("お題: " + keshimasu.theme)
    # 盤面の表示 番号付き
    keshimasu.display(number_is=True)

    input("エンターキーを押すと始まります.")
    print("制限時間は " + str(keshimasu.time) + "s です")

    #
    # タイマーの設定
    #

    signal.signal(signal.SIGALRM, signal_handler)
    signal.setitimer(signal.ITIMER_REAL, keshimasu.time)  # 100秒後に例外を起こす

    #############
    # ゲーム開始 #
    #############

    try:
        # 1ターンの処理
        while True:
            while True:
                try:
                    # 回答マスの選択
                    input_str = input("番号を指定してください. >>").split(' ')

                    # 数値以外を入力していないかチェック
                    if not np.all([i.isdecimal() for i in input_str]):
                        raise InputError("非負整数を入力してください.")
                    in_num = [int(e) for e in input_str]

                    # 有効な選択か否かのチェック
                    if not np.all(0 < np.all(np.array(in_num) < hei * yoko)):
                        raise InputError(f"0から{hei*yoko-1}の数値を入力してください.")

                    # 選択が2つ以上の場合更に間隔をチェック
                    if len(in_num) > 1:
                        # 各隣り合う要素の差分からなる階差列
                        check_list = np.array([])
                        for i in range(len(in_num) - 1):
                            check_list = np.append(check_list,
                                                   in_num[i + 1] - in_num[i])

                        # 横: 間隔がすべて1 縦: 間隔がすべて横幅
                        if np.all(check_list == 1) or np.all(
                                check_list == yoko):
                            break

                        # ここを通る場合, 入力が不適
                        raise InputError("隣り合ったマスを左からもしくは上から指定してください.")
                    else:
                        break
                except ValueError:
                    print("数値を入力してください.")
                except InputError as e:
                    print(e)

            # 選択した番号をnumpy式のindexに変換
            in_num_f = (np.array(in_num) // yoko + tate - hei,
                        np.array(in_num) % yoko)

            # 選択した番号から熟語を構成
            choice = keshimasu.construct_word(in_num_f)

            # 選択した熟語を表示
            print("'" + choice + "'が選択されました.")

            # 回答の入力
            in_ans = input("この選択に対し, お題に合うように答えを入力してください. >>")

            # 正解判定
            if keshimasu.check_answer(choice, in_ans):
                # 正解の場合
                print(choice + ': ' + in_ans + " 正解です.")
                # 盤面の更新
                keshimasu.delete_word(in_num_f)
                print("盤面が更新されました.")

                # 全消しの場合ループを抜けてクリア
                if np.all(keshimasu.playing_table == ' '):  # 全角スペース
                    print("全消しが達成されました. おめでとうございます.")
                    break
                # ターンの終了
            else:
                # 不正解の場合
                print(choice + ': ' + in_ans + " 不正解です.")
            r_time = floor(signal.getitimer(signal.ITIMER_REAL)[0])
            print("残り時間は " + str(r_time) + "s です")

            # お題の表示
            print("お題: " + keshimasu.theme)
            # 盤面の表示 番号付き
            keshimasu.display(number_is=True)

    except TimeUpException as e:
        print(e.args[0])