예제 #1
0
    def redrawAll(self, screen):
        screen.blit(self.background, [-150, 0])
        self.mouse = pygame.mouse.get_pos()
        self.click = pygame.mouse.get_pressed()

        if 540 > self.mouse[0] > 390 and 640 > self.mouse[1] > 580:
            pygame.draw.rect(self.screen, (153, 153, 255), (390, 580, 150, 60))
            if self.click[0] == 1:
                Level().run()

        else:
            pygame.draw.rect(self.screen, (0, 102, 204), (390, 580, 150, 60))

        #hover over instruction
        if 320 > self.mouse[0] > 190 and 640 > self.mouse[1] > 580:
            pygame.draw.rect(self.screen, (153, 153, 255), (190, 580, 130, 60))
            if self.click[0] == 1:
                Instructions().run()
        else:
            pygame.draw.rect(self.screen, (0, 102, 204), (190, 580, 130, 60))

        self.buttonFont = pygame.font.Font("freesansbold.ttf", 20)
        self.buttonText = self.buttonFont.render("Choose Level", True,
                                                 (0, 0, 255))
        self.screen.blit(self.buttonText, (400, 600))

        self.instruction = self.buttonFont.render("Instruction", True,
                                                  (0, 0, 255))
        self.screen.blit(self.instruction, (200, 600))
예제 #2
0
def assemble(file_name):
    symbols = []
    memory = Memory()
    instructions = Instructions()
    sap1_parser = Parser()

    print("Assemble {}".format(file_name))
    segments = sap1_parser.parse_file(file_name)

    if segments == []:
        print("ERROR: No code found in source file")
        exit(-2)

    # Extract all the lables from the segments to create a symbol table
    for segment in segments:
        for label in segment.labels:
            symbols.append(label)

    for segment in segments:
        segment.assemble(symbols, instructions)

    code_segment = None
    for segment in segments:
        if segment.is_code():
            code_segment = segment
        memory = segment.load_memory(memory)

    memory.dump(symbols, code_segment)
예제 #3
0
def main(configfile='../default_setup.ini'):
    """
    Start hello world!

    :param int configfile: use this configuration file. Defaults to 'default_setup.ini'.
    """

    #Read config and settings
    config = configparser.ConfigParser()
    config.read(configfile, encoding='utf8')

    try:
        myPort = config['midi'].getint('port')
        device_id = config['midi'].getint('noteon_id')
    except KeyError:
        raise LookupError('Missing key information in the config file.')

    if (myPort == None or device_id == None):
        raise LookupError('Missing key information in the config file.')

    codeK = Setup()
    tutorial = Instructions()
    codeK.open_port(myPort)
    codeK.open_port_out(myPort)

    # Use your favourite mapping of the keys
    mapping = Mapping_HelloWorld_NKK()

    # class to handle the midi input and map it to characters
    #TODO: this is ugly! Move this to the CodeKlavier module
    class HelloWorld(object):
        def __init__(self, port):
            self.port = port

        def __call__(self, event, data=None):
            message, deltatime = event
            # print(message)
            if message[2] > 0:  #only noteOn
                if (message[0] == device_id):
                    mapping.mapping(message[1])
                    # forwarding only note on messages to tutorial terminal for NKK:
                    codeK.send_message([message[0], message[1], message[2]])
                if (message[0] == 176):  #hardcoded pedal id (not pretty)
                    mapping.stopSC(message[1])

    codeK.set_callback(HelloWorld(myPort))

    # Loop to program to keep listening for midi input
    try:
        # timer = time.time()
        while True:
            if tutorial.mode():
                break
            time.sleep(0.01)
    except KeyboardInterrupt:
        print('')
    finally:
        # print("Bye-Bye :(")
        codeK.end()
예제 #4
0
def doInstructions():
    ''' 
    Creates and runs the instructions screen
    '''

    instructions = Instructions(screen, background)
    doneInstructions = instructions.createInstuctionsScreen()

    if doneInstructions == True:
        doMenu()
