Beispiel #1
0
def init_fundamentals():
    init_pygame()
    import platform_specific
    platform_specific.startup_hook()
    audio.init()
    commands.init()
    init_archy()
Beispiel #2
0
def init_fundamentals():
    init_pygame()
    import platform_specific
    platform_specific.startup_hook()
    audio.init()
    commands.init()
    init_archy()
Beispiel #3
0
def main():

    resource.path.append('data')
    resource.reindex()
    font.add_directory('data/font')

    log.init()
    audio.init()
    client.init()
    server.init()
    options.init()
    director.init()

    clt = client.GameClient()
    clt.start()
    clt.stop()
Beispiel #4
0
def init():
    cfg = read_config()
    audio_cfg = cfg['audio']
    led_cfg = cfg['led']
    viz_cfg = cfg['viz']
    try:
        audio.init(audio_cfg['channels'], audio_cfg['rate'],
                   audio_cfg['chunk-size'], audio_cfg['device-index'])
        analyzer.init(led_cfg['bar-amount'], audio_cfg['rate'],
                      audio_cfg['chunk-size'], audio_cfg['min-freq'],
                      audio_cfg['max-freq'])
        pretty.init(led_cfg['bar-amount'], viz_cfg['decay'])
        led_controller.init(cfg)
    except StrypeException as e:
        logger.error(e)
        sys.exit(1)
Beispiel #5
0
def init_audio_plugin(interface_name):
    """ Find and initialise audio plugin for given interface. """
    names = audio_backends[interface_name]
    for audio_name in names:
        if audio.init(audio_name):
            return interface_name
        logging.debug('Could not initialise %s plugin.', audio_name)
    logging.error(
        'Null sound plugin malfunction. Could not initialise interface.')
    raise error.Exit()
Beispiel #6
0
import image, audio, time
from ulab import numpy as np
from ulab import scipy as sp

SIZE = 512//4
raw_buf = None
fb = image.Image(SIZE+50, SIZE, image.RGB565, copy_to_fb=True)
audio.init(channels=2, frequency=16000, gain=24, highpass=0.9883)

def audio_callback(buf):
    # NOTE: do Not call any function that allocates memory.
    global raw_buf
    if (raw_buf == None):
        raw_buf = buf

# Start audio streaming
audio.start_streaming(audio_callback)

def draw_fft(img, fft_buf):
    fft_buf = (fft_buf / max(fft_buf)) * SIZE
    fft_buf = np.log10(fft_buf + 1) * 20
    color = (0xFF, 0x0F, 0x00)
    for i in range(0, SIZE):
        img.draw_line(i, SIZE, i, SIZE-int(fft_buf[i]), color, 1)

