コード例 #1
0
    def setUp(self):
        self.port = randint(10000, 65000)
        self.server_manager = None
        self.server_started = False

        def server_thread(test_case):
            test_case.server_manager = ServerManager(config_object={'network':{'port': self.port}})

            def on_run():
                test_case.server_started = True
            test_case.server_manager.on_run = on_run

            dbs = test_case.server_manager.db_session_type()
            dbs.add(User(name='john', password='******'))
            dbs.add(User(name='lazy', password=''))
            dbs.add(GamePawn(name='test_pawn', width=2, height=3, shapestring="100110"))
            dbs.add(GameBoard(name='test_board', width=6, height=8, shapestring="0"*48))
            dbs.flush()
            test_case.server_manager.run()

        self.server_thread = Thread(target=server_thread, args=(self,))
        self.server_thread.start()

        while not self.server_started:
            sleep(milliseconds(10))
        sleep(milliseconds(100))
コード例 #2
0
ファイル: Player.py プロジェクト: COUNTERKILL/XedusGame
	def Move(self,step):
		if self._clock.elapsed_time < sf.milliseconds(10):
			return
		self._clock.restart()
		if self._position.x < 0:
			self._position.x = 0
		if self._position.y < 0:
			self._position.y = 0
		if (self._position.x + self.GetWidth()) > self._location.GetWidth():
			self._position.x = self._location.GetWidth() - self.GetWidth()
		if (self._position.y + self.GetHeight()) > self._location.GetHeight():
			self._position.y = self._location.GetHeight() - self.GetHeight()
		if step.x==0 and step.y==0:
			self._stopCounter += 1
			if self._stopCounter > 10:
				self.StopAnimate()
				music = musicCollection.GetMusic("ACTOR", "STEP")
				music.stop()
		else:
			obj.Object.Move(self, step)
			self._stopCounter = 0
			self.SetAnimation("WALK")
			self.StartAnimate()
			music = musicCollection.GetMusic("ACTOR", "STEP")
			if music.status == sf.audio.SoundSource.STOPPED and self._stepBetweenTime.elapsed_time.seconds > TIME_BETWEEN_STEPS:
				self._stepBetweenTime.restart()
				music.volume = 50
				music.play()
コード例 #3
0
ファイル: gv_audio.py プロジェクト: hasvers/jehuti
 def thread(self, sound, volume, loops=0):
     sound.play()
     sound.volume = rint(volume)
     # loop while the sound is playing
     time = 0
     killtime = 0
     deltat = 10
     while sound.status in (sfml.Sound.PLAYING, sfml.Sound.PAUSED):
         # leave some CPU time for other processes
         sfml.sleep(sfml.milliseconds(deltat))
         time += deltat
         if sound.fadein and time < sound.fadein:
             sound.volume = rint(volume * float(time) / sound.fadein)
         if sound.fadeout and time > sound.duration - sound.fadeout:
             sound.volume = rint(volume * float(time) / (rint(volume * float(time) / sound.fadein)))
         if not sound.kill_in is None:
             killtime += deltat
             if killtime > sound.kill_in:
                 sound.stop()
                 sound.kill_in = None
                 break
             else:
                 sound.volume *= 1 - float(killtime / sound.kill_in)
     if loops > 0:
         self.thread(sound, volume, loops - 1)
     if self.permanent == sound:
         self.thread(sound, volume)
     elif self.permanent and sound.typ == "music":
         self.thread(self.permanent, volume)
コード例 #4
0
def gerer_fps(temps_actuel):

    print(temps_actuel.elapsed_time.milliseconds)
    if temps_actuel.elapsed_time.milliseconds < 30:
        sf.sleep(sf.milliseconds(30-temps_actuel.elapsed_time.milliseconds))

    temps_actuel.restart()
コード例 #5
0
def gerer_fps(temps_actuel):

    print(temps_actuel.elapsed_time.milliseconds)
    if temps_actuel.elapsed_time.milliseconds < 30:
        sf.sleep(sf.milliseconds(30 - temps_actuel.elapsed_time.milliseconds))

    temps_actuel.restart()
コード例 #6
0
ファイル: m5k.py プロジェクト: lvm/m5k
def _sfml(s_file, times=None, fadeout=None):
    global FRAMERATE
    sound = sf.Music.from_file(s_file)

    for t in range(times):
        sound.play()
        while sound.status == sf.Music.PLAYING:
            sf.sleep(sf.milliseconds(FRAMERATE))
コード例 #7
0
 def __init__(self, window):
     self._window = window
     self._clear_color = sf.Color(255, 255, 255)
     self._background_sprite = None
     self._background_texture = None
     self._window_opened = True
     self._clock = sf.Clock()
     self._fps = 30
     self._frame_time = sf.milliseconds(1000 / self._fps)