예제 #5
0
def main(configfile='../default_setup.ini'):
    # Start the CodeKlavier
    #Read config and settings
    config = configparser.ConfigParser()
    config.read(configfile, encoding='utf8')

    try:
        myPort = config['midi'].getint('port')
        device_id = config['midi'].getint('noteon_id')
    except KeyError:
        raise LookupError('Missing key information in the config file.')

    if (myPort == None or device_id == None):
        raise LookupError('Missing key information in the config file.')

    codeK = Setup()
    tutorial = Instructions()
    codeK.open_port(myPort)
    codeK.open_port_out(myPort)

    # Use your favourite mapping of the keys
    mapping = Mapping_HelloWorld_NKK()

    # class to handle the midi input and map it to characters
    #TODO: this is ugly! Move this to the CodeKlavier module
    class HelloWorld(object):
        def __init__(self, port):
            self.port = port

        def __call__(self, event, data=None):
            message, deltatime = event
            # print(message)
            if message[2] > 0:  #only noteOn
                if (message[0] == device_id):
                    mapping.mapping(message[1])

    codeK.set_callback(HelloWorld(myPort))

    tutorial.do_tutorial()
    codeK.send_message([0x90, 108, 127])  #send enter to codespace
    tutorial.level_four()

    # Loop to program to keep listening for midi input
    try:
        timer = time.time()
        while True:
            time.sleep(0.01)
    except KeyboardInterrupt:
        print('')
    finally:
        # print("Bye-Bye :(")
        codeK.end()
예제 #6
0
    def __init__(self, canvas, design, day, participantid):
        self.participantid = participantid
        self.perf_data = {}
        self.canvas = canvas
        self.design = design
        self.rm_count = 1
        # read in response key counterbalance from csv
        keybalance = pd.read_csv(
            "items/keybalance.csv", header=None).iloc[self.participantid, 0] - 1

        responsekey_list = ({"word": 'd', "nonword": 's', "pm": 'j'},
                            {"word": 's', "nonword": 'd', "pm": 'j'},
                            {"word": 'j', "nonword": 'k', "pm": 'd'},
                            {"word": 'k', "nonword": 'j', "pm": 'd'})

        self.responsekeys = responsekey_list[keybalance]
        # Will need to associate keybalance with hand for instructions
        self.OThand = 'LEFT'
        if self.responsekeys["word"] == 'j' or self.responsekeys["word"] == 'k':
            self.OThand = 'RIGHT'
        self.bal = participantid % 2
        self.counterbalance = [np.array([["single", "multi"], ["multi", "single"]]),
                               np.array([["multi", "single"], ["single", "multi"]])][self.bal]
        self.day = day
        # blocknum will increment as the experiment runs
        self.blocknum = 1
        if day == 1:
         # create stimuli
            self.design.practice_stim(
                self.responsekeys["word"], self.responsekeys["nonword"], self.participantid)
            self.design.set_stim(self.counterbalance)
            self.design.set_pm_positions(3)
            self.design.create_blocks(self.responsekeys)
            self.design.insert_pm(self.counterbalance, self.responsekeys)
            self.design.setup_data(self.participantid, self.counterbalance)
            self.design.gen_recmem_nontargets(self.participantid)
        else:
            self.design.read_data(participantid)
        # read in PM stimuli as need to display them in instructions
        self.todays_multi = self.design.multi_cond_words.to_frame().copy().iloc[
            range((self.day-1)*8, (self.day-1)*8+8), :]
        self.todays_single = self.design.single_cond_words.to_frame().copy().iloc[[
            self.day-1]]
        self.todays_single = self.todays_single.rename(columns={1: 'Words'})
        self.todays_multi = self.todays_multi.rename(columns={1: 'Words'})
        self.instructions = Instructions(
            self.responsekeys, self.todays_multi, self.todays_single)
예제 #7
0
    def parse_instruction(self, line, index):
        instruction = Instructions(index) # Instruction Number from #0
        instruction.set_text(line.strip())
        line = line.strip().upper()

        opcode_token = 0

        index_colon = line.find(':')
        if index_colon != -1:
            instruction.set_label(line[:index_colon].strip())
            print(instruction.label + "#")
            line = line[index_colon + 1:].strip()
            print(line)

        tokens = re.split('\s+', line)
        tokens = [token.strip(',') for token in tokens]

        instruction.set_opcode(tokens[opcode_token].strip())
        instruction.set_operands(tokens[opcode_token + 1:])
        return instruction
예제 #8
0
if len(sys.argv) < 3:
    print "Usage: python %s <single|full|debug|cfg|parse> <inputfile1> <inputfile2> .. <inputfileN>" % (sys.argv[0])
else:
    mode = sys.argv[1]
    datafiles = sys.argv[2:]
    
    if 'full' in mode:
        sys.setrecursionlimit(500) # watch out!
    if 'single' in mode:
        sys.setrecursionlimit(2000) # watch out!
    
    
    try:
        for datafile in datafiles:
            
            instructions = Instructions()
            parser = Parser(datafile, instructions)
            analysis = Analysis(instructions)
            
            if mode == 'debugnofilter':
                logging.info("running debug mode with ipython on file %s..." % (datafile))
                
                parser = Parser(datafile, instructions, [])
                
                parser.run()
                ipshell = IPShellEmbed()
                ipshell()
            
            if mode == 'debug':
                logging.info("running debug mode with ipython on file %s..." % (datafile))
                
