def prepare(): """ Initialise sound module. """ audio.plugin_dict['pygame'] = AudioPygame if pygame: # must be called before pygame.init() if mixer: mixer.pre_init(sample_rate, -mixer_bits, channels=1, buffer=1024) #4096
def todo_test_pre_init__keyword_args(self): # Fails on Mac; probably older SDL_mixer ## Probably don't need to be so exhaustive. Besides being slow the repeated ## init/quit calls may be causing problems on the Mac. ## configs = ( {'frequency' : f, 'size' : s, 'channels': c } ## for f in FREQUENCIES ## for s in SIZES ## for c in CHANNELS ) configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}] for kw_conf in configs: mixer.pre_init(**kw_conf) mixer.init() mixer_conf = mixer.get_init() self.assertEquals( # Not all "sizes" are supported on all systems. (mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]), (kw_conf['frequency'], abs(kw_conf['size']), kw_conf['channels']) ) mixer.quit()
def init(): """ Must be called before pygame.init() to enable low latency sound """ # reduce sound latency. the pygame defaults were ok for 2001, # but these values are more acceptable for faster computers if _pygame: mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=512)
def main(): intervals = {'major 2nd': 2, 'minor 3rd': 3, 'major 3rd': 4, 'perfect 4th': 5, 'perfect 5th': 7} interval_lookup = {} for key, val in intervals.copy().iteritems(): # We don't want to modify the dict we're iterating though interval_lookup[val] = key # Add the reverse to the dict used_tones = [False] * 12 notes = len(Note.chromatic) tune = [] def prev_interval(): """Return the most recent interval""" previous_interval = (tune[-2] - tune[-1]) % notes # interval might not be in intervals if previous_interval in interval_lookup: previous_interval = interval_lookup[previous_interval] return previous_interval def get_new_note(pitch, interval=None): """This is embedded so we don't need to pass in used_tones. Checks that the note is valid otherwise it picks a new note and sets it as used""" if interval is not None: pitch = (pitch + interval) % len(Note.chromatic) if used_tones[pitch] is True and False in used_tones: pitch = rand_choice([i for i, used in enumerate(used_tones) if used is False]) used_tones[pitch] = True return pitch tune.append(get_new_note(randint(0, notes - 1))) tune.append(get_new_note(tune[-1], rand_choice(intervals.values()))) while False in used_tones: # intelligently choose a new pitch based on the interval between the # previous two note = get_new_note(randint(0, notes - 1)) if randint(1, 4) > 1: # 1 in 4 chance for a random note if prev_interval() == 'major 3rd': # if the previous interval was a minor 3rd, attempt to follow # it with a major 2nd # mod is used to stay in the octave note = get_new_note(tune[-1], intervals['major 2nd']) elif prev_interval == 'perfect 4th': # if the previous interval was a major 3rd, attempt to follow # by going down a minor 3rd note = get_new_note(tune[-1], -1* intervals['major 3rd']) tune.append(note) mixer.pre_init(44100, -16, 1, 1024) pygame.init() play_tune([Note.chromatic[note] for note in tune]) pygame.quit()
def __init__(self, delegate): super(SoundController, self).__init__() self.logger = logging.getLogger('game.sound') try: mixer.pre_init(44100,-16,2,2048) mixer.init() except Exception, e: # The import mixer above may work, but init can still fail if mixer is not fully supported. self.enabled = False self.logger.error("pygame mixer init failed; sound will be disabled: "+str(e))
def todo_test_init__zero_values(self): # Ensure that argument values of 0 are replaced with # preset values. No way to check buffer size though. mixer.pre_init(44100, 8, 1) # None default values mixer.init(0, 0, 0) try: self.failUnlessEqual(mixer.get_init(), (44100, 8, 1)) finally: mixer.quit() mixer.pre_init(0, 0, 0, 0)
def main(): mixer.pre_init(44100, -16, 2, 1024) #sound effects are delayed on my windows machine without this, I think the buffer is initialized too large by default pygame.init() if android: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) while True: screen = get_screen() pygame.display.set_caption(TITLE) pygame.display.set_icon(load_image(os.path.join('blocks', 'lightgreen.png'))) menu = Menu(screen)
def init_mixer(): """ Check that the mixer's initialized and initialize it if not. """ # Check PyGame is available # This will raise an error if it's not check_pygame() from pygame import init, mixer # Set the mixer settings before initializing everything mixer.pre_init(frequency=44100) init()
def __init__(self, music_directory): """ Initialize the MusicPlayer with the music in the given directory. Needs to be called before pygame.init(). """ self.music_directory = music_directory songs = self.get_list_of_songs(self.music_directory) if (len(songs) <= 0): print("Please place a .wav file in the directory %s" % directory) # Initialize mixer with correct frame rate mixer.pre_init(self.get_frame_rate(music_directory + '/' + songs[0]))
def init_sound(experiment): print( u"openexp.sampler._legacy.init_sound(): sampling freq = %d, buffer size = %d" \ % (experiment.sound_freq, experiment.sound_buf_size)) if hasattr(mixer, u'get_init') and mixer.get_init(): print( u'openexp.sampler._legacy.init_sound(): mixer already initialized, closing') pygame.mixer.quit() mixer.pre_init(experiment.sound_freq, experiment.sound_sample_size, \ experiment.sound_channels, experiment.sound_buf_size) mixer.init()
def init_sound(experiment): """ Initializes the pygame mixer before the experiment begins. Arguments: experiment -- An instance of libopensesame.experiment.experiment """ print "openexp.sampler._legacy.init_sound(): sampling freq = %d, buffer size = %d" \ % (experiment.sound_freq, experiment.sound_buf_size) if hasattr(mixer, 'get_init') and mixer.get_init(): print 'openexp.sampler._legacy.init_sound(): mixer already initialized, closing' pygame.mixer.quit() mixer.pre_init(experiment.sound_freq, experiment.sound_sample_size, \ experiment.sound_channels, experiment.sound_buf_size) mixer.init()
def __init__(self,game,priority=10): super(SoundController, self).__init__(game,priority) self.logger = logging.getLogger('game.sound') try: mixer.pre_init(frequency=22050, size=-16, channels=2, buffer=256) #256 prev mixer.init() mixer.set_num_channels(8) self.queue=deque() #for queing up quotes mixer.set_reserved(CH_MUSIC_1) mixer.set_reserved(CH_MUSIC_2) mixer.set_reserved(CH_VOICE) #mixer.Channel(CH_VOICE).set_endevent(pygame.locals.USEREVENT) -- pygame event queue really needs display and cause a ton of issues, creating own except Exception, e: self.logger.error("pygame mixer init failed; sound will be disabled: "+str(e)) self.enabled = False
def __init__(self): try: #Inicilializo el modulo para ejecutar sonidos if sys.platform.find('win') != -1: mixer.pre_init(44100,16,1,4096) else: mixer.pre_init(44100) mixer.init() self.__canal = mixer.find_channel() self.__cola = [] self.__ejecutando_sonidos = False self.__end_sound_event = False self.__new_sound_event = False self.__escuchar = True self.__sonido_actual = "" self.SILENCE_CHANNEL = USEREVENT + 4 self.nombre_grupo_sonido = "" except pygame.error, e: raise Exception("ERROR!: " + str(e) + ", al inicilizar el video. La aplicacion se cerrara")
def __init__(self, volume): mixer.pre_init(44100, -16, 2, 1024) mixer.init() self.menuSound = normpath("sounds/theme.mp3") self.gameSound = normpath("sounds/gameTheme.mp3") self.successSound = mixer.Sound(normpath("sounds/success.wav")) self.failureSound = mixer.Sound(normpath("sounds/failure.wav")) self.victorySound = mixer.Sound(normpath("sounds/victory.wav")) self.currSound = self.menuSound self.volumeLevel = volume self.setVolume(self.volumeLevel) mixer.music.load(self.menuSound)
def __init__(self): """Initializes player in this order: External libraries Data attributes Populating data attributes """ threading.Thread.__init__(self) pygame.init() mixer.pre_init(44100, -16, 2, 2048) # frequency, size, channels, buffersize mixer.music.set_endevent(SONG_END) self.isPaused = False self.isStopped = False self.isOnDrakeToday = True self.Files = [] self.CurrentPosition = 0 self.__loadFiles() self.TotalFiles = len(self.Files)
def __init__(self, audio_queue, **kwargs): """Initialise sound system.""" if not pygame: raise InitFailed('Module `pygame` not found') if not numpy: raise InitFailed('Mdoule `numpy` not found') if not mixer: raise InitFailed('Module `mixer` not found') # this must be called before pygame.init() in the video plugin mixer.pre_init( synthesiser.SAMPLE_RATE, -synthesiser.SAMPLE_BITS, channels=1, buffer=BUFSIZE ) # synthesisers self.signal_sources = synthesiser.get_signal_sources() # sound generators for each voice self.generators = [deque(), deque(), deque(), deque()] # do not quit mixer if true self._persist = False # keep track of quiet time to shut down mixer after a while self.quiet_ticks = 0 AudioPlugin.__init__(self, audio_queue)
def __init__(self, audio_queue): """Initialise sound system.""" if not pygame: logging.warning('PyGame module not found. Failed to initialise PyGame audio plugin.') raise base.InitFailed() if not numpy: logging.warning('NumPy module not found. Failed to initialise PyGame audio plugin.') raise base.InitFailed() if not mixer: logging.warning('PyGame mixer module not found. Failed to initialise PyGame audio plugin.') raise base.InitFailed() # this must be called before pygame.init() in the video plugin mixer.pre_init(synthesiser.sample_rate, -synthesiser.sample_bits, channels=1, buffer=1024) #4096 # synthesisers self.signal_sources = synthesiser.get_signal_sources() # sound generators for each voice self.generators = [deque(), deque(), deque(), deque()] # do not quit mixer if true self._persist = False # keep track of quiet time to shut down mixer after a while self.quiet_ticks = 0 base.AudioPlugin.__init__(self, audio_queue)
def init(): if os.name == 'posix': # We need to force stereo in many cases. try: mixer.pre_init(44100, -16, 2) except pygame.error: pass pygame.init() config.init(rc_file) os.chdir(angrydd_path) pygame.display.set_caption("Angry, Drunken Programmers") try: pygame.display.set_icon(pygame.image.load("angrydd.png")) except pygame.error: pass pygame.mouse.set_visible(False) if config.getboolean("settings", "fullscreen"): flags = FULLSCREEN else: flags = 0 pygame.display.set_mode([800, 600], flags) import game import menu import boxes import characters boxes.TickBox.sound = load.sound("tick.wav") boxes.TickBox.sound.set_volume(0.3) boxes.BreakBox.sound = load.sound("break.wav") boxes.BreakBox.sound.set_volume(0.3) boxes.Special.sound = load.sound("select-confirm.wav") boxes.Special.sound.set_volume(0.5) game.FallingBoxes.rotate_sound = load.sound("rotate.wav") game.FallingBoxes.rotate_sound.set_volume(0.2) menu.Menu.bg = load.image("menu-bg.png").convert() characters.init() mixer.music.load(os.path.join("music", "intro.ogg")) mixer.music.play(-1)
import pygame import math, random from pygame import mixer import sys ############################ pygame.init() #mixer.init() mixer.pre_init(frequency=4410, size=16, channels=1, buffer=512) width = 300 height = 400 screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() pygame.display.set_caption('Snake Game') font1 = pygame.font.SysFont('arial', 35) font2 = pygame.font.SysFont('arial', 50) ############ SOUNDS ############ #provide appropriate path score_sound = mixer.Sound( 'D:\Python program\games\FLAPPY_BIRD\sound\sfx_point.wav') death_sound = mixer.Sound( 'D:\Python program\games\FLAPPY_BIRD\sound\sfx_hit.wav') ############## FUNCTIONS ############### def myText(text): screenText = font1.render(text, True, white) screen.blit(screenText, (90, 5))
import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 import pymysql pymysql.install_as_MySQLdb() import MySQLdb db = MySQLdb.connect("118.42.88.117", "root", "qwer1234", "NIC") cur = db.cursor() #mySQL Query list update_true = "UPDATE module SET wait=1" update_false = "UPDATE module SET wait=0" getData = "SELECT play FROM module" setPlay = "UPDATE module SET play=0" mixer.pre_init(44100, -16, 2, 256) mixer.init(frequency=16000, buffer=24000) CLK = 18 MISO = 23 MOSI = 24 CS = 25 mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI) port_num = 6 state = False print('Program start.. press Ctrl-C to quit...') # get Value Func def getValue(num):
# -*- coding:utf-8 -*- from pygame.sprite import Sprite, collide_rect from pygame import Surface, mixer import pyganim mixer.pre_init(44100, -16, 1, 512) mixer.init() MOVE_SPEED = 7 JUMP_POWER = 10 GRAVITY = 0.4 COLOR = (10, 120, 10) ANIMATION_DELAY = 0.1 ANIMATION_STAY = [('images/hero/hero.png', ANIMATION_DELAY)] ANIMATION_RIGHT = ['images/hero/hero_right1.png', 'images/hero/hero_right2.png', 'images/hero/hero_right3.png'] ANIMATION_LEFT = ['images/hero/hero_left1.png', 'images/hero/hero_left2.png', 'images/hero/hero_left3.png'] ANIMATION_UP = ['images/hero/hero_up1.png', 'images/hero/hero_up2.png', 'images/hero/hero_up3.png', 'images/hero/hero_up4.png'] class Player(Sprite): def __init__(self, x, y):
subMenu3 = Menu(menuBar, tearoff=0) menuBar.add_cascade(label='Sample Rate', menu=subMenu3) subMenu3.add_command(label='22.05 kHz', command=partial(set_frequency, 22050)) subMenu3.add_command(label='44.1 kHz', command=partial(set_frequency, 44100)) subMenu3.add_command(label='48 kHz', command=partial(set_frequency, 48000)) subMenu3.add_command(label='96 kHz', command=partial(set_frequency, 96000)) # Create the fourth subMenu subMenu4 = Menu(menuBar, tearoff=0) menuBar.add_cascade(label='Help', menu=subMenu4) subMenu4.add_command(label='About', command=about) # initilizing the mixer mixer.pre_init(frequency=chosen_frequency) mixer.init() # ============ Creating the left frame ================= left_frame = Frame(root) left_frame.grid(column=0, row=0) song_list_box = Listbox(left_frame) song_list_box.grid(columnspan=2, row=0, padx=30) add_btn = ttk.Button(left_frame, text='Add', command=fileOpen) add_btn.grid(column=0, row=1) del_btn = ttk.Button(left_frame, text='Delete', command=delete_song) del_btn.grid(column=1, row=1)
import pygame import os from pygame import mixer pygame.init() mixer.pre_init(channels=12) mixer.init() # A list of all constants used in the game, you can change them at will (changing TILE_SIZE will change the saved # worlds in ways you probably don't want, so this is not advised) GRAVITY = 500 FPS = 60 SCREEN_SIZE = (1200, 600) TILE_SIZE = (15, 15) CAMERA_POS = (-300, -300) TIME_SPRITE_CHANGE = 0.075 TIME_SPRITE_CHANGE_PLAYER = 0.01 TIME_SPRITE_CHANGE_COINS = 0.07 SPEED_DOWN_FLAGPOLE = 150 SPEED_PLAYER = 100 JUMP_SPEED_PLAYER = 300 DUCK_SPEED_PLAYER = 450 SPEED_ENEMY = 60 SPEED_MUSHROOM = 60 SPEED_TURTLE = 120 INVULNERABLE_TIME = 0.6 FLAGPOLE_SIZE = (60, 150) GOOMBA_SECONDS_REMOVED_AFTER_DEATH = 1 SPRITE_PATH = os.path.join("assets", "sprites")
def __init__(self): mixer.init() mixer.pre_init(44100, -16, 2, 1024*4)
import math, random try: import android except ImportError: android = None VIBRATE = True SOUND = True if SOUND: try: import pygame.mixer as mixer except ImportError: import android.mixer as mixer mixer.pre_init(44100, -16, 2, 2048) mixer.init() BOP_SOUND = mixer.Sound('./sound/bop.ogg') DEATH_SOUND = mixer.Sound('./sound/death.ogg') def addVectors(v1, v2): """ Returns the sum of two vectors """ (angle1, length1) = (v1[0], v1[1]) (angle2, length2) = (v2[0], v2[1]) x = math.sin(angle1) * length1 + math.sin(angle2) * length2 y = math.cos(angle1) * length1 + math.cos(angle2) * length2 angle = 0.5 * math.pi - math.atan2(y, x) length = math.hypot(x, y)
import pygame import sys from Entity import * from Vector2 import Vector2 from random import randint, uniform from pygame import mixer # Init pygame libraries mixer.pre_init(22050, -16, 40, 4096 / 4) pygame.init() mixer.init() # Setup pygame window screen_size = (1280, 720) # Bits per pixel, 8 bits for each RGBA value. bpp = 32 screen = pygame.display.set_mode(screen_size, pygame.HWSURFACE, bpp) # Load some sound effects laser_shot_sfx = mixer.Sound("Assets/laser_shot.wav") hit_sfx = mixer.Sound("Assets/hit.wav") # Setup the player entity player = Entity() player.graphicsBounds.radius = 10 player.collider.radius = 10 player.position = Vector2(screen_size[0] / 2, screen_size[1] / 2) player.color = (255, 0, 0) player.max_speed = 200
} # Duracion de un punto cw = 0.05 LEFT = 1 running = 1 screen = pygame.display.set_mode((320, 200)) nopulsado = (time.clock()) letra = "" pulsado = 0 pre_init(22500, -8, 1, 1024) pygame.init() class Note(Sound): def __init__(self, frequency, volume=.1): self.frequency = 2*frequency # Eliminar el 2 si se usa sample rate de 44100 Sound.__init__(self, self.build_samples()) self.set_volume(volume) def build_samples(self): period = int(round(get_init()[0] / self.frequency)) samples = array("h", [0] * period)
from tkinter import * from sound_panel import * import pygame.mixer import os app = Tk() app.title('Head First Mix') mixer = pygame.mixer mixer.pre_init(buffer=300) mixer.init() dirList = os.listdir('.') for fname in dirList: #if fname.endswith('.wav') and fname[0] in '345': if fname.startswith('1Bla'): #if fname.endswith('aif'): SoundPanel(app, mixer, fname).pack() def shutdown(): mixer.stop() app.destroy() app.protocol('WM_DELETE_WINDOW', shutdown) app.mainloop()
sample_buffer[i] = int(round(sample_buffer[i] / len(samples))) # Add the wave LCMs (and normalize?) return array("h", sample_buffer) def play_tune(tune, time=0.5): """Make sure this class can play basic notes""" # change this to an array of notes. music = [Note(note) for note in tune] for note in music: note.play(-1, int(time * 1000)) # Loop until we hit our time print note.note, note.frequency, sleep(time) note.stop() def test(): """Make sure this class can play basic notes""" tune = ["A", "D", "D#", "B", "F#", ("G", "C", "E"), "Ab", ("E", "G", "C"), "F", "Bb", ("C", "E", "G"), "C#"] pygame.init() play_tune(tune) pygame.quit() if __name__ == "__main__": # Pre-set the sample freq per sec, size, number of channels, # and buffer size mixer.pre_init(44100, -16, 1, 2 ** 16) pygame.init() test()
from pygame import mixer from pygame.mixer import music import pyglet from pyglet.window import key import time import cocos mixer.pre_init(44100, -16, 2, 1024) mixer.init() # Make sure we exit the mixer when the application quits cocos.director.event_loop.push_handlers(on_exit=mixer.quit) def play(soundtrack): # music.load(bytes(os.path.join("assets", "music", soundtrack), 'utf-8')) music.load(soundtrack) music.play(loops=-1) def actions_play(soundtrack): music.load(soundtrack) music.play(loops=1) def pause(): music.pause() def mute_volume(m): music.set_volume(m)
def run(self): log.debug('pre-initializing sound') mixer.pre_init(buffer=32) log.debug('starting game') pygame.init() log.debug('initializing screen') self.screen = self._screen_init() log.debug('getting font') self.font = pygame.font.Font(None, 36) log.debug('loading background') self.background, self.background_rect = self._get_background() log.debug('setting up drop locations') self._board_space_setup() log.debug('building text') bg_rect = self.background_rect class FPSText(Text): def update(self, *args): Text.update(self, *args) self.rect.right, self.rect.bottom = bg_rect.right, bg_rect.bottom self.fps_text = FPSText('', self.font, WHITE) if self.show_fps: self.fg_text.add(self.fps_text) class TurnText(Text): def update(self, *args): Text.update(self, *args) self.rect.centerx, self.rect.centery = bg_rect.centerx, bg_rect.centery self.turn_text = TurnText('', self.font, WHITE) self.bg_text.add(self.turn_text) class WinnerText(Text): def update(self, *args): Text.update(self, *args) self.rect.centerx, self.rect.centery = bg_rect.centerx, bg_rect.centery self.winner_text = WinnerText('', self.font, WHITE) self.fg_text.add(self.winner_text) class PlayerText(Text): def update(self, *args): Text.update(self, *args) self.rect.centerx, self.rect.bottom = bg_rect.centerx, bg_rect.bottom self.player_text = PlayerText('', pygame.font.Font(None, 24), WHITE) self.bg_text.add(self.player_text) class GameIdText(Text): def update(self, *args): Text.update(self, *args) self.rect.centerx, self.rect.top = bg_rect.centerx, bg_rect.top + (0.25 * self.font.get_height()) self.game_id_text = GameIdText('', pygame.font.Font(None, 20), WHITE) self.bg_text.add(self.game_id_text) log.debug('drawing initial content to screen') self.screen.blit(self.background, ORIGIN) pygame.display.flip() self.piece_selected = GroupSingle() self.current_piece_position = ORIGIN self.fps_clock = Clock() # Event loop while self.game_running: self._clear_items() for event in pygame.event.get(): if event.type == QUIT: self._quit() if event.type == MOUSEBUTTONDOWN: # select a piece log.debug('mouse pressed') self._select_piece(event) if event.type == MOUSEBUTTONUP: # let go of a piece log.debug('mouse released') self._drop_piece(event) if pygame.event.get_grab(): # drag selected piece around self._drag_piece() self._update() self._draw_items() self.fps_clock.tick(60) # Waits to maintain 60 fps # TODO: Use display.update instead pygame.display.flip() log.debug('finishing game loop')
def tearDown(self): mixer.quit() mixer.pre_init(0, 0, 0, 0)
#!/usr/bin/env python from pygame import mixer import time print 'init' mixer.init() mixer.pre_init(44100, -16, 2, 2048) mixer.music.load("/var/www/tabor/media/01.mp3") mixer.music.play() print 'playing' while True: time.sleep(0.2)
freq = frequency / abs( self.freq_transpose) #frequency/abs(self.freq_transpose) elif self.freq_transpose > 0: freq = frequency * abs(self.freq_transpose) else: freq = frequency print(freq) sample_rate = pygame.mixer.get_init()[0] period = int(round(sample_rate / freq)) amplitude = 2**(abs(get_init()[1]) - 1) - 1 def frame_value(i): return amplitude * self._wave_func( 2.0 * np.pi * freq * i / sample_rate) return np.array([frame_value(x) for x in range(0, period)]).astype(np.int16) if __name__ == "__main__": for note in Notes: print(round(note.freq % 12)) pre_init(44100, -16, 2, 8192) #pygame.init() pygame.mixer.init() o = Oscillator(Waveform.square, volume=0.25) o.play_osillator([Notes.C5, Notes.E5, Notes.G5, Notes.C6])
def init(): mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=512) mixer.init() print()
def main(): global PLAY_STATE PLAY_STATE = True # Initialize the sound mixer.pre_init() mixer.init() # Load the sounds # Set this to the directory you installed the app in chimedir = "/home/pi/Chimes/" # Download the chime sounds you want to use and rename # these sound file names to match your sounds. global qh qh = mixer.Sound("%sQuarterHourChime.wav" % chimedir) global hh hh = mixer.Sound("%sHalfHourChime.wav" % chimedir) global tqh tqh = mixer.Sound("%s3QuarterChime.wav" % chimedir) global hc hc = mixer.Sound("%sHourChime.wav" % chimedir) global hcc hcc = mixer.Sound("%sHourCountChime.wav" % chimedir) global ChimeVolume ChimeVolume = 40 set_volume(ChimeVolume) # Initialize the buttons GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) for pin in audio_config: GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(pin, GPIO.FALLING, callback=gpio_event, bouncetime=150) # Initialize the weather global temp temp = weather.get_temperature() if temp < -100: temp = 0 # Initialize the image # Download the image you want to use as a backgroound # and rename this variable appropriately. image_file = f"{chimedir}/bigben.jpg" # Change this to point at the font yuou want to use FONT = "pygame/examples/data/sans.ttf" ttf = ImageFont.truetype( FONT, 50, ) dttf = ImageFont.truetype( FONT, 40, ) # Create ST7789 LCD display class. disp = ST7789.ST7789( rotation=90, port=0, cs=1, dc=9, backlight=13, spi_speed_hz=90000000, ) # Initialize display. disp.begin() WIDTH = disp.width HEIGHT = disp.height # Load an image. image = Image.open(image_file) # Resize the image and display the initial clock image = image.resize((WIDTH, HEIGHT)) draw = ImageDraw.Draw(image) curtime = localtime() ap = "AM" if curtime.tm_hour < 12 else "PM" hour = curtime.tm_hour % 12 if hour == 0: hour = 12 fahr = int((temp * 9.0) / 5.0) + 32 draw.text((20, 170), f"{fahr}F {temp:.1f}C", font=dttf) draw.text((15, 90), f"{hour:02}:{curtime.tm_min:02} {ap}", font=ttf) date = localtime() # People outside the US will want to change this format draw.text( (20, 20), f"{date.tm_mon:02}/{date.tm_mday:02}/{date.tm_year}", font=dttf, ) disp.display(image) while True: image = Image.open(image_file) image = image.resize((WIDTH, HEIGHT)) draw = ImageDraw.Draw(image) while localtime().tm_sec > 0: sleep(1) curtime = localtime() hour = curtime.tm_hour % 12 minute = curtime.tm_min ap = "AM" if curtime.tm_hour < 12 else "PM" if hour == 0: hour = 12 fahr = int((temp * 9.0) / 5.0) + 32 draw.text((30, 170), f"{fahr}F {temp:.1f}C", font=dttf) draw.text((15, 90), f"{hour:02}:{minute:02} {ap}", font=ttf) date = localtime() # People outside the US will want to change this format draw.text( (20, 20), f"{date.tm_mon:02}/{date.tm_mday:02}/{date.tm_year}", font=dttf, ) disp.display(image) if minute % 15 == 2 and "chimeThread" in locals(): chimeThread.join(1.0) # noqa: F821 del chimeThread if minute % 15 == 0: chimeThread = Thread(target=play_chimes, args=(hour, minute)) chimeThread.start() sleep(2)
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import pygame from pygame.mixer import Sound, get_init, pre_init from array import array from time import sleep from enum import Enum from random import randint pre_init(44100, -16, 1, 2048) successes, failures = pygame.init() font1 = pygame.font.SysFont("monospace", 16) font2 = pygame.font.SysFont("monospace", 32) clock = pygame.time.Clock() # Colours for the game BLACK = (0, 0, 0) WHITE = (255, 255, 255) LIGHT_RED = (255, 99, 71) RED = (255, 0, 0) DARK_RED = (139, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255)
def playSound(hz,ms): pre_init(44100, -16, 1, 1024) Note(hz).play(ms)
if 'brexit' in text: greeting = random.choice(GREETINGS) phrase = random.choice(PHRASES) say(f'{greeting} {phrase}') return response def say(words): with NamedTemporaryFile(suffix='.mp3') as mp3_fp: tts = gTTS(text=words, lang='en') tts.write_to_fp(mp3_fp) mp3_fp.flush() mixer.music.load(mp3_fp.name) mixer.music.play() while mixer.music.get_pos() > -1: time.sleep(0.2) if __name__ == "__main__": mixer.pre_init(25000, 16, 2) mixer.init() # create recognizer and mic instances recognizer = sr.Recognizer() microphone = sr.Microphone() say("Hi, I'm Brexa. What would you like to know?") guess = recognize_speech_from_mic(recognizer, microphone)
player1_y_start = int(ct.WINDOW_HEIGHT / 2) player2_x_start = ct.WINDOW_WIDTH - ct.PONG_BAR_WALL_PADDING player2_y_start = player1_y_start player1 = Player( "Krystof", 1, (player1_x_start, player1_y_start )) # Create players objects with initial position (paddle's center) player2 = Player("Maciej", 2, (player2_x_start, player2_y_start)) player1_move_step = 0 # move velocity - ONLY FOR KEYBOARD player2_move_step = 0 # Create a ball ball = Ball(ct.BALL_RADIUS) # create a ball of defined radius # Load sounds mixer.pre_init() mixer.init(size=-8, channels=1, buffer=512) bounce_sound = mixer.Sound("sounds/bounce.wav") # Draw player's paddle on a new position def move_player(player, x, y): # player object, pos-x, pos-y # Save new position and get its UL corner coordinates player.position = [x, y] # save player's new position (paddle's center) corner_position = player.get_corner_position() # get UL corner coords # Keep players inside the window corner_position[1] = max( 0, corner_position[1]) # make sure y stays above 0 (screen boundary) corner_position[1] = min( corner_position[1], ct.WINDOW_HEIGHT -
def set_frequency(rate): state['frequency'] = rate print('The new frecuency should be : ', rate) mixer.quit() mixer.pre_init(frequency=state['frequency']) mixer.init() # initilizing the mixer
def pre_init(): mixer.pre_init(22050, -16, 2, 2048)
def __init__(self, frequency=44100, size=-16, channels=4, buffer=4096): mixer.pre_init(frequency, size, channels, buffer) global GENERAL_VOLUME global SOUND_VOLUME global MUSIC_VOLUME
#!/usr/bin/env python ## Sound - part of the Penuine game engine # Controls sound loading and playback in-game # Copyright David Barker 2008 # # Update history: # Created - Monday 17th December 2007, by David Barker # Version 1.0 finished - Wednesday 13th February 2008 import pygame from pygame import mixer mixer.pre_init(22050, -16, 2, 512) # Buffer size (last argument) has been fiddled with, with little effect mixer.init() class MusicPlayer(): """ A class that plays music from a given file. This takes one argument; "filepath", which is the filepath of the *.OGG format music to play. """ def __init__(self, filepath): """ Initialise the music player. """ self.channel = pygame.mixer.Channel(7) self.music = mixer.Sound(filepath) self.playmode = "" self.paused = 0 def Play(self):
if len(Tune.tune_schedule) > 0: now = time() for i, note in enumerate(Tune.tune_schedule): if note[0] <= now: play_now.append(note) if len(play_now) > 0: for note_to_push in play_now: _, freq, dur, spd = note_to_push Note(freq, 0.5).play(int((freq*dur)/spd)) for to_remove in play_now: Tune.tune_schedule.remove(to_remove) if __name__ == "__main__": pre_init(44100, -16, 1, 1024) pygame.init() tune = Tune() tune.sequence_a = ['c1n','d1n','c1n','e1n','e1n','d1n','c1n', 'c1n','d1n','c1n','e1n','e1n','d1n','c1n', 'f1n','g1n','f1n','a2n','a2n','g1n','f1n', 'c1n','d1n','c1n','e1n','e1n','d1n','c1n', 'g1n','a2n','g1n','b2n','b2n','a2n','g1n', 'a2n','a2n','g1n','f1n','f1n','e1n','d1n','c1n'] tune.sequence_b = ['c1n','d1n','c1n','d1+','d1+','d1n','c1n', 'c1n','d1n','c1n','d1+','d1+','d1n','c1n', 'f1n','g1n','f1n','g1+','g1+','g1n','f1n', 'c1n','d1n','c1n','d1+','d1+','d1n','c1n', 'g1n','a2n','g1n','a2+','a2+','a2n','g1n', 'g1+','g1+','g1n','f1n','f1n','d1+','d1n','c1n'] tune.lengths = [0.6, 0.6, 0.6, 0.3, 1.2, 0.6, 5.4,
def _init_pygame(self): logging.info("INFO: loading pygame mixer") mixer.pre_init(44100, -16, 2, 1024) mixer.init()
else: samples[time] = -amplitude return samples chunk = 2048 CHANNELS = 1 RECORD_SECONDS = 0.1 frequency = 23000 p = PyAudio.PyAudio() stream = p.open(format=p.get_format_from_width(1), # 8bit channels=1, # mono rate=96000, input=True, output=False, frames_per_buffer=chunk) pre_init(96000, -16, 1, 1024) pygame.init() best_frequency = 0 amplitude = 0 #msgbox(msg="First, I need to tune.", title="", ok_button="Begin!") for frequency in range(22700,23500,5): data=stream.read(6048) Note(frequency).stop() Note(frequency).play(-1) sleep(0.05) print(audioop.maxpp(data,2))
def __init__(self): PM.pre_init(44100, -16, 1, 1024) PG.init() ###(Screen stuff)#### Globals.SCREEN.fill((255, 255, 255)) PD.set_caption("Master Chef's wicked adventure " + "with his ice cream buddies") ###(Declare interface)##### self.font = PF.SysFont('Arial', 25) #Win/Lose items self.end_time = 100 self.win_image = PI.load("FPGraphics/" + "specialEffects/UWIN.png").convert_alpha() self.lose_image = PI.load("FPGraphics/" + "specialEffects/ULOSE.png").convert_alpha() self.MAX_LEVEL = 4 self.MAX_STAGE = 2 #items self.pill_img = PI.load("FPGraphics/tiles/" + "lactasePill.png").convert_alpha() ######(Initialize objects on screen)#### ##draw map/background ##draw sprites self.character = Player(Globals.DELTA) self.INVINCIBILITY_TIME = Globals.DEFAULT_INVINCIBILITY self.player_group = PS.GroupSingle(self.character) # adding extra since cutscene bug deletes one # self.remainingEnemies = self.num_enemies #create icecream group self.icecream_list = PS.Group() self.burger_list = PS.Group() self.egg_list = PS.Group() self.lettuce_list = PS.Group() self.cupcake_list = PS.Group() self.enemy_list = PS.Group() # all enemies self.pad_list = PS.Group() self.trap_group = PS.Group() self.item_group = PS.Group() self.projectile_group = PS.Group() self.enemies = None #allsprites has all dirty sprites (player, enemies, traps, pads) self.allsprites = PS.LayeredDirty(self.trap_group, self.pad_list, self.item_group, self.player_group, self.icecream_list, self.burger_list, self.egg_list, self.lettuce_list, self.cupcake_list, self.projectile_group) #variables to be handled in change_level method self.objective = None self.objectiveBlit = True self.updated_obj = False self.map = None self.num_enemies = 0 self.background = None self.end_time = 100 self.end_image_position = (100, 178) self.block_group = None ####(Level variables)#### Globals.INVINCIBILITY_COUNT = 0 # player's invinicibility frame time #what kind of enemy by ID (-1 means no enemy) used for collisions self.enemy_ID = -1 #if true, tells map to redraw self.map_modified = False # self.level = 1 # self.stage = 1 self.level = 1 self.stage = 1 self.change_level(self.level, self.stage) self.burn_player = False ####Joystick######### self.joy = Joystick() self.use_joy = str(inbx.ask(Globals.SCREEN, 'Joystick? y/n')) self.score_health_background = PI.load("FPGraphics/specialEffects/ScoreHealth.png").convert_alpha() self.items_table = PI.load("FPGraphics/specialEffects/ItemsTable.png").convert_alpha()
#!/usr/bin/python # basado en # http://lists.canonical.org/pipermail/kragen-hacks/2007-November/000465.html from pygame import mixer, sndarray, time, init from Numeric import arange, Int16, sin, pi tasa = 22050 # de muestreo mixer.pre_init(tasa, -16, 1) # 16bit, un canal init() # necesario para mixer hz, pico, n_muestras = 440, 16384, tasa theta = arange(n_muestras) * (2*pi * hz / tasa) sndarray.make_sound((pico * sin(theta)).astype(Int16) ).play(-1, 0, 20) # 20ms fadein time.wait(1000) # un segundo
@app.route('/changeSound') def changeSound(): soundId = int(request.args['soundId']) print("soundId = {}".format(soundId)) audioFile = audioFiles[soundId] playAudioFile(audioFile) return "" if __name__ == "__main__": # List audio files audioDir = "./audio" audioFiles = [ os.path.join(audioDir, f) for f in os.listdir(audioDir) if os.path.splitext(f)[1] == ".mp3" ] # Initialize pygame music mixer mixer.pre_init(44100, -16, 2, 4096) mixer.init( ) # Pygame inits must be called on main thread. Flask app seems to run in a separate thread. with app.app_context(): # Start playing the first file playAudioFile(audioFiles[0]) mixer.music.set_volume(0.5) # Run the webserver app.run(host='0.0.0.0', port='8080')
'.-.-': '' } # Duracion de un punto cw = 0.05 LEFT = 1 running = 1 screen = pygame.display.set_mode((320, 200)) nopulsado = (time.clock()) letra = "" pulsado = 0 pre_init(22500, -8, 1, 1024) pygame.init() class Note(Sound): def __init__(self, frequency, volume=.1): self.frequency = 2 * frequency # Eliminar el 2 si se usa sample rate de 44100 Sound.__init__(self, self.build_samples()) self.set_volume(volume) def build_samples(self): period = int(round(get_init()[0] / self.frequency)) samples = array("h", [0] * period) amplitude = 2**(abs(get_init()[1]) - 1) - 1 for time in xrange(period): if time < period / 2:
from pygame import mixer from pygame import time import sys mixer.pre_init() mixer.init(frequency=16000,channels=1,size=-16,buffer=4096) mixer.music.load('/home/shikw/Design/Develop/Audio/'+str(sys.argv[1])+'.mp3') mixer.music.play() while mixer.music.get_busy(): time.Clock().tick(10)
from luma.core.render import canvas from luma.core.interface.serial import i2c from luma.oled.device import ssd1306 from PIL import ImageFont import time import datetime from pygame import mixer serial = i2c(port=0, address=0x3C) device = ssd1306(serial) running = True mixer.pre_init(22050, -8, 2, 512, None) mixer.init() font = ImageFont.load_default() bpm = 1 stepscount = 8 path = 'samples/' patterns = [] class Track: name = '' steps = [] audio = None def __init__(self, name): self.name = name class Pattern:
if __name__ != '__main__': from pygame.mixer import Sound from pygame import mixer mixer.pre_init(44100, -16, 1, 1000) mixer.init() mixer.set_num_channels(30) sounds = { 'gun': { 'shoot': Sound('data/Sounds/gun.wav'), 'reload': Sound('data/Sounds/gun_reload.wav') }, 'ak47': { 'shoot': Sound('data/Sounds/ak47.wav'), 'reload': Sound('data/Sounds/ak47_reload.wav') }, 'm249': { 'shoot': Sound('data/Sounds/m249.wav'), 'reload': Sound('data/Sounds/m249_reload.wav') }, 'rifle': { 'shoot': Sound('data/Sounds/rifle.wav'), 'reload': Sound('data/Sounds/rifle_reload.wav') }, 'shotgun': { 'shoot': Sound('data/Sounds/shotgun.wav'), 'reload': Sound('data/Sounds/shotgun_reload.wav') }, 'flamethrower': { 'shoot': Sound('data/Sounds/flamethrower.wav'),
def run_game(): # Game parameters SCREEN_WIDTH, SCREEN_HEIGHT = 400, 400 BG_COLOR = 150, 150, 80 CREEP_FILENAMES = [ 'bonehunter2.png', 'skorpio.png', 'tuma.png', 'skrals.png', 'stronius1.png', 'stronius2.png', 'metus_with_guards.png'] TOWER_FILENAMES = [ 'matanui.png', 'malum.png', 'gresh.png', 'gelu.png', 'vastus.png', 'kiina.png', 'ackar.png', 'straak.png' ] SELL_FILENAME = 'Sell.png' RAIN_OF_FIRE = 'rain_of_fire.png' TORNADO = 'tornado.png' TORNADO_BIG = 'tornado_big.png' BUTTON_FILENAMES = TOWER_FILENAMES + [RAIN_OF_FIRE, TORNADO, SELL_FILENAME] money = 643823726935627492742129573207 mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag mixer.init() mixer.set_num_channels(30) print "mix", mixer.get_num_channels() EXPLOSIONS = [mixer.Sound('expl%d.wav'%(i)) for i in range(1, 7)] FIRING = [mixer.Sound('fire%d.wav'%(i)) for i in range(1, 4)] N_CREEPS = 10 N_TOWERS = 0 pygame.init() background = pygame.image.load("Background_Level_1.JPG") path = pygame.image.load("Path_Level_1.png") w, h = background.get_size() assert (w, h) == path.get_size() sc = min(1024.0/w, 1024.0/h) background = pygame.transform.scale(background, (int(w * sc), int(h * sc))) path = pygame.transform.scale(path, (int(w * sc), int(h * sc))) backgroundRect = background.get_rect() starts, paths = create_paths(path) screen = pygame.display.set_mode( background.get_size(), 0, 32) clock = pygame.time.Clock() # Create N_CREEPS random creeps. creeps = [] for i in range(N_CREEPS): creeps.append(Creep(screen, choice(CREEP_FILENAMES), ( choice(starts)[::-1]), # reversed x and y ( choice([-1, 1]), choice([-1, 1])), 0.05, paths, choice(EXPLOSIONS))) towers = [Tower(screen, choice(TOWER_FILENAMES), (randint(0, background.get_size()[0]), randint(0, background.get_size()[1])), (1, 1), 0.0, paths, radius=100, max_attacks=3, firing_sounds=FIRING) for i in range (N_TOWERS)] buttons = [Button(screen, buttonfile, (randint(0, background.get_size()[0]), randint(0, background.get_size()[1])), (1, 1), 0.0, paths) for buttonfile in BUTTON_FILENAMES] rightedge = screen.get_width() - 5 for b in buttons[:len(buttons)//2]: b.pos = vec2d(rightedge - b.image.get_width() / 2, 5 + b.image.get_height() / 2) rightedge -= (b.image.get_width() + 5) rightedge = screen.get_width() - 5 for b in buttons[len(buttons)//2:]: b.pos = vec2d(rightedge - b.image.get_width() / 2, 5 + b.image.get_height() / 2 + 80) rightedge -= (b.image.get_width() + 5) next_tower = TOWER_FILENAMES[0] cursor = Cursor(screen, TOWER_FILENAMES[0], (0, 0), (1,1), 0.0, paths) font = pygame.font.SysFont(pygame.font.get_default_font(), 20, bold=True) tornado_img = pygame.image.load(TORNADO_BIG).convert_alpha() global_attacks = GlobalAttacks(screen, RAIN_OF_FIRE, (randint(0, background.get_size()[0]), randint(0, background.get_size()[1])), (1, 1), 0.0, paths, radius=100, max_attacks=3, firing_sounds=FIRING) # The main game loop # rect = pygame.Rect((1, 1), (10, 10)) selling = False while True: # Limit frame speed to 50 FPS # time_passed = clock.tick(50) for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: rect.center = pygame.mouse.get_pos() collided = False for b in buttons: if b.rect.colliderect(rect): selling = (b.img_filename == SELL_FILENAME) rain_of_fire = (b.img_filename == RAIN_OF_FIRE) tornado = (b.img_filename == TORNADO) buying = (not selling) and (not rain_of_fire) if buying: next_tower = BUTTON_FILENAMES[buttons.index(b)] cursor.change_image(next_tower) # only one rain of fire available at a time if global_attacks.ready(): if rain_of_fire: for i in range(20): target = choice(creeps) global_attacks.target(target) if tornado: targets = [choice(creeps) for i in range(20)] tornado_attack = MobileAttack(global_attacks, targets, img=tornado_img, pos=vec2d((randint(0, background.get_size()[0]), randint(0, background.get_size()[1])))) tornado_attack.speed = 0.2 global_attacks.add_attack(tornado_attack) collided = True for t in towers: if cursor.rect.colliderect(t.rect): collided = t if not collided and not selling and money >= 100: towers += [Tower(screen, next_tower, pygame.mouse.get_pos(), (1, 1), 0.0, paths, radius=100, max_attacks=3, firing_sounds=FIRING)] money -= 100 if selling and collided: if collided in towers: towers.remove(collided) money += 50 # Redraw the background screen.blit(background, backgroundRect) # Update and redraw all creeps for creep in creeps: creep.update(time_passed) for tower in towers: tower.attack(creeps) money += tower.update(time_passed) money += global_attacks.update(time_passed) cursor.update() for obj in creeps + towers + buttons + [global_attacks, cursor]: obj.blitme() money_text = font.render("%d"%(money), True, pygame.Color(0, 0, 0)) screen.blit(money_text, (rightedge - 5 - money_text.get_width(), 5 + money_text.get_height())) pygame.display.flip()
import sys import copy from pygame import mixer from pygame.mixer import Sound import save_load if __name__ == "__main__": sys.exit() else: main = sys.modules["__main__"] # noinspection PyArgumentList mixer.pre_init(frequency=44100, buffer=1024) mixer.init() # Sword Slash -- Played when you attempt to physically attack an enemy sword_slash = Sound('../Sound FX/sword_slash.wav') # Magical Attack -- Played when you attempt to use a magical attack magic_attack = Sound('../Sound FX/magic_attack.wav') # Magic Healing -- Played when you attempt to use a magical healing spell magic_healing = Sound('../Sound FX/magic_healing.wav') # Enemy-hit -- Played when the enemy is hit by a player attack enemy_hit = Sound('../Sound FX/enemy_hit.wav') # Foot-steps -- Played when you move on the overworld
def test_init__zero_values(self): # Ensure that argument values of 0 are replaced with # preset values. No way to check buffer size though. mixer.pre_init(44100, 8, 1, allowedchanges=0) # None default values mixer.init(0, 0, 0) self.assertEqual(mixer.get_init(), (44100, 8, 1))
def main(): intervals = { 'major 2nd': 2, 'minor 3rd': 3, 'major 3rd': 4, 'perfect 4th': 5, 'perfect 5th': 7 } interval_lookup = {} for key, val in intervals.copy().iteritems(): # We don't want to modify the dict we're iterating though interval_lookup[val] = key # Add the reverse to the dict used_tones = [False] * 12 notes = len(Note.chromatic) tune = [] def prev_interval(): """Return the most recent interval""" previous_interval = (tune[-2] - tune[-1]) % notes # interval might not be in intervals if previous_interval in interval_lookup: previous_interval = interval_lookup[previous_interval] return previous_interval def get_new_note(pitch, interval=None): """This is embedded so we don't need to pass in used_tones. Checks that the note is valid otherwise it picks a new note and sets it as used""" if interval is not None: pitch = (pitch + interval) % len(Note.chromatic) if used_tones[pitch] is True and False in used_tones: pitch = rand_choice( [i for i, used in enumerate(used_tones) if used is False]) used_tones[pitch] = True return pitch tune.append(get_new_note(randint(0, notes - 1))) tune.append(get_new_note(tune[-1], rand_choice(intervals.values()))) while False in used_tones: # intelligently choose a new pitch based on the interval between the # previous two note = get_new_note(randint(0, notes - 1)) if randint(1, 4) > 1: # 1 in 4 chance for a random note if prev_interval() == 'major 3rd': # if the previous interval was a minor 3rd, attempt to follow # it with a major 2nd # mod is used to stay in the octave note = get_new_note(tune[-1], intervals['major 2nd']) elif prev_interval == 'perfect 4th': # if the previous interval was a major 3rd, attempt to follow # by going down a minor 3rd note = get_new_note(tune[-1], -1 * intervals['major 3rd']) tune.append(note) mixer.pre_init(44100, -16, 1, 1024) pygame.init() play_tune([Note.chromatic[note] for note in tune]) pygame.quit()
def fun(root): root.destroy() SPEED_FIGHTER = 4 SPEED_BIRD_X = 0.4 SPEED_BIRD_Y = 0.1 JUMP_SPEED = 0.2 HEALTH_FIGHTER = 100 DAMAGE_FIGHTER = 0.1 HEALTH_BOT = 70 DAMAGE_BOT_PROST = 0.09 DAMAGE_BOT_SIL = 1 GRAVITY = 0.08 MANA = 100 MANA_PLUS = 1 """размер окна""" SIZE = (1450, 770) """создание окна""" window = pygame.display.set_mode(SIZE) pygame.display.set_caption("Fighters") """холст""" screen = pygame.image.load("images/fon.png").convert() screen = pygame.transform.scale(screen, (SIZE)) screen_win = pygame.image.load("images/win.jpg").convert() screen_lose = pygame.image.load("images/lose.jpg").convert() clock = pygame.time.Clock() """холст фейк""" screen_fake = pygame.Surface(SIZE) """шрифты""" pygame.font.init() font = pygame.font.SysFont("Berlin Sans FB", 25) font2 = pygame.font.SysFont("Berlin Sans FB", 17) """создание обектов""" """Птицы""" bird = pygame.image.load("images/bird.png").convert_alpha() bird = pygame.transform.scale(bird, (70, 70)) birdq = bird birdleft = pygame.image.load("images/birdleft.png").convert_alpha() birdleft = pygame.transform.scale(birdleft, (70, 70)) birdw = birdleft birdnew1 = pygame.image.load("images/bird.png").convert_alpha() birdnew1 = pygame.transform.scale(birdnew1, (70, 70)) birdt = birdnew1 """Fighter (анимация)""" fighter = pygame.image.load("images/fighter.png").convert_alpha() fighter_copy = fighter fighter_down = pygame.image.load("images/fighter_down.png").convert_alpha() fighter_down_copy = fighter_down fighter_left = pygame.image.load("images/fighter_left.png").convert_alpha() fighter_left_copy = fighter_left fighter_right = pygame.image.load( "images/fighter_right.png").convert_alpha() fighter_right_copy = fighter_right fighter_up = pygame.image.load("images/fighter_up.png").convert_alpha() fighter_up_copy = fighter_up """атаки Fighters""" fighter_atack_stay = pygame.image.load( "images/fighter_atack_stay.png").convert_alpha() fighter_atack_stay_copy = fighter_atack_stay fighter_atack_stay_2 = pygame.image.load( "images/fighter_atack_stay(2).png").convert_alpha() fighter_atack_stay_2_copy = fighter_atack_stay_2 fighter_right_atack = pygame.image.load( "images/fighter_right_atack.png").convert_alpha() fighter_right_atack_copy = fighter_right_atack fighter_left_atack = pygame.image.load( "images/fighter_left_atack.png").convert_alpha() fighter_left_atack_copy = fighter_left_atack """БОТ""" bot = pygame.image.load("images/bot.png").convert_alpha() bot_copy = bot """Атаки Бота""" bot_atack_right = pygame.image.load( "images/bot_atack_right.png").convert_alpha() bot_atack_right_copy = bot_atack_right bot_atack_left = pygame.image.load( "images/bot_atack_left.png").convert_alpha() bot_atack_left_copy = bot_atack_left """Mana""" mana = pygame.image.load("images/Mana/1000%.png").convert() mana_copy = mana mana_950 = pygame.image.load("images/Mana/950%.png").convert() mana_900 = pygame.image.load("images/Mana/900%.png").convert() mana_850 = pygame.image.load("images/Mana/850%.png").convert() mana_800 = pygame.image.load("images/Mana/800%.png").convert() mana_750 = pygame.image.load("images/Mana/750%.png").convert() mana_700 = pygame.image.load("images/Mana/700%.png").convert() mana_650 = pygame.image.load("images/Mana/650%.png").convert() mana_600 = pygame.image.load("images/Mana/600%.png").convert() mana_550 = pygame.image.load("images/Mana/550%.png").convert() mana_500 = pygame.image.load("images/Mana/500%.png").convert() mana_450 = pygame.image.load("images/Mana/450%.png").convert() mana_400 = pygame.image.load("images/Mana/400%.png").convert() mana_350 = pygame.image.load("images/Mana/350%.png").convert() mana_300 = pygame.image.load("images/Mana/300%.png").convert() mana_250 = pygame.image.load("images/Mana/250%.png").convert() """Health fighter""" health = pygame.image.load("images/Health/100%.png").convert() health_copy = health health_95 = pygame.image.load("images/Health/95%.png").convert() health_90 = pygame.image.load("images/Health/90%.png").convert() health_85 = pygame.image.load("images/Health/85%.png").convert() health_80 = pygame.image.load("images/Health/80%.png").convert() health_75 = pygame.image.load("images/Health/75%.png").convert() health_70 = pygame.image.load("images/Health/70%.png").convert() health_65 = pygame.image.load("images/Health/65%.png").convert() health_60 = pygame.image.load("images/Health/60%.png").convert() health_55 = pygame.image.load("images/Health/55%.png").convert() health_50 = pygame.image.load("images/Health/50%.png").convert() health_45 = pygame.image.load("images/Health/45%.png").convert() health_40 = pygame.image.load("images/Health/40%.png").convert() health_35 = pygame.image.load("images/Health/35%.png").convert() health_30 = pygame.image.load("images/Health/30%.png").convert() health_25 = pygame.image.load("images/Health/25%.png").convert() health_20 = pygame.image.load("images/Health/20%.png").convert() health_15 = pygame.image.load("images/Health/15%.png").convert() health_10 = pygame.image.load("images/Health/10%.png").convert() health_5 = pygame.image.load("images/Health/5%.png").convert() health_0 = pygame.image.load("images/Health/0%.png").convert_alpha() """Health bot""" health_bot = pygame.image.load("images/Health_bot/70%.png").convert health_bot_copy = health_bot """координаты птиц""" bird_right = True bird_down = True bird_x = 0 bird_y = 0 birdnew1_right = True birdnew1_down = True birdnew1_x = -600 birdnew1_y = 80 """координаты бойца""" fighter_right = False fighter_left = False fighter_down = False fighter_up = False fighter_atack_1 = False fighter_atack_2 = False fighter_right_atacks = False fighter_left_atacks = False onGROUND = False fighter_yvel = 0 fighter_x = 200 fighter_y = 250 vidimost_fighter = True """координаты бота""" bot_right = bot_left = False bot_atack1 = False bot_atack2 = False vidimost = True """1 БОТ""" bot1 = Bots(1000, 250, fighter_x, fighter_y, bot, bot_atack_right, bot_atack_left, HEALTH_BOT, HEALTH_FIGHTER) """функция для столкновения обьектов""" def Intersect(x1, x2, y1, y2): if (x1 > x2 - 135) and (x1 < x2 + 159) and (y1 > y2 - 140) and ( y1 < y2 + 185): return 1 else: return 0 """Фоновая музыка""" mixer.pre_init(44100, -16, 1, 512) mixer.init() sound = mixer.Sound("sounds/metro_2033.ogg") sound.play(-1) sec = 0.50 """обработчик событий""" done = True while done: timer = pygame.time.get_ticks() / 1000 print(timer) if MANA != 100: if timer > sec: sec += 0.50 MANA += MANA_PLUS """ЦИКЛ""" for e in pygame.event.get(): if e.type == pygame.QUIT: done = False sys.exit() """событие нажатие на мыщку""" if e.type == pygame.MOUSEBUTTONDOWN: if e.button == 3: fighter_atack_1 = True if e.button == 1: fighter_atack_2 = True """событие отжатие на мышку""" if e.type == pygame.MOUSEBUTTONUP: if e.button == 3: fighter_atack_1 = False fighter = fighter_copy if e.button == 1: fighter_atack_2 = False fighter = fighter_copy """событие нажатия на клавиатуру""" if e.type == pygame.KEYDOWN: if e.key == pygame.K_ESCAPE: menu() if e.key == pygame.K_d: fighter_right = True if e.key == pygame.K_a: fighter_left = True if e.key == pygame.K_s: fighter_down = True if e.key == pygame.K_e: fighter_right_atacks = True if e.key == pygame.K_q: fighter_left_atacks = True if fighter_y > 544: if e.key == pygame.K_SPACE: fighter_up = True """событие отжатие клавиатуры""" if e.type == pygame.KEYUP: if e.key == pygame.K_d: fighter_right = False fighter = fighter_copy if e.key == pygame.K_a: fighter_left = False fighter = fighter_copy if e.key == pygame.K_s: fighter_down = False fighter = fighter_copy if e.key == pygame.K_e: fighter_right_atacks = False fighter = fighter_copy if e.key == pygame.K_q: fighter_left_atacks = False fighter = fighter_copy """Условия передвежения Fighter""" if vidimost_fighter == True: if fighter_right == True: fighter = fighter_right_copy if fighter_x < 1330: fighter_x += SPEED_FIGHTER if fighter_left == True: fighter = fighter_left_copy if fighter_x > 0: fighter_x -= SPEED_FIGHTER if fighter_down == True: if fighter_y > 544: onGROUND = True fighter = fighter_down_copy """Прыжок""" if fighter_up == True: onGROUND = True fighter = fighter_up_copy if fighter_y > 200: for i in range(20): fighter_y -= JUMP_SPEED else: fighter_up = False onGROUND = False if onGROUND == True: fighter_yvel = 0 """Падение""" if onGROUND == False: fighter = fighter_copy if fighter_y < 545: fighter_yvel += GRAVITY fighter_y += fighter_yvel """атаки Fighters""" if vidimost_fighter == True: if fighter_atack_1 == True: fighter = fighter_atack_stay_copy if fighter_atack_2 == True: fighter = fighter_atack_stay_2_copy if MANA > 10: if fighter_right_atacks == True: fighter = fighter_right_atack_copy MANA -= MANA_PLUS if MANA > 10: if fighter_left_atacks == True: fighter = fighter_left_atack_copy MANA -= MANA_PLUS if HEALTH_FIGHTER < -1: vidimost_fighter = False """Мана fighter""" if MANA != -100: if MANA == 100: mana = mana_copy elif MANA >= 95: mana = mana_950 elif MANA >= 90: mana = mana_900 elif MANA >= 85: mana = mana_850 elif MANA >= 80: mana = mana_800 elif MANA >= 75: mana = mana_750 elif MANA >= 70: mana = mana_700 elif MANA >= 65: mana = mana_650 elif MANA >= 60: mana = mana_600 elif MANA >= 55: mana = mana_550 elif MANA >= 50: mana = mana_500 elif MANA >= 45: mana = mana_450 elif MANA >= 40: mana = mana_400 elif MANA >= 35: mana = mana_350 elif MANA >= 30: mana = mana_300 elif MANA >= 25: mana = mana_250 """Health fighter""" if vidimost_fighter == True: if HEALTH_FIGHTER == 100: health = health_copy elif HEALTH_FIGHTER >= 95: health = health_95 elif HEALTH_FIGHTER >= 90: health = health_90 elif HEALTH_FIGHTER >= 85: health = health_85 elif HEALTH_FIGHTER >= 80: health = health_80 elif HEALTH_FIGHTER >= 75: health = health_75 elif HEALTH_FIGHTER >= 70: health = health_70 elif HEALTH_FIGHTER >= 65: health = health_65 elif HEALTH_FIGHTER >= 60: health = health_60 elif HEALTH_FIGHTER >= 55: health = health_55 elif HEALTH_FIGHTER >= 45: health = health_45 elif HEALTH_FIGHTER >= 40: health = health_40 elif HEALTH_FIGHTER >= 35: health = health_35 elif HEALTH_FIGHTER >= 30: health = health_30 elif HEALTH_FIGHTER >= 25: health = health_25 elif HEALTH_FIGHTER >= 20: health = health_20 elif HEALTH_FIGHTER >= 15: health = health_15 elif HEALTH_FIGHTER >= 10: health = health_10 elif HEALTH_FIGHTER >= 5: health = health_5 elif HEALTH_FIGHTER >= 0: health = health_0 if vidimost == True: """Health bot""" bot1.health(HEALTH_BOT, HEALTH_FIGHTER) """Передвежение 1 птицы по оси X""" if bird_right == True: bird_x += SPEED_BIRD_X if bird_x > 1500: bird_right = False else: bird = birdw bird_x -= SPEED_BIRD_X if bird_x < -70: bird = birdq bird_right = True """Передвежение 1 птицы по оси y""" if bird_down == True: bird_y += SPEED_BIRD_Y if bird_y > 70: bird_down = False else: bird_y -= SPEED_BIRD_Y if bird_y < 20: bird_down = True """Передвежение 2 птицы по оси X""" if birdnew1_right == True: birdnew1_x += SPEED_BIRD_X if birdnew1_x > 1500: birdnew1_right = False else: birdnew1 = birdw birdnew1_x -= SPEED_BIRD_X if birdnew1_x < -70: birdnew1 = birdt birdnew1_right = True """Передвежение 2 птицы по оси y""" if birdnew1_down == True: birdnew1_y += SPEED_BIRD_Y if birdnew1_y > 150: birdnew1_down = False else: birdnew1_y -= SPEED_BIRD_Y if birdnew1_y < 80: birdnew1_down = True if vidimost == True: """Передвежение бота по оси x""" bot1.update(fighter_x, fighter_y, bot) if HEALTH_BOT <= 9: vidimost = False if HEALTH_BOT < 10: screen = screen_win if HEALTH_FIGHTER < -1: screen = screen_lose """заливка фейкового холста""" screen_fake.fill((50, 50, 50)) if vidimost == True: """столкновение c ботом""" if Intersect(fighter_x, bot1.bot_x, fighter_y, bot1.bot_y) == True: """право(бот)""" if fighter_x > bot1.bot_x: fighter_left = False bot_atack1 = True bot_atack2 = False if vidimost_fighter == True: """атака вправо от бота""" if bot_atack1 == True: bot = bot_atack_right HEALTH_FIGHTER -= DAMAGE_FIGHTER else: bot = bot_copy """простая атака влево от fighter""" if fighter_atack_2: HEALTH_BOT -= DAMAGE_BOT_PROST """сильная атака от fighter""" if MANA > 30: if fighter_left_atacks == True: HEALTH_BOT -= DAMAGE_BOT_SIL """лево(бот)""" if fighter_x < bot1.bot_x: fighter_right = False bot_atack2 = True bot_atack1 = False if vidimost_fighter == True: """атака влево от бота""" if bot_atack2 == True: bot = bot_atack_left HEALTH_FIGHTER -= DAMAGE_FIGHTER else: bot = bot_copy """простая атака вправо от fighter""" if fighter_atack_1: HEALTH_BOT -= DAMAGE_BOT_PROST """сильная атака от fighter""" if MANA > 30: if fighter_right_atacks == True: HEALTH_BOT -= DAMAGE_BOT_SIL else: bot = bot_copy else: bot = pygame.image.load("images/Health_bot/0%.png").convert_alpha() """отоброжение обьектов""" screen_fake.blit(screen, (0, 0)) screen_fake.blit( font.render('Health Fighter: ' + str(HEALTH_FIGHTER), 5, (117, 74, 103)), (45, 20)) screen_fake.blit( font.render('Health Bot: ' + str(HEALTH_BOT), 5, (117, 74, 103)), (45, 50)) screen_fake.blit(font.render('Mana: ' + str(MANA), 5, (117, 74, 103)), (45, 80)) screen_fake.blit( font2.render('fps: ' + str(int(clock.get_fps())), 5, (117, 74, 103)), (1370, 20)) screen_fake.blit(health, (fighter_x, fighter_y - 25)) if vidimost_fighter == True: screen_fake.blit(mana, (fighter_x, fighter_y - 40)) if vidimost == True: bot1.draw(screen_fake) if vidimost_fighter == True: screen_fake.blit(fighter, (fighter_x, fighter_y)) screen_fake.blit(bird, (bird_x, bird_y)) screen_fake.blit(birdnew1, (birdnew1_x, birdnew1_y)) """отображение рабочей поверхности на экран""" window.blit(screen_fake, (0, 0)) clock.tick(0) pygame.display.flip()
# this is a good time to set any fusion parameters imu.setSlerpPower(0.02) imu.setGyroEnable(True) imu.setAccelEnable(True) imu.setCompassEnable(True) poll_interval = imu.IMUGetPollInterval() print("Recommended Poll Interval: %dmS\n" % poll_interval) import pygame import pygame.mixer as pm pm.init() pm.pre_init(44100, -16, 1, 4096) def start_sounds(sound_list): """ start list of sound files with PyGame """ loops = [] for sound in sound_list: loop = pygame.mixer.Sound(sound) loops.append(loop) for loop in loops: loop.play(-1) return