コード例 #8
0
	def __init__(self, window):
		self._window = window
		self._clear_color = sf.Color(255, 255, 255)
		self._background_sprite = None
		self._background_texture = None
		self._window_opened = True
		self._clock = sf.Clock()
		self._fps = 30
		self._frame_time = sf.milliseconds(1000 / self._fps)
コード例 #9
0
 def __playMusicFromFile(self, music_file):
     if not self.pausing:
         self.music = sf.Music.from_file(music_file)
     ## Play it
     self.music.play()
     
     #loop while the sound is playing
     while self.music.status == sf.Music.PLAYING:
         #leave some cpu time for other processes
         sf.sleep(sf.milliseconds(100))
コード例 #10
0
    def __init__(self, number_of_frames, duration):
        sf.Drawable.__init__(self)

        # if current_frame == number_of_frames then it means there's no
        # frame left or in other words, the animation is over.
        self._current_frame = 0
        self._number_of_frames = number_of_frames

        # integer arithmetic operation not supported yet for sf.Time
        self._frame_time = sf.milliseconds(duration.milliseconds / number_of_frames)
コード例 #11
0
 def __init__(self) :
   self.PlayerLife = 2
   self.PlayerBomb = 3
   self.Focus = False
   self.PlayerCoor = sfml.Vector2(100,400)
   self.Clock = sfml.Clock()
   self.TimeToMove = sfml.milliseconds(45)
   self.EnemyList = []
   self.Boss = None
   self.Bounds = sfml.Rectangle((30,30),(500,550))
   self.BulletList = []
コード例 #12
0
ファイル: server.py プロジェクト: Jijidici/python-sfml
def do_server(port):
	# build an audio stream to play sound data as it is received through the network
	audio_stream = NetworkAudioStream()
	audio_stream.start(port)

	# loop until the sound playback is finished
	while audio_stream.status != sf.SoundStream.STOPPED:
		# leave some CPU time for other threads
		sf.sleep(sf.milliseconds(100))


	# wait until the user presses 'enter' key
	input("Press enter to replay the sound...")

	# replay the sound (just to make sure replaying the received data is OK)
	audio_stream.play();

	# loop until the sound playback is finished
	while audio_stream.status != sf.SoundStream.STOPPED:
		sf.sleep(sf.milliseconds(100))
コード例 #13
0
ファイル: sound_capture.py プロジェクト: Jijidici/python-sfml
def main():
	# check that the device can capture audio
	if not sf.SoundRecorder.is_available():
		print("Sorry, audio capture is not supported by your system")
		return

	# choose the sample rate
	sample_rate = int(input("Please choose the sample rate for sound capture (44100 is CD quality): "))

	# wait for user input...
	input("Press enter to start recording audio")

	# here we'll use an integrated custom recorder, which saves the captured data into a sf.SoundBuffer
	recorder = sf.SoundBufferRecorder()

	# audio capture is done in a separate thread, so we can block the main thread while it is capturing
	recorder.start(sample_rate)
	input("Recording... press enter to stop")
	recorder.stop()

	# get the buffer containing the captured data
	buffer = recorder.buffer

	# display captured sound informations
	print("Sound information:")
	print("{0} seconds".format(buffer.duration))
	print("{0} samples / seconds".format(buffer.sample_rate))
	print("{0} channels".format(buffer.channel_count))

	# choose what to do with the recorded sound data
	choice = input("What do you want to do with captured sound (p = play, s = save) ? ")

	if choice == 's':
		# choose the filename
		filename = input("Choose the file to create: ")

		# save the buffer
		buffer.to_file(filename);
	else:
		# create a sound instance and play it
		sound = sf.Sound(buffer)
		sound.play();

		# wait until finished
		while sound.status == sf.Sound.PLAYING:
			# leave some CPU time for other threads
			sf.sleep(sf.milliseconds(100))

	# finished !
	print("Done !")

	# wait until the user presses 'enter' key
	input("Press enter to exit...")
コード例 #14
0
    def setUp(self):
        self.port = randint(10000, 65000)
        self.server_manager = None
        self.server_started = False

        def server_thread(test_case):
            test_case.server_manager = ServerManager(config_object={'network':{'port': self.port}})

            def on_run():
                test_case.server_started = True
            test_case.server_manager.on_run = on_run

            dbs = test_case.server_manager.db_session_type()
            dbs.add(User(name='john', password='******'))
            dbs.add(User(name='lazy', password=''))
            dbs.flush()
            test_case.server_manager.run()

        self.server_thread = Thread(target=server_thread, args=(self,))
        self.server_thread.start()

        while not self.server_started:
            sleep(milliseconds(10))
        sleep(milliseconds(100))