def draw_audio_bar(img, level, offset):
    blk_size = SIZE//10
    color = (0xFF, 0x00, 0xF0)
    blk_space = (blk_size//4)
    for i in range(0, int(round(level/10))):
        fb.draw_rectangle(SIZE+offset, SIZE - ((i+1)*blk_size) + blk_space, 20, blk_size - blk_space, color, 1, True)
Beispiel #7
0
import image, audio, time
from ulab import numpy as np
from ulab import scipy as sp

CHANNELS = 1
FREQUENCY = 32000
N_SAMPLES = 32 if FREQUENCY == 16000 else 64
SCALE = 1
SIZE = (N_SAMPLES * SCALE) // CHANNELS

raw_buf = None
fb = image.Image(SIZE+(50*SCALE), SIZE, image.RGB565, copy_to_fb=True)
audio.init(channels=CHANNELS, frequency=FREQUENCY, gain_db=16, overflow=False)

def audio_callback(buf):
    # NOTE: do Not call any function that allocates memory.
    global raw_buf
    if (raw_buf == None):
        raw_buf = buf

# Start audio streaming
audio.start_streaming(audio_callback)

def draw_fft(img, fft_buf):
    fft_buf = (fft_buf / max(fft_buf)) * SIZE
    fft_buf = np.log10(fft_buf + 1) * 20
    color = (0xFF, 0x0F, 0x00)
    for i in range(0, len(fft_buf)):
        img.draw_line(i*SCALE, SIZE, i*SCALE, SIZE-int(fft_buf[i]) * SCALE, color, SCALE)

def draw_audio_bar(img, level, offset):
Beispiel #8
0
''' The main file for the program
'''

import sys
import pygame
import config
import sprites
import audio

pygame.init()
sprites.init()  # Initialize content
audio.init()  # Initialize audio

from screens.place_ships_screen import PlaceShipScreen
from screens.battle_screen import BattleScreen
from screens.menu_screen import MenuScreen
from screens.win_screen import WinScreen
from screens.intro_screen import IntroScreen
from screens.lose_screen import LoseScreen
from screens.test_screen import TestScreen
from screens.difficulty_screen import DifficultyScreen

# Initialize the game window
config.window = pygame.display.set_mode(
    (config.SCREEN_WIDTH, config.SCREEN_HEIGHT))
pygame.display.set_caption('Modern Battleship Extreme Warfare')

# Icon
icon = pygame.image.load('content/sprites/icon.png')
pygame.display.set_icon(icon)
Beispiel #9
0
playing = True

def quit(e):
	global playing
	if e.type == pygame.QUIT:
		playing = False
	elif e.type == pygame.KEYUP:
		if ((e.key == pygame.K_F4) and
		   (e.mod and pygame.KMOD_ALT)):
			playing = False

player = units.player(500, 500)
display.register(player)

event.register(player.handler)
event.register(quit)
event.register(audio.handler)
event.register(display.handler)

audio.init()
clock = pygame.time.Clock()
while(playing):

	clock.tick(30)

	event.update()
	player.update()
	display.update()
	
pygame.display.quit()
Beispiel #10
0
def init(showFrameRate = False, daemon = False):
    "Initializes various global components, like audio, lighting, and the clock. Should be called once at the beginning of the program."
    global renderLit
    global clock
    global renderObjects
    global renderEnvironment
    global log
    global reflectionBuffer
    global reflectionCamera
    global reflectionRenderTexture
    global defaultFov
    global enableShaders
    global enablePostProcessing
    global enableDistortionEffects
    global filters
    global isDaemon
    global mf
    global maps
    
    mf = None
    
    if not vfs.isDirectory("maps"):
        mf = Multifile()
        mf.openRead(ExecutionEnvironment.getEnvironmentVariable("PKG_ROOT") + "/pkg.mf")
    
    isDaemon = daemon
    
    if not daemon:
        base.setBackgroundColor(2.0/255.0, 28.0/255.0, 53.0/255.0)
    
    log = Logger()
    
    sys.excepthook = exceptHook
        
    clock = Clock()
    base.disableMouse() # Disable default mouse camera control
    if not daemon:
        base.camNode.setCameraMask(BitMask32.bit(1))
        base.camLens.setFov(defaultFov)
    renderLit = render.attachNewNode("renderLit")
    renderObjects = renderLit.attachNewNode("renderObjects")
    renderEnvironment = renderLit.attachNewNode("renderEnvironment")
    controllers.init()
    ai.init()
    audio.init(dropOffFactor = 1.4, distanceFactor = 14, dopplerFactor = 0.0)
    numMaxDynamicLights = 0
    if enableShaders and not daemon:
        numMaxDynamicLights = 2
    for i in range(numMaxDynamicLights):
        light = PointLight("Light" + str(i))
        light.setColor(Vec4(0, 0, 0, 1))
        light.setAttenuation(Vec3(0, 0, 1))
        lightNode = renderLit.attachNewNode(light)
        lightNode.setPos(0, 0, 0)
        renderLit.setLight(lightNode)
        lightNodes.append((light, lightNode))
    if enableShaders and not daemon:
        shadersChanged()
    if enablePostProcessing and not daemon:
        postProcessingChanged()
    if not daemon:
        winprops = WindowProperties()
        props = FrameBufferProperties()
        props.setRgbColor(1)
        reflectionBuffer = base.graphicsEngine.makeOutput(
        base.pipe, "reflection-buffer", -2,
        props, winprops,
        GraphicsPipe.BFSizeTrackHost | GraphicsPipe.BFRefuseWindow,
        base.win.getGsg(), base.win)
        reflectionBuffer.setSort(-100)
        reflectionBuffer.setClearColor(Vec4(0, 0, 0, 0))
        reflectionRenderTexture = Texture()
        reflectionBuffer.addRenderTexture(reflectionRenderTexture, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)
        reflectionCamera = base.makeCamera(reflectionBuffer, scene = render, lens = base.cam.node().getLens(), mask = BitMask32.bit(4))
        reflectionCamera.reparentTo(render)
        reflectionCamera.node().setActive(False)
    particles.init()
    maps = [x.split("\t") for x in readFile("maps/maps.txt").splitlines()]
Beispiel #11
0
import image, audio, time
from ulab import numpy as np
from ulab import scipy as sp

CHANNELS = 2
SIZE = 512 // (2 * CHANNELS)

raw_buf = None
fb = image.Image(SIZE + 50, SIZE, image.RGB565, copy_to_fb=True)
audio.init(channels=CHANNELS, frequency=16000, gain_db=24, highpass=0.9883)


def audio_callback(buf):
    # NOTE: do Not call any function that allocates memory.
    global raw_buf
    if (raw_buf == None):
        raw_buf = buf


# Start audio streaming
audio.start_streaming(audio_callback)


def draw_fft(img, fft_buf):
    fft_buf = (fft_buf / max(fft_buf)) * SIZE
    fft_buf = np.log10(fft_buf + 1) * 20
    color = (0xFF, 0x0F, 0x00)
    for i in range(0, SIZE):
        img.draw_line(i, SIZE, i, SIZE - int(fft_buf[i]), color, 1)

Beispiel #12
0
import image, audio, time
from ulab import numpy as np
from ulab import scipy as sp

CHANNELS = 1
FREQUENCY = 32000
N_SAMPLES = 32 if FREQUENCY == 16000 else 64
SCALE = 2
SIZE = (N_SAMPLES * SCALE) // CHANNELS

raw_buf = None
fb = image.Image(SIZE+(50*SCALE), SIZE, image.RGB565, copy_to_fb=True)
audio.init(channels=CHANNELS, frequency=FREQUENCY, gain_db=16)

def audio_callback(buf):
    # NOTE: do Not call any function that allocates memory.
    global raw_buf
    if (raw_buf == None):
        raw_buf = buf

# Start audio streaming
audio.start_streaming(audio_callback)

def draw_fft(img, fft_buf):
    fft_buf = (fft_buf / max(fft_buf)) * SIZE
    fft_buf = np.log10(fft_buf + 1) * 20
    color = (0xFF, 0x0F, 0x00)
    for i in range(0, len(fft_buf)):
        img.draw_line(i*SCALE, SIZE, i*SCALE, SIZE-int(fft_buf[i]) * SCALE, color, SCALE)

def draw_audio_bar(img, level, offset):
Beispiel #13
0
    def __init__(self, parent=None):
        super().__init__(parent, board_class=ArrangeBoard)
        self.setWindowTitle(f"中国象棋 v{VERSION}")
        self.setupContextMenu()

        audio.init()

        self.engine = None
        self.engines = {
            Chess.RED: None,
            Chess.BLACK: None,
        }

        self.engine_side = [Chess.BLACK]
        self.human_side = [Chess.RED]

        self.board.csize = 80
        self.board.callback = self.board_callback
        self.resize(self.board.csize * Chess.W, self.board.csize * Chess.H)

        self.game_signal = GameSignal()

        self.method = MethodDialog(self)
        self.method.setWindowIcon(QtGui.QIcon(self.board.FAVICON))

        self.settings = SettingsDialog(self)
        self.settings.setWindowIcon(QtGui.QIcon(self.board.FAVICON))

        self.game_menu = GameContextMenu(self, self.game_signal)

        self.toast = Toast(self)

        # 以下初始化信号

        self.game_signal.thinking.connect(self.set_thinking)
        self.game_signal.settings.connect(self.settings.show)
        self.game_signal.hint.connect(self.hint)
        self.game_signal.undo.connect(self.undo)
        self.game_signal.redo.connect(self.redo)
        self.game_signal.reset.connect(self.reset)
        self.game_signal.debug.connect(self.debug)

        self.game_signal.load.connect(self.load)
        self.game_signal.save.connect(self.save)
        self.game_signal.paste.connect(self.paste)

        self.game_signal.move.connect(self.play)

        self.game_signal.checkmate.connect(self.checkmateMessage)
        self.game_signal.checkmate.connect(lambda: self.set_thinking(False))

        self.game_signal.nobestmove.connect(self.nobestmove)

        self.game_signal.draw.connect(lambda: self.toast.message('和棋!!!'))
        self.game_signal.resign.connect(lambda: self.toast.message('认输了!!!'))

        self.game_signal.animate.connect(self.animate)

        self.settings.transprancy.valueChanged.connect(
            lambda e: self.setWindowOpacity((100 - e) / 100)
        )

        self.settings.reverse.stateChanged.connect(
            lambda e: self.board.setReverse(self.settings.reverse.isChecked())
        )

        self.settings.audio.stateChanged.connect(
            lambda e: audio.play(Chess.MOVE) if e else None
        )

        self.settings.standard_method.stateChanged.connect(
            lambda e: self.method.set_standard(e)
        )

        self.settings.ok.clicked.connect(self.accepted)
        self.settings.loads()

        self.game_signal.arrange.connect(self.arrange)
        self.board.signal.finish.connect(self.finish_arrange)

        self.game_signal.method.connect(self.method.show)
        self.method.list.currentItemChanged.connect(self.method_changed)

        self.reset()
        self.accepted()
        self.check_openfile()
Beispiel #14
0
def main():
    """Initialization, configuration reading, start of server
    over sockets on given port"""
    global conf, log
    # TODO: Register signals
    #   SIGINT, SIGPIPE?, others?

    signal.signal(signal.SIGINT, sigint_handler)

    # At this stage, logging on stdout
    log = logs.Logging()

    log.info("Starting server")
    conf = UserConfiguration(logger=log)

    # Create primary pid file
    create_pid_file()

    # Create global state
    global_state = GlobalState()

    if conf.mode == 'daemon':
        # Destroy pid file, will be re-created after fork
        destroy_pid_file()
        # Fork, detach pipes, chdir to '/' etc...
        daemon.createDaemon()
        create_pid_file()

    # Create server socket
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(("", conf.port))
    server_socket.listen(conf.max_simultaneous_connections)

    # Redirect logging to logfile
    log.init_stage2(conf)
    log.info("Configuration loaded")

    # Create pidfile

    log.info("Starting audio server")
    audio.port = conf.audio_port
    audio.host = conf.audio_host
    audio.init(logger=log, config=conf)

    log.info("Starting audio event delivery thread")
    audio_event_delivery_thread = threading.Thread(
        target=audio_event_delivery,
        name="Audio event delivery",
        kwargs={'global_state': global_state})
    audio_event_delivery_thread.start()
    # Terminate and join this thread on exit()
    atexit.register(join_audio_event_delivery_thread,
                    audio_event_delivery_thread)

    log.info("Waiting for connections")
    atexit.register(join_terminated_client_threads)
    while True:
        log.info("Waiting for connections")
        (client_socket, address) = server_socket.accept()

        join_terminated_client_threads()

        log.debug("Connection ready")
        client_provider = threading.Thread(target=serve_client,
                                           name="Provider (" +
                                           str(client_socket.fileno()) + ")",
                                           kwargs={
                                               'method': 'socket',
                                               'socket': client_socket,
                                               'global_state': global_state
                                           })
        client_threads.append(client_provider)
        client_provider.start()
        log.info("Accepted new client, thread started")
Beispiel #15
0
def init(showFrameRate=False, daemon=False):
    "Initializes various global components, like audio, lighting, and the clock. Should be called once at the beginning of the program."
    global renderLit
    global clock
    global renderObjects
    global renderEnvironment
    global log
    global reflectionBuffer
    global reflectionCamera
    global reflectionRenderTexture
    global defaultFov
    global enableShaders
    global enablePostProcessing
    global enableDistortionEffects
    global filters
    global isDaemon
    global mf
    global maps

    mf = None

    if not vfs.isDirectory("maps"):
        mf = Multifile()
        mf.openRead(
            ExecutionEnvironment.getEnvironmentVariable("PKG_ROOT") +
            "/pkg.mf")

    isDaemon = daemon

    if not daemon:
        base.setBackgroundColor(2.0 / 255.0, 28.0 / 255.0, 53.0 / 255.0)

    log = Logger()

    sys.excepthook = exceptHook

    clock = Clock()
    base.disableMouse()  # Disable default mouse camera control
    if not daemon:
        base.camNode.setCameraMask(BitMask32.bit(1))
        base.camLens.setFov(defaultFov)
    renderLit = render.attachNewNode("renderLit")
    renderObjects = renderLit.attachNewNode("renderObjects")
    renderEnvironment = renderLit.attachNewNode("renderEnvironment")
    controllers.init()
    ai.init()
    audio.init(dropOffFactor=1.4, distanceFactor=14, dopplerFactor=0.0)
    numMaxDynamicLights = 0
    if enableShaders and not daemon:
        numMaxDynamicLights = 2
    for i in range(numMaxDynamicLights):
        light = PointLight("Light" + str(i))
        light.setColor(Vec4(0, 0, 0, 1))
        light.setAttenuation(Vec3(0, 0, 1))
        lightNode = renderLit.attachNewNode(light)
        lightNode.setPos(0, 0, 0)
        renderLit.setLight(lightNode)
        lightNodes.append((light, lightNode))
    if enableShaders and not daemon:
        shadersChanged()
    if enablePostProcessing and not daemon:
        postProcessingChanged()
    if not daemon:
        winprops = WindowProperties()
        props = FrameBufferProperties()
        props.setRgbColor(1)
        reflectionBuffer = base.graphicsEngine.makeOutput(
            base.pipe, "reflection-buffer", -2, props, winprops,
            GraphicsPipe.BFSizeTrackHost | GraphicsPipe.BFRefuseWindow,
            base.win.getGsg(), base.win)
        reflectionBuffer.setSort(-100)
        reflectionBuffer.setClearColor(Vec4(0, 0, 0, 0))
        reflectionRenderTexture = Texture()
        reflectionBuffer.addRenderTexture(reflectionRenderTexture,
                                          GraphicsOutput.RTMBindOrCopy,
                                          GraphicsOutput.RTPColor)
        reflectionCamera = base.makeCamera(reflectionBuffer,
                                           scene=render,
                                           lens=base.cam.node().getLens(),
                                           mask=BitMask32.bit(4))
        reflectionCamera.reparentTo(render)
        reflectionCamera.node().setActive(False)
    particles.init()
    maps = [x.split("\t") for x in readFile("maps/maps.txt").split("\n")]