def update(self): for event in pygame.event.get(): if event.type == QUIT: self.running = False elif event.type == MOUSEBUTTONDOWN and self.hovered_btns: self.snd("click").play() clicked = self.hovered_btns[0] if clicked.name == "start": color_choice = ColorChoice(self.display, self.clock) color_choice.run() elif clicked.name == "instructions": i = Instructions(self.display, self.clock) i.run() elif clicked.name == "highscores": highscores = HighScores(self.display, self.clock) highscores.run() elif clicked.name == "quit": self.running = False elif event.type == KEYDOWN: if event.key == K_m: self.music_paused = not self.music_paused if self.music_paused: pygame.mixer.music.unpause() else: pygame.mixer.music.pause()
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()
def doInstructions(): ''' Creates and runs the instructions screen ''' instructions = Instructions(screen, background) doneInstructions = instructions.createInstuctionsScreen() if doneInstructions == True: doMenu()
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))
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)
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)
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
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()
class Experiment(): 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) def trial(self, stim, corr): self.canvas.fixcross() core.wait(0.5) self.canvas.clear() self.canvas.show() core.wait(0.25) pre_stim_resps = event.getKeys() self.canvas.text(stim) #New way to get accurate ms timing trial_clock = core.Clock() self.canvas.win.callOnFlip(trial_clock.reset) self.canvas.show() resp = event.waitKeys(timeStamped=trial_clock) #If statement to deal with case when participants are getting RM tested- #no feedback except telling them not to press random keys if resp[0][0] != corr and not (corr == self.responsekeys["pm"] and resp[0][0] == self.responsekeys["word"]): self.canvas.clear() self.canvas.text("INCORRECT") self.canvas.show() core.wait(1) self.canvas.clear() self.canvas.show() # return response, RT, list of pre stimulus responses return resp[0][0], resp[0][1], pre_stim_resps def print_instructions(self, instructions, delay, waitkey=None, size=None, height=None, wrapWidth=None): self.canvas.clear() self.canvas.text(instructions, height=height, wrapWidth=wrapWidth) self.canvas.show() core.wait(delay) if event.getKeys(['escape']): self.canvas.close_display() core.quit() if (waitkey is not None): resp = event.waitKeys( keyList=[waitkey, 'escape'], timeStamped=True) if (resp[0][0] == 'escape'): self.canvas.close_display() core.quit() def block_leadup(self, btype): block_instructions, recmem_instructions1, recmem_instructions2, response_instructions = self.instructions.block_instructions( btype) self.print_instructions( block_instructions, instruct_delay, 'space', height=0.085, wrapWidth=1.65) self.print_instructions( recmem_instructions1, memorize_delay, height=0.085, wrapWidth=1.65) self.print_instructions( recmem_instructions2, instruct_delay, 'space', height=0.085, wrapWidth=1.65) self.recmem_practice(btype) self.canvas.clear() self.print_instructions( response_instructions, instruct_delay, 'n', height=0.085, wrapWidth=1.65) self.puzzle() def block_main(self, btype): choices1, RTs1, pre_stim_resps1 = self.block(self.design.data['day_' + str(self.day) + '_block_' + str( self.blocknum)].loc[0:first_trials, 'stim'], self.design.data['day_' + str(self.day) + '_block_' + str( self.blocknum)].loc[0:first_trials:, 'C']) self.print_instructions( "Please take a break for one minute.", break_delay) self.print_instructions( "Press space to begin the task again.", 0, waitkey='space') # Mid block break choices2, RTs2, pre_stim_resps2 = self.block(self.design.data['day_' + str(self.day) + '_block_' + str( self.blocknum)].loc[(first_trials+1):second_trials, 'stim'].tolist(), self.design.data['day_' + str(self.day) + '_block_' + str( self.blocknum)].loc[(first_trials+1):second_trials:, 'C'].tolist()) # Combine data from the halves and save choices = choices1 + choices2 RTs = RTs1 + RTs2 pre_stim_resps = pre_stim_resps1 + pre_stim_resps2 perf = pd.DataFrame({'RT': RTs, 'R': choices, 'prestim_R': pre_stim_resps, 'block': self.blocknum, 'day': self.day, 'cond': btype}) self.perf_data['day_' + str(self.day) + '_block_' + str(self.blocknum)] = pd.concat([ self.design.data['day_' + str(self.day) + '_block_' + str( self.blocknum)], perf], axis=1, sort=False) def block_ending(self, btype): self.recmem_test(btype) if (btype == 'multi'): self.print_instructions( ("Thank you. You no longer need to remember your target words." " In fact, you will not be presented those words again in this" " experiment. Press space to continue."), 0, waitkey="space") else: self.print_instructions( ("Thank you. You no longer need to remember your target word." " In fact, you will not be presented that word again in this" " experiment. Press space to continue."), 0, waitkey="space") if self.blocknum == 1: self.print_instructions( "Please have a break for two minutes.", break_time) self.blocknum += 1 def run_block(self, btype): self.block_leadup(btype) self.block_main(btype) self.block_ending(btype) # loads up practice stimuli, runs practice block def practice_block(self): stim = pd.read_csv("tmp/p"+str(self.participantid)+"_practice.csv") stim = stim.sample(frac=1).reset_index() self.print_instructions(self.instructions.practice_instructions( ), instruct_delay, 'space', height=0.075, wrapWidth=1.65) choices, RTs, pre_stim_resps = self.block(stim["stim"], stim["C"]) perf = pd.DataFrame({'stim': stim.loc[range(0, len(RTs)), "stim"], 'S': stim.loc[range(0, len(RTs)), "S"], 'C': stim.loc[range(0, len(RTs)), "C"], 'RT': RTs, 'R': choices, 'prestim_R': pre_stim_resps, 'day': self.day, 'cond': 'practice'}) perf.to_csv("data/practice_p" + str(self.participantid) + "_day_" + str(self.day) + ".csv") def run_both_blocks(self): for block in range(0, 2): self.run_block(self.counterbalance[self.day-1, block]) def block(self, trials, corrs): RTs = [] choices = [] pre_stim = [] ntrials = len(trials) if pilot: ntrials = 1 for i in range(0, ntrials): choice, RT, pre_stim_resps = self.trial(trials[i], corrs[i]) RTs.append(RT) choices.append(choice) pre_stim.append(pre_stim_resps) core.wait(0.5) if event.getKeys(['escape']): self.canvas.close_display() core.quit() return choices, RTs, pre_stim '''fairly cooked. Before each block, participants do a recognition memory task to make sure they perfectly recall the items. The recognition memory task involves 50% non-targets and 50% target items. I have stored a list of non-targets in a separate csv, which are shuffled when the experiment is initialised. However, I was concerned that this list might run out if people kept getting the RM task wrong. Thus there is a check at the start to make sure there are enough targets, and if not then shuffle a new RM target list from scratch.''' def recmem_newstim(self, btype, n_copies, n_nontargets): # Shuffle in new rec-mem non-targets each loop from a csv full_nontargets = pd.read_csv("tmp/p" + str(self.participantid) + "recmem_nontargets" + ".csv") full_nontargets.dropna(how="all", inplace=True) # if there's not enough targets, re-generate them from scratch if (len(full_nontargets) < n_nontargets): self.design.gen_recmem_nontargets(self.participantid) full_nontargets = full_nontargets.append(pd.read_csv("tmp/p" + str(self.participantid) + "recmem_nontargets" + ".csv")) full_nontargets.reset_index(inplace=True, drop=True) nontargets = full_nontargets.copy().iloc[0:n_nontargets, 1].to_frame() next_nontargets = full_nontargets.copy( ).loc[range(n_nontargets, len(full_nontargets)), :] next_nontargets.reset_index(inplace=True, drop=True) next_nontargets.to_csv("tmp/p" + str(self.participantid) + "recmem_nontargets" + ".csv", index=False) if (btype == 'multi'): targets = self.todays_multi.copy() else: targets = pd.concat([self.todays_single.copy()] * 8, ignore_index=True) nontargets['corr'] = "n" nontargets = nontargets.rename(columns={'0': 'Words'}) targets['corr'] = "y" stim = pd.concat([nontargets, targets]) stim = stim.sample(frac=1) stim.reset_index(inplace=True, drop=True) #Copy/shuffle/append the stimulus list to make as many trials as desired for i in range(1, n_copies): stim2 = stim.copy() stim2 = stim2.sample(frac=1) stim2.reset_index(inplace=True, drop=True) stim = stim.append(stim2) stim.reset_index(inplace=True, drop=True) return(stim) '''runs the recognition memory task until perfect accuracy. In the single target condition, participants are presented one target word and one non-target word. 8 of each in the multi target condition''' def recmem_practice(self, btype): # run recmem trials til 100% accuracy while True: # add in a check that there are enough recmem targets in the .csv # If <designed nontargets, create a new file stim = self.recmem_newstim(btype, n_copies=2, n_nontargets=8) choices, RTs, pre_stim_resps = self.block( stim.iloc[:, 0], stim.iloc[:, 1]) # Update recmem saved data perf = pd.DataFrame({'stim': stim.loc[range(0, len(RTs)), 'Words'], 'C': stim.loc[range(0, len(RTs)), 'corr'], 'RT': RTs, 'R': choices, 'prestim_R': pre_stim_resps, 'block': self.blocknum, 'day': self.day, 'cond': btype, 'count': self.rm_count } ) if (self.rm_count == 1): perf.to_csv("data/RM_p" + str(self.participantid) + "_day_" + str(self.day) + ".csv", index=False) elif(self.rm_count > 1): old_perf = pd.read_csv( "data/RM_p" + str(self.participantid) + "_day_" + str(self.day) + ".csv") new_perf = old_perf.append(perf) new_perf.to_csv("data/RM_p" + str(self.participantid) + "_day_" + str(self.day) + ".csv", index=False) # rm_count keeps track of how many tries they had at the RM task self.rm_count += 1 # check if all answers correct match = [i == j for i, j in zip( choices, stim['corr'].values.tolist())] if all(match): self.print_instructions( ('100% accuracy, great job!' ' Press space to continue'), 3, 'space') break else: if (btype == 'single'): self.print_instructions( ('You were not 100% accurate, please study the target word' ' and try again. Press space when ready.'), 3, 'space') self.print_instructions("Here is the target word: \n\n" + ' '.join(self.todays_single.values.flatten()) + "\n\n Press space when you are ready for another test.", 3, 'space') else: self.print_instructions( ('You were not 100% accurate, please study the target words' ' and try again. Press space when ready.'), 3, 'space') self.print_instructions("Here are the target words: \n\n" + ' '.join(self.todays_multi.values.flatten()) + "\n\n Press space when you are ready for another test.", 3, 'space') # Runs the RM test once (to get recognition after the block) def recmem_test(self, btype): if (btype == 'multi'): RM1 = "words." RM2 = "from your target list" else: RM1 = "word." RM2 = "your target word" self.print_instructions( ("Great work completing the block!\n\n" " We now wish to test your memory for your target " + RM1 + "\n\n You will be presented words one by one. Press the 'y' key if the " "word is " + RM2 + ", otherwise press the 'n' key. \n\n" "Press space to begin."), 3, 'space') stim = self.recmem_newstim(btype, n_copies=1, n_nontargets=24) choices, RTs, pre_stim_resps = self.block( stim.iloc[:, 0], stim.iloc[:, 1]) # Update recmem saved data perf = pd.DataFrame({'stim': stim.loc[range(0, len(RTs)), 'Words'], 'C': stim.loc[range(0, len(RTs)), 'corr'], 'RT': RTs, 'R': choices, 'prestim_R': pre_stim_resps, 'block': self.blocknum, 'day': self.day, 'cond': btype } ) perf.to_csv("data/test_RM_p" + str(self.participantid) + "_day_" + str(self.day) + "_" + str(btype) + ".csv", index=False) # distractor puzzle before they complete the task def puzzle(self): self.print_instructions(('Before you complete the lexical decision trials we would like you' ' to complete a sudoku puzzle.\n\n Please find the puzzle on your desk. ' 'You have three minutes. Do not worry if there is not time to finish the puzzle.'), puzzle_time) self.print_instructions(("It is now time to begin the lexical decision trials. \n\n" "Please rest your fingers on the response keys." " Press space when you are ready to begin."), 1, 'space') # saves of the main data at the end of the experiment. def save_data(self): for j in range(1, self.design.blocks+1): data = self.perf_data["day_" + str(self.day) + "_block_" + str(j)].copy() if j == 1: day_dats = data else: day_dats = day_dats.append(data, ignore_index=True) day_dats.to_csv("data/p" + str(self.participantid) + "_day_" + str(self.day) + ".csv")
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
def run_game(): # Get access to our game settings settings = Settings() engine = Engine() # 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, "Play 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) # main event loop while True: # Advance our game clock, get the current mouse position, and check for new events time_passed = clock.tick(50) mouse_x, mouse_y = pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1] engine.check_events(settings, scoreboard, sword, play_button, mouse_x, mouse_y, balloons) # Redraw the empty screen before redrawing any game objects screen.fill(settings.bg_color) if settings.game_active: # Update the sword's position and check for popped or disappeared balloons engine.update_sword(sword, mouse_x, mouse_y, settings) engine.check_balloons(balloons, kittens, sword, scoreboard, screen, settings, time_passed) engine.check_kittens(kittens, sword, scoreboard, screen, settings, time_passed) # 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(screen, settings, balloons, kittens) 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()
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()
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()
def title(self): print "TITLE SCREEN" #set up game title self.imperial_music = pygame.mixer.Sound("media/audio/imperialMarch.wav") #loop to wait for clicks #while title running variable #variable to keep track of when title options should be running while self.titleRunning: #self.imperial_music.play() for event in pygame.event.get(): if event.type == QUIT: #if user clicks red x in corner, exit pygame.quit() sys.exit() elif event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: if pygame.mouse.get_pressed()[0]: #if left mouse button is clicked mouse_x, mouse_y = pygame.mouse.get_pos() #if event.button == 1: should do same thing #if mouse pos is in single player box, get ship selection ready if self.player1pos.collidepoint(mouse_x, mouse_y): print "First option pressed" self.gs.screen.fill(self.gs.black) #self.imperial_music.stop() selection_screen = ShipSelect(self.gs) selection_screen.ship_select() #make second 2 options disappear, show ship options as new buttons #if mouse pos is in multiplayer box, wait for connection (?) if self.player2pos.collidepoint(mouse_x, mouse_y): self.connections = not self.connections self.gs.screen.fill(self.gs.black) #Add networking elements here #if mouse pos is in instructions box, open instructions page if self.instpos.collidepoint(mouse_x, mouse_y): #bring up a new instructions screen print "instructions options pressed" self.gs.screen.fill(self.gs.black) instruction_screen = Instructions(self.gs) instruction_screen.readInstructions() #self.titleRunning = False if self.hostPos.collidepoint(mouse_x, mouse_y) and self.connections: selection_screen = ShipSelect(self.gs) selection_screen.ship_select() self.gs.HOST = 1 elif self.joinPos.collidepoint(mouse_x, mouse_y) and self.connections: print "NOT HOST" self.gs.HOST = 2 self.titleRunning = False self.gs.screen.fill(self.gs.black) self.gs.screen.blit(self.titleText, self.titlepos) if not self.connections: self.gs.screen.blit(self.player1Text, self.player1pos) self.gs.screen.blit(self.player2Text, self.player2pos) self.gs.screen.blit(self.instructionText, self.instpos) else: self.gs.screen.blit(self.hostText, self.hostPos) self.gs.screen.blit(self.joinText, self.joinPos) pygame.display.flip()
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()
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))
def __init__(self): self.instructions = Instructions()