예제 #9
0
def run_game():
    settings = Settings()

    # initialise the game
    pygame.init()
    # returns a pyGame surface
    music = pygame.mixer.Sound("music.wav")
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height), 0, 32)
    clock = pygame.time.Clock()
    scoreboard = Scoreboard(screen)
    play_button = Button(
        screen, settings.screen_width / 2 - settings.button_width / 2,
        settings.screen_height / 2 - settings.button_height / 2, settings,
        "Play Food Fetcher")
    instructions = Instructions(screen, settings)
    draw_title = Title(screen)

    foods = []
    poisons = []
    basket = Basket(screen)
    engine = Engine(screen, settings, scoreboard, foods, poisons, basket)
    # play music

    music.play(loops=-1)

    # main event loop
    # while True:
    while True:
        time_passed = clock.tick(50)
        mouse_x = pygame.mouse.get_pos()[0]
        mouse_y = pygame.mouse.get_pos()[1]
        engine.check_events(play_button, mouse_x, mouse_y)

        screen.fill(settings.bg_color)

        if settings.game_active:
            engine.update_basket(mouse_x)
            engine.check_foods(time_passed)
            engine.check_poisons(time_passed)

            if len(foods) == 0:
                if scoreboard.food_caught > 0:
                    #  Increase the balloon speed for each new batch of balloons.
                    settings.food_speed *= settings.speed_increase_factor
                    settings.poison_ratio *= settings.speed_increase_factor
                    scoreboard.batches_finished += 1
                    # If player has completed required batches, increase batch_size

                if scoreboard.batches_finished % settings.batches_needed == 0 and scoreboard.batches_finished > 0:
                    settings.batch_size += 1
                engine.release_batch()
        else:
            play_button.blitme()
            draw_title.blitme(
                settings.screen_width / 2 - settings.button_width / 2,
                settings.screen_height / 2 - settings.button_height * 4)
            # If a game has just ended, show Game Over button
            if settings.games_played > 0:
                score = scoreboard.get_score()
                pizza_caught = scoreboard.get_caught_pizza()
                poison_caught = scoreboard.get_caught_poison()
                displayScore = DisplayScore(screen, settings, score,
                                            pizza_caught, poison_caught)
                displayScore.blitme()

            if settings.games_played < 1:
                instructions.blitme()

        # Display scoreboard
        scoreboard.blitme()
        pygame.display.flip()
예제 #10
0
def run_game():
    # Get access to our game settings
    settings = Settings()

    # initialize game
    pygame.init()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height), 0, 32)
    clock = pygame.time.Clock()
    scoreboard = Scoreboard(screen, settings)
    play_button = Button(
        screen, settings.screen_width / 2 - settings.button_width / 2,
        settings.screen_height / 2 - settings.button_height / 2, settings,
        "Start Balloon Ninja")
    game_over_button = Button(
        screen, play_button.x_position,
        play_button.y_position - 2 * settings.button_height, settings,
        "Game Over")
    instructions = Instructions(screen, settings)
    # Create a list to hold our balloons, and our kittens
    balloons = []
    #kittens = []

    # Create our dagger
    sword = Sword(screen, settings.scoreboard_height)

    # Create our game engine, with access to appropriate game parameters:
    engine = Engine(screen, settings, scoreboard, balloons, sword)

    # main event loop
    while True:
        rcreen, center = ball.getit(settings.screen_width,
                                    settings.screen_height)
        img = pygame.transform.flip(
            pygame.transform.rotate(pygame.surfarray.make_surface((rcreen)),
                                    270), True, False)

        time_passed = clock.tick(50)
        if center is None or center[0] is None:
            mousex, mousey = pygame.mouse.get_pos()[0], pygame.mouse.get_pos(
            )[1]
        else:
            mousex, mousey = center
        mouse_x, mouse_y = pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]
        engine.check_events(play_button, mouse_x, mouse_y)
        # Redraw the empty screen before redrawing any game objects
        screen.blit(img, (0, 0))

        if settings.game_active:
            # Update the sword's position and check for popped or disappeared balloons
            engine.update_sword(mousex, mousey)
            engine.check_balloons(time_passed, mousex, mousey)

            # If all balloons have disappeared, either through popping or rising,
            #  release a new batch of balloons.
            if len(balloons) == 0:
                # If we are not just starting a game, increase the balloon speed and points per balloon,
                #  and increment batches_finished
                if scoreboard.balloons_popped > 0:
                    #  Increase the balloon speed, and other factors, for each new batch of balloons.
                    settings.balloon_speed *= settings.speed_increase_factor
                    settings.kitten_ratio *= settings.speed_increase_factor
                    settings.points_per_balloon = int(
                        round(settings.points_per_balloon *
                              settings.speed_increase_factor))
                    scoreboard.batches_finished += 1
                # If player has completed required batches, increase batch_size
                if scoreboard.batches_finished % settings.batches_needed == 0 and scoreboard.batches_finished > 0:
                    settings.batch_size += 1
                engine.release_batch()
        else:
            # Game is not active, so...
            #  Show play button
            play_button.blitme()
            #  Show instructions for first few games.
            if settings.games_played < 3:
                instructions.blitme()
            #  If a game has just ended, show Game Over button
            if settings.games_played > 0:
                game_over_button.blitme()

        # Display updated scoreboard
        scoreboard.blitme()

        # Show the redrawn screen
        pygame.display.flip()
예제 #11
0
def run_game():
    # access to settings
    #width,height=800,600
    settings =Settings()
    #initialize game
    pygame.init()
    sound= 'resources/back_sound.mp3'
    pygame.mixer.init()
    pygame.mixer.music.load(sound)
    pygame.mixer.music.play(-1)
    pygame.event.wait()
    screen=pygame.display.set_mode((settings.width,settings.height),0,32)

    pygame.display.set_caption("PopBob")
    clock =pygame.time.Clock()
    scoreboard = Scoreboard(screen, settings)
    play_button = Button(screen, settings.width/2-settings.button_width/2,
                            settings.height/2-settings.button_height/2, settings, "Play")
    game_over_button = Button(screen,play_button.x_position, play_button.y_position-2*settings.button_height,
                            settings, "Game Over")
    #balloons=[Balloon(screen, settings.balloon_speed)]
    # scoreboard_height=50
    # game play params
    #balloon_speed= 0.1
    #points_per_hit=10
    instructions = Instructions(screen, settings)
    #scoreboard=Scoreboard(screen, settings.scoreboard_height)
    balloons =  []
    fish = []
    #spawn_balloon(screen, settings, balloons)
    # balloons=[Balloon(screen, settings.balloon_speed)]

    sword=Sword(screen, settings.scoreboard_height)
    #new_balloon=Balloon(screen)
    #bg_image=pygame.image.load('resources/back_pop_ga.jpg')

    engine = Engine(screen, settings, scoreboard, balloons, fish, sword)

    while 1:
        time_passed =  clock.tick(50)
        mouse_x,mouse_y  = pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]
        engine.check_events(play_button,  mouse_x,  mouse_y)
        print (pygame.mouse.get_pos())

        screen.blit(settings.bg_image,(0,0))

        if settings.game_active:
            engine.update_sword(mouse_x, mouse_y)
            engine.check_balloons(time_passed)
            engine.check_fishes(time_passed)

            if len(balloons)==0:
                if scoreboard.balloons_popped >0:
                    settings.balloon_speed *= settings.speed_increase_factor
                    settings.fish_ratio *= settings.speed_increase_factor
                    settings.points_per_hit = int(round(settings.points_per_hit * settings.speed_increase_factor))
                    scoreboard.batches_finished +=1

                if scoreboard.batches_finished % settings.batches_needed == 0 and scoreboard.batches_finished>0:
                    settings.batch_size+=1
                engine.release_batch()
        else :
            play_button.blitme()
            if settings.games_played < 3 :
                instructions.blitme()
            if settings.games_played >0:
                game_over_button.blitme()
        #displaying the scoreboard
        scoreboard.blitme()

        pygame.display.flip()
                        else:
                            exe_cycles += 2 * (int(self.config[0]['Main memory']) + int(self.config[0]['D-Cache'])) + \
                                          int(self.config[0]['D-Cache']) - 1

            return exe_cycles


if __name__ == '__main__':

    tabu = []
    pipe_obj = Pipeline()
    list_of_inst_obj = []

    # creating the instruction objects
    for instruct in pipe_obj.inst[0]:
        list_of_inst_obj.append(Instructions(instruct))

    # assigning the address for each of the instructions
    for i in range(len(list_of_inst_obj)):
        list_of_inst_obj[i].address = i

    # creating a deepcopy of the instructions
    instr_copy = copy.deepcopy(list_of_inst_obj)

    len_of_org_list = len(list_of_inst_obj)

    # creating the blocks for i-cache
    blocks = [[], [], [], []]
    i = 100
    while i > 0:
        i -= 1
예제 #13
0
 def __init__(self):
     self.instructions = Instructions()