コード例 #15
0
ファイル: sound.py プロジェクト: alfredr/python-sfml
def play_music():
    # load an ogg music file
    music = sf.Music.from_file("data/orchestral.ogg")

    # display music informations
    print("orchestral.ogg:")
    print("{0} seconds".format(music.duration))
    print("{0} samples / sec".format(music.sample_rate))
    print("{0} channels".format(music.channel_count))

    # play it
    music.play()

    # loop while the music is playing
    while music.status == sf.Music.PLAYING:
        # leave some CPU time for other processes
        sf.sleep(sf.milliseconds(100))
コード例 #16
0
ファイル: sound.py プロジェクト: alfredr/python-sfml
def play_sound():
    # load a sound buffer from a wav file
    buffer = sf.SoundBuffer.from_file("data/canary.wav")

    # display sound informations
    print("canary.wav:")
    print("{0} seconds".format(buffer.duration))
    print("{0} samples / sec".format(buffer.sample_rate))
    print("{0} channels".format(buffer.channel_count))

    # create a sound instance and play it
    sound = sf.Sound(buffer)
    sound.play()

    # loop while the sound is playing
    while sound.status == sf.Sound.PLAYING:
        # leave some CPU time for other processes
        sf.sleep(sf.milliseconds(100))
コード例 #17
0
ファイル: server.py プロジェクト: Jijidici/python-sfml
	def on_get_data(self, chunk):
		# we have reached the end of the buffer and all audio data have been played : we can stop playback
		if self.offset >= len(self.samples) and self.has_finished:
			return False

		# no new data has arrived since last update : wait until we get some
		while self.offset >= len(self.samples) and not self.has_finished:
			sf.sleep(sf.milliseconds(10))

		# don't forget to lock as we run in two separate threads
		lock = threading.Lock()
		lock.acquire()

		# fill audio data to pass to the stream
		chunk.data = self.samples.data[self.offset*2:]

		# update the playing offset
		self.offset += len(chunk)

		lock.release()

		return True
コード例 #18
0
ファイル: media.py プロジェクト: shackra/thomas-aquinas
    def playsong(cls, songname, play_offset=0, loop=True):
        """ Reproduce determinada canción.

        'play_offset' indica la nueva posición donde comenzara a
        sonar la musica. Esto se aplica DESPUÉS de iniciar la reproducción.
        el tiempo se expresa en milisegundos.
        'loop' al ser falso, reproduce la musica una sola vez. de lo contrario
        reproducirá la canción por siempre en bucle.
        """
        if hasattr(cls.actualsong, "play"):
            # tiene el volumen en 0 la canción actual?
            if cls.actualsong == 0:
                # detenemos la canción y le restablecemos el volumen
                cls.actualsong.stop()
                cls.actualsong.volume = 100.0

        try:
            cls.actualsong = cls.songs[songname]
            cls.actualsong.loop = loop
            cls.actualsong.play()
            cls.actualsong.playing_offset = sfml.milliseconds(play_offset)
        except KeyError:
            logging.exception("Canción {0} no a "
                              "sido cargada o no existe".format(songname))
コード例 #19
0
 def set_fps(self, fps):
     self._fps = fps
     self._frame_time = sf.milliseconds(1000 / self._fps)
コード例 #20
0
	def set_fps(self, fps):
		self._fps = fps
		self._frame_time = sf.milliseconds(1000 / self._fps)
コード例 #21
0
ファイル: network.py プロジェクト: wojtex/dvd-project-yellow
    def _work(self):
        while self.working:
            if self.selector.wait(sf.milliseconds(100)):
                clients_to_remove = set()
                unaccepted_to_remove = set()
                for client_id, data in self.clients.items():
                    if self.selector.is_ready(data.socket):
                        try:
                            if data.current_packet_size == -1:
                                if data.receive_to_buffer(_packet_length_size):
                                    msg = data.buffer
                                    data.buffer = b''
                                    data.current_packet_size = struct.unpack('I', msg)[0]
                            else:
                                if data.receive_to_buffer(data.current_packet_size):
                                    msg = data.get_buffer()
                                    module, packet = pickle.loads(msg)
                                    handler = self.query_handlers.get(module)
                                    if handler and \
                                            (not self.permission_checker or self.permission_checker(client_id, module)):
                                        result = handler(client_id, packet)
                                    else:
                                        result = None
                                    # send result
                                    # channel 0 => response to query
                                    msg = pickle.dumps((0, result))
                                    data.socket.send(struct.pack('I', len(msg)))
                                    data.socket.send(msg)
                                    data.current_packet_size = -1
                        except net.SocketDisconnected:
                            if self.disconnect_handler:
                                self.disconnect_handler(client_id)
                            self.selector.remove(data.socket)
                            clients_to_remove.add(client_id)

                for client_id, data in self.unaccepted.items():
                    if self.selector.is_ready(data.socket):
                        try:
                            if data.receive_to_buffer(_hello_message_size):
                                msg = data.get_buffer()
                                if msg[:len(_hello_message)] == _hello_message:
                                    try:
                                        api_version = int(pickle.loads(msg[len(_hello_message):]))
                                        if self.api_version_checker(api_version):
                                            data.socket.send(_accept_message.ljust(_hello_message_size, b'\x00'))
                                            self.clients[client_id] = data
                                            data.current_packet_size = -1
                                            unaccepted_to_remove.add(client_id)
                                            if self.accept_handler:
                                                self.accept_handler(client_id)
                                        else:
                                            data.socket.disconnect()
                                            self.selector.remove(data.socket)
                                            unaccepted_to_remove.add(client_id)
                                    except TypeError:
                                        data.socket.disconnect()
                                        self.selector.remove(data.socket)
                                        unaccepted_to_remove.add(client_id)
                                else:
                                    data.socket.disconnect()
                                    self.selector.remove(data.socket)
                                    unaccepted_to_remove.add(client_id)
                        except net.SocketDisconnected:
                            self.selector.remove(data.socket)
                            unaccepted_to_remove.add(client_id)

                for client_id in clients_to_remove:
                    del self.clients[client_id]

                for client_id in unaccepted_to_remove:
                    del self.unaccepted[client_id]

                if self.selector.is_ready(self.listener):
                    socket = self.listener.accept()
                    client_id = next(self.id_generator)
                    self.unaccepted[client_id] = _ClientData(client_id, socket)
                    self.selector.add(socket)
コード例 #22
0
            lives = 5
            enemies = []
            bullets = []
            blasts = []
            player.position = (50, window.size.y / 2)
            game_state = 1
        window.clear(sfml.Color(0, 128, 255))
        window.draw(title_text)
        alpha = int(
            math.fabs((blink_clock.elapsed_time.milliseconds %
                       blink_interval) - blink_interval / 2) / blink_interval *
            2 * 255)
        press_space_text.color = sfml.Color(255, 255, 255, alpha)
        window.draw(press_space_text)
        window.display()
        sfml.system.sleep(sfml.milliseconds(20))

    # Game
    elif game_state is 1:
        # Handle player input
        if sfml.Keyboard.is_key_pressed(sfml.Keyboard.UP):
            player.move((0, -player_speed))
        if sfml.Keyboard.is_key_pressed(sfml.Keyboard.DOWN):
            player.move((0, player_speed))
        if sfml.Keyboard.is_key_pressed(sfml.Keyboard.LEFT):
            player.move((-player_speed, 0))
        if sfml.Keyboard.is_key_pressed(sfml.Keyboard.RIGHT):
            player.move((player_speed, 0))
        # Fire!
        if sfml.Keyboard.is_key_pressed(
                sfml.Keyboard.SPACE
コード例 #23
0
    if game_state is 0:
        if sfml.Keyboard.is_key_pressed(sfml.Keyboard.SPACE):
            score = 0
            lives = 5
            enemies = []
            bullets = []
            blasts = []
            player.position = (50, window.size.y/2)
            game_state = 1
        window.clear(sfml.Color(0,128,255))
        window.draw(title_text)
        alpha = int(math.fabs((blink_clock.elapsed_time.milliseconds % blink_interval) - blink_interval/2)/blink_interval*2*255)
        press_space_text.color = sfml.Color(255, 255, 255, alpha)
        window.draw(press_space_text)
        window.display()
        sfml.system.sleep(sfml.milliseconds(20))

    # Game
    elif game_state is 1:
        # Handle player input
        if sfml.Keyboard.is_key_pressed(sfml.Keyboard.UP):
            player.move((0, -player_speed))
        if sfml.Keyboard.is_key_pressed(sfml.Keyboard.DOWN):
            player.move((0, player_speed))
        if sfml.Keyboard.is_key_pressed(sfml.Keyboard.LEFT):
            player.move((-player_speed, 0))
        if sfml.Keyboard.is_key_pressed(sfml.Keyboard.RIGHT):
            player.move((player_speed, 0))
        # Fire!
        if sfml.Keyboard.is_key_pressed(sfml.Keyboard.SPACE) and fire_clock.elapsed_time.milliseconds > fire_cooldown:
            blast = sfml.Sprite(blast_tx)