def startscreen(): startscreen = 1 background = pygame.image.load('Menu.BMP') icon = pygame.image.load('binaryclock3.BMP') pygame.display.set_icon(icon) width = 432 height = 407 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Binary Clock') meclock = BinaryTime() while startscreen == 1: screen.blit(background, (0, 0)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: startscreen = 0 main() elif event.type == pygame.K_ESCAPE: startscreen = 0 pygame.quit() sys.quit()
def get_batch(self, batch_size, with_labels=False, with_wrong_labels=False, is_random=False): if (with_labels or with_wrong_labels) and not self.with_labels: print_time_info("Error! The engine hasn't initialized with the labels, quit.") sys.quit() if self.counter + batch_size >= self.data_size and not is_random: self.counter = 0 self.shuffle_data() if self.channels == 1: grayscale = True else: grayscale = False if is_random: images_path = np.random.choice(self.images, batch_size) else: images_path = self.images[self.counter: self.counter + batch_size] images = get_images( images_path = images_path, input_shape = self.input_shape, output_shape = self.output_shape, crop = self.crop, grayscale = grayscale ) if with_labels: labels = self.get_labels(images_path) if with_wrong_labels: wrong_labels = self.get_random_labels(batch_size) if not is_random: self.counter += batch_size batch = {"images": images} if with_labels: batch["labels"] = labels if with_wrong_labels: batch["wrong_labels"] = wrong_labels return batch
def __init__(self): # Check for files if path.isfile(testData) and path.isfile(trainData): pass else: print "Traning or Test File Not found!" sys.quit(0)
def test(self): checker, before_counter = self.load_model() if not checker: print_time_info("There isn't any ready model, quit.") sys.quit() for i in range(32): batch_A, batch_B = self.get_batch(self.batch_size, is_random=True) fake_A, fake_B, cycle_A, cycle_B = self.sess.run( [self.fake_A, self.fake_B, self.cycle_A, self.cycle_B], feed_dict={self.real_A: batch_A, self.real_B: batch_B}) fake_A, fake_B = fake_A[0], fake_B[0] cycle_A, cycle_B = cycle_A[0], cycle_B[0] image_real_A_path = os.path.join(self.images_dir, "{}_test{}_real_A.jpg".format(before_counter, i)) image_real_B_path = os.path.join(self.images_dir, "{}_test{}_real_B.jpg".format(before_counter, i)) image_fake_A_path = os.path.join(self.images_dir, "{}_test{}_fake_A.jpg".format(before_counter, i)) image_fake_B_path = os.path.join(self.images_dir, "{}_test{}_fake_B.jpg".format(before_counter, i)) image_cycle_A_path = os.path.join(self.images_dir, "{}_test{}_cycle_A.jpg".format(before_counter, i)) image_cycle_B_path = os.path.join(self.images_dir, "{}_test{}_cycle_B.jpg".format(before_counter, i)) imsave(image_real_A_path, np.squeeze(batch_A)) imsave(image_real_B_path, np.squeeze(batch_B)) imsave(image_fake_A_path, np.squeeze(fake_A)) imsave(image_fake_B_path, np.squeeze(fake_B)) imsave(image_cycle_A_path, np.squeeze(cycle_A)) imsave(image_cycle_B_path, np.squeeze(cycle_B)) print_time_info("Testing end!")
def main(original_text): """main function""" #original_text = " ".join(sys.argv[1:]) if len(original_text) > 600: print("You can't check more than 600 characters at a time.") sys.quit() fixed_text = original_text results = get_ginger_result(original_text) # Correct grammar if(not results["LightGingerTheTextResult"]): print(original_text) sys.quit() # Incorrect grammar color_gap, fixed_gap = 0, 0 for result in results["LightGingerTheTextResult"]: if(result["Suggestions"]): from_index = result["From"] + color_gap to_index = result["To"] + 1 + color_gap suggest = result["Suggestions"][0]["Text"] # Colorize text colored_incorrect = ColoredText.colorize(original_text[from_index:to_index], 'red')[0] colored_suggest, gap = ColoredText.colorize(suggest, 'green') original_text = original_text[:from_index] + colored_incorrect + original_text[to_index:] fixed_text = fixed_text[:from_index-fixed_gap] + colored_suggest + fixed_text[to_index-fixed_gap:] color_gap += gap fixed_gap += to_index-from_index-len(suggest) #print("from: " + original_text) print(fixed_text)
def loadImages(self, urls): nodepaths=[] # z is the vertical axis in the 3D world sx,sz = getattr(self.config,'f_scale',[1.0,1.0]) horGap = getattr(self.config,'f_horgap',0.1) vertGap = getattr(self.config,'f_vertgap',0.1) # for horizontal distribution # incX: distance between centers # inc = vertGap + 2.0*sx # startX is the first position (all the space / 2) incX = vertGap + 2.0*sx startX = - (len(urls)-1)*incX/2.0 # load each texture # the screen x coord in 2D goes from -1.6 to 1.6 (left to right horizontally) # the screen z coord in 2D goes from -1 to 1 (top-down vertically) try: for i in urls: # no need to reparent to render or aspect or anything!!!! nodepath = OnscreenImage( image = i , scale = Vec3(sx,1.0,sz)) nodepath.setTransparency(TransparencyAttrib.MAlpha) nodepath.setX(startX) startX += incX nodepaths.append(nodepath) except: print "Fatal error, could not load texture file or model in models/plane" print "Check the file path" sys.quit() return nodepaths
def main(): setup() iteration = 0 while True: action = input("> ") # Loop through control options if action == 'w': # Forward GPIO.output(GPIO_Dir["F"], True) elif action == 'a': # Left GPIO.output(GPIO_Dir["L"], True) elif action == 'd': # Right GPIO.output(GPIO_Dir["R"], True) elif action == 's': # Reverse GPIO.output(GPIO_Dir["R"], True) elif action == " ": # Stop reset() elif action == "e": # End reset() GPIO.cleanup() import sys sys.quit() Cam.take_picture(action, iteration) iteration += 1
def create_wav_chunks(timestamps, full_audio, audio_file, corpus, age_in_days, child_id='child_id', its="its"): print("creating wav chunks") output_dir = '/'.join(audio_file.split('/') [:-1]) + "/output/" # path to the output directory if not os.path.exists(output_dir): os.makedirs( output_dir) # creating the output directory if it does not exist # audio_file_id = audio_file.split('/')[-1][:-4] for ts in timestamps: onset, offset = ts[0], ts[1] if len(its_files) > 1: print("More than one its file! Panic", its_files) sys.quit() its_name = str(its_files)[-29:len(str(its_files)) - 6] difference = float(offset) - float(onset) if difference < 1.0: tgt = 1.0 - difference onset = float(onset) - tgt / 2 offset = float(offset) + tgt / 2 else: new_dur, remain = check_dur(offset - onset) onset = float(onset) - remain / 2 offset = float(offset) + remain / 2 new_audio_chunk = full_audio[float(onset) * 1000:float(offset) * 1000] new_audio_chunk.export("{}_{}_{}_{}_{}_{}.wav".format( output_dir + corpus, child_id, str(age_in_days), its_name, onset, offset), format("wav"), bitrate="192k")
def run(self, screen): def blit(screen): screen.blit(self.background, (0,0)) for image, rect in zip(self.images, self.rects): if image != self.images[self.index]: screen.blit(image, rect) screen.blit(self.himages[self.index], self.rects[self.index]) pygame.display.update() done = False blit(screen) while not done: for event in pygame.event.get(): if event.type == QUIT: sys.quit() if event.type == KEYDOWN: if event.key == K_DOWN: self.index = min(self.index+1, len(self.images)-1) blit(screen) if event.key == K_UP: self.index = max(self.index-1, 0) blit(screen) if event.key == K_RETURN: done = True return self.index
def basic_compute_loop(compute_function, looper, run_parallel=True, debug=None): """ Canonical form of the basic compute loop. !!! remove this from contacts.py when it works """ #---send the frame as the debug argument if debug != None and debug != False: fr = debug incoming = compute_function(**looper[fr]) import ipdb ipdb.set_trace() sys.quit() start = time.time() if run_parallel: incoming = Parallel(n_jobs=8, verbose=10 if debug else 0)( delayed(compute_function, has_shareable_memory)(**looper[ll]) for ll in framelooper(len(looper), start=start)) else: incoming = [] for ll in framelooper(len(looper)): incoming.append(compute_function(**looper[ll])) return incoming
def __init__(self, train_file, test_file): # Check for files if path.isfile(train_file) and path.isfile(train_file): pass else: print "Traning or Test File Not found!" sys.quit(0)
def run(self): for users in self.users_dict: for elem in self.dict:# # if the password is empty if elem == ' ': cmd = "mysql -u%s -e\"show databases\"" %(users.strip("\n")) else: cmd = "mysql -u%s -p%s -e\"show databases\"" %(users.strip("\n"),elem.strip("\n")) p = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE) for line in iter(p.stdout.readline, ''): if line.startswith("Database"): if self.options.force == True: print "[+] We are in !" print "[+] Username: '******' have the following password: '******' " %(users.strip("\n"),elem.strip("\n")) print "\t[+] Execute this string to get list of users:" print "\t\t[+] mysql -u%s -p%s -e\"select user,password from mysql.user;\""%(users.strip("\n"),elem.strip("\n")) print "Done!" sys.quit(1) else: print "[+] Username: '******' have the following password: '******' " %(users.strip("\n"),elem.strip("\n")) for line in iter(p.stderr.readline, ''): if line.startswith("ERROR 2003"): print "[!] Unable to Connect to database" print "[!] Quitting" sys.exit(1) elif line.startswith("ERROR 1045"): if self.options.verbose == False: print "[!] Failed Password: "******"\n") # Clean after every try! sys.stdout.flush() sys.stderr.flush() p.wait() print "Done!"
def playerMove(grid, playerList): pygame.draw.rect(SCREEN, BLACK, (0, 75 + ((BARRIER + (CIRCLE_RADIUS * 2)) * NUM_OF_ROWS), SCREEN_WIDTH, 20)) prompt = MESSAGE_FONT.render( playerList[0][0] + ", PLACE YOUR CHIP IN A COLUMN. TO QUIT, PRESS '0'", True, WHITE) SCREEN.blit(prompt, [60, 75 + ((BARRIER + (CIRCLE_RADIUS * 2)) * NUM_OF_ROWS)]) pygame.display.update() xCoor, yCoor = 0, 0 while True: for e in pygame.event.get(): if e.type == pygame.KEYDOWN: if pygame.key.name(e.key) == '0': pygame.quit() sys.quit() elif pygame.key.name(e.key) >= '1' and pygame.key.name( e.key) <= str(NUM_OF_COLUMNS): pressedKey = int(pygame.key.name(e.key)) for spot in range(NUM_OF_ROWS - 1, -1, -1): if grid[spot][pressedKey - 1] == EMPTY: xCoor, yCoor = spot, pressedKey - 1 grid[spot][pressedKey - 1] = playerList[0][1] tempCoordinates = (50 + ((pressedKey - 1) * 85), 50 + (spot * 85)) pygame.draw.circle(SCREEN, playerList[0][1], tempCoordinates, CIRCLE_RADIUS) pygame.display.update() return [yCoor, xCoor]
async def read(self, event_queue): #Axis 1: left sticks #Axis 3: right sticks if not self.axis_data: self.axis_data = {} while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.quit(0) break elif event.type == pygame.JOYAXISMOTION: self.axis_data[event.axis] = round(event.value,2) # axis_left = round(self.controller.get_axis(1),4) # axis_right = round(self.controller.get_axis(3),4) print (self.axis_data) # writing to vars goes here # print("Left:") # print(axis_left) # print("Right:") # print(axis_right) # os.system('cls') asyncio.get_event_loop()
def start_telemetry(robot_ip, robot_port, client_port): global RUN_TELEMETRY_THREAD global telemetry_log PKT_SIZE = 1024 if DEBUG_TELEMETRY: print("[MSG]> start_telemetry_client()") if (RUN_TELEMETRY_THREAD == False): sys.quit() TEL_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) TEL_socket.bind(('0.0.0.0', client_port)) total_bytes_recv = 0 try: while RUN_TELEMETRY_THREAD: telemetry_data = TEL_socket.recv(PKT_SIZE) telemetry_data = telemetry_data.decode() if not telemetry_data: if DEBUG_TELEMETRY: print('[MSG]> error: connection closed') break if DEBUG_TELEMETRY: print(telemetry_data) d = telemetry_data.split(',') if (d[0] == '$MOT'): if d[1]: mot_data = "Motor: {}".format(d[1]) func_success_msg(motor_log, mot_data) except Exception as e: if DEBUG_TELEMETRY: print("[MSG]> exception: {}".format(str(e))) finally: TEL_socket.close() if DEBUG_TELEMETRY: print("[MSG]> telemetry channel closed") func_error_msg(tag_log, "Telemetry stopped")
def init( self, spot_dict ): if self.number is not spot_dict['number']: quit() self.vertices = spot_dict['vertices'] self.base_nEdges = spot_dict['base_nEdges'] self.monthly = spot_dict['monthly'] self.handicap = spot_dict['handicap']
def loading_picture(): global loading_screen global anim_running display_logo() if loading_screen == True: anim_running = True for i in range(0, 253): asurf = pygame.image.load( os.path.join("images", "loading", str(i) + ".gif") ).convert() gameDisplay.blit( asurf, (int(display_width_height[0] / 3), int(display_width_height[1] / 3)), ) pygame.display.update() time.sleep(0.03) else: time.sleep(0.03) anim_running = False else: gameDisplay.fill(white) waiting = font.render("Connectivity Error Please try Later", 1, black) asurf = pygame.image.load(os.path.join("images", "error-internet.png")) gameDisplay.blit( asurf, (display_width_height[0] / 4, display_width_height[1] / 4) ) gameDisplay.blit(waiting, (0, 0)) pygame.display.update() time.sleep(5) pygame.quit() quit()
def wait_for_countdown(self): try: self.driver.find_element_by_class_name('countdownPopup') except KeyboardInterrupt: sys.quit() except Exception as e: self.ready = True
def OnMenuQuit(self, event): # check to see if we want to save our work # any other user cleanups. # and die: sys.quit()
def menu_loop(): while True: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.KEYDOWN: game_loop() if event.type == pygame.QUIT: quit() window.fill(colors.white) window.blit( constants.logo_image, ( # blits the logo to the screen constants.window_width * 0.5 - constants.logo_image_dimensions[0] // 2, constants.window_height * 0.1)) utils.show_text( "Press start", monospace_font, (constants.window_width * 0.4, constants.window_height * 0.7), colors.black, window) pygame.display.update() game_clock.tick(constants.framerate)
def showPause(): print("Pause") pauseFlickerCounter = 0.0 # Counter for changing the pause screen background while Data.pause == True: print("in pause loop") for event in pygame.event.get(): # check for user input if event.type == pygame.KEYDOWN and (event.key == pygame.K_SPACE or event.key == pygame.K_ESCAPE or event.key == pygame.K_p): print("break pause loop back to game") Data.pause = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_q: print("quit from pause loop") pygame.quit() sys.quit() # flicker pause screen background pauseFlickerCounter += clock.tick(60) backgroundImage = 'paused_1.png' if pauseFlickerCounter > 1000: backgroundImage = 'paused_2.png' if pauseFlickerCounter > 2000: pauseFlickerCounter = 0 startScreen = Background(backgroundImage, [0,0]) screen.fill(BLACK) screen.blit(startScreen.image, startScreen.rect) pygame.display.flip()
def get_photos(): data_term = input("User to get photos links (empty if you dont want this): ") if (data_term == ""): sys.quit("Closed :)") driver.get("https://www.instagram.com/" + data_term + "/") time.sleep(0.5) print("") try: driver.find_element_by_css_selector(".QlxVY") print("User '" + data_term + "' have an private account!") print("") wwwa99 = input("Try other user? (y/n): ") if wwwa99 == "y" or wwwa99 == "Y" or wwwa99 == "yes" or wwwa99 == "Yes": get_photos() else: pass except NoSuchElementException: photos_links = [] all_photos = driver.find_elements_by_css_selector('.FFVAD') for pht in all_photos: photos_links.append(pht.get_attribute("src")) i = 0 while i < len(photos_links): print(photos_links[i]) i += 1
def __init__(self, **kwargs): """ world is a reference to the main class """ # build basic element super(HUDText, self).__init__(**kwargs) # this defines: # self.sceneNP and self.hudNP text = getattr(self.config, 'text', None) if text is None: printOut("Missing 'text' attribute in experiment file", 0) sys.quit() # text is hung by the aspect2D, which is -1 to 1 # in height and w/h in width. leftBorder = - base.win.getXSize() / float(base.win.getYSize()) tN = TextNode(self.config.name) tN.setAlign(TextNode.ALeft) tNP = NodePath(tN) tNP.setName(self.config.name) tNP.setScale(0.09) topLeft = getattr(self.config,'tuple_topLeft',[0.0,0.0]) tNP.setPos(leftBorder + topLeft[0], 0, 1.0 - topLeft[1]) tN.setText(self.config.text) # attach the text node to the HUD section tNP.reparentTo(self.hudNP) # hide the whole node self.textNode = tN self.hideElement()
def run(): if(len(sys.argv)==0): print("Add Filepath") print(" ") sys.quit() filename = sys.argv[1] main(filename)
def simpleBattle(player, enemy): while not player.isFleeing: selectBattleOption(player, enemy) if player.isFleeing == True: print("") time.sleep(3) break elif isDead(enemy): print("") time.sleep(3) print("ENEMY DEFEATED") time.sleep(3) break print("") print("Enemy Health: ", enemy.health, " / ", enemy.maxHealth) time.sleep(3) player.health = enemy.attack(player.defenseValue, player.health, player.name) print("") print("Player Health: ", player.health, " / ", player.maxHealth) if isDead(player): print("") print(player.name + "has been defeated...") time.sleep(3) print("") print("Press enter to quit") cont = input("") sys.quit() time.sleep(3)
def loop_wizualizacja(self, MonteCarlo): while not self.gameExit: # game_loop pygame.display.update() self.clock.tick(self.FPS) for event in pygame.event.get(): # event_loop if event.type == pygame.QUIT: gameExit = True pygame.quit() quit() sys.quit() if event.type == pygame.KEYDOWN: # CZAT if event.key == pygame.K_ESCAPE or event.key == pygame.K_q: gameExit = True pygame.quit() quit() sys.quit() if event.key == pygame.K_KP_ENTER or event.key == pygame.K_SPACE or event.key == pygame.K_s: MonteCarlo.calulatePi(self) if event.type == pygame.VIDEORESIZE: self.window_height = event.h self.window_width = event.w self.__init__()
def DiskTorusT(self, a, zeta): """ The temperature of the torus varies with zeta but not a. There are currently two possibilities for the zeta dependence 1) SINUSOID T = 0.5 * (Tmax + Tmin) + 0.5* (Tmax - Tmin) * cos( zeta - zetaTmax ); 2) POINT The disk torus height and temperature is defined by a set of points, one point per DISKTORUSPARS= line in the parameter file: DISKTORUSPARS= POINT Zeta1 H1 T1 DISKTORUSPARS= POINT Zeta2 H2 T2 . . . . . . . . . . The temperatures are linearly interpolated between the specified points. The Zetas must be in increasing order and disktorus.PointZeta[1] must be 0 degrees (this avoids messy computer code). """ if (zeta > 2 * math.pi): sys.exit("zeta greater than TWOPI in DiskTorusT.") if (zeta < 0.0): sys.exit("zeta less than zero in DiskTorusT.") if (a < (disktorusparams.azero - 0.5 * disktorusparams.awidth)): temperature = 0.0 return temperature if (a > (disktorusparams.azero + 0.5 * disktorusparams.awidth)): temperature = 0.0 return temperature if (disktorusparams.type == "SINUSOID"): temperature = 0.5 * ( disktorusparams.Tmax + disktorusparams.Tmin) + 0.5 * ( disktorusparams.Tmax - disktorusparams.Tmin ) * math.cos(zeta - disktorusparams.ZetaTmax) elif (disktorusparams.type == "POINT"): if (disktorusparams.points == 1): temperature = disktorusparams.PointT[1] else: for i in range(disktorusparams.points): zetalow = disktorusparams.PointZeta[i] Tlow = disktorusparams.PointT[i] if (i < disktorusparams.points): zetahigh = disktorusparams.PointZeta[i + 1] Thigh = disktorusparams.PointT[i + 1] else: zetahigh = 2 * math.pi Thigh = disktorusparams.PointT[1] if ((zeta >= zetalow) and (zeta < zetahigh)): slope = (Thigh - Tlow) / (zetahigh - zetalow) temperature = Tlow + slope * (zeta - zetalow) break else: sys.quit("Unrecognized disk torus type in DiskTorusT.") return temperature
def file_exists(fname): if not os.path.exists(fname): if 'dwell' not in fname: print 'ERROR: ' + str(fname) + 'not found.' sys.quit(1) else: return False return True
def photoPrintSelect(bg_selection, screen_info, DISPLAYSURF): fg_timer = FG_LIMIT + 1 self_timer = 0 print bg_selection print_choice = 0 # 0 as not selected(Print), 1 as Recapture, 2 as Discard all, and re-select Photo Frame screen_info = pygame.display.Info() DISPLAYSURF = pygame.display.set_mode((screen_info.current_w, screen_info.current_h), FULLSCREEN) pygame.mouse.set_pos([screen_info.current_w, screen_info.current_h]) instruction_mask = PngOverlay("count_down_img/print_or_restart.png") instruction_mask.show() # show Photo Result Img_w_bgcolor(bg_selection, WHITE, screen_info, DISPLAYSURF) pygame.display.update() pygame.time.wait(20) while (self_timer < STAGE_LIMIT_CNT) & (print_choice == 0): pygame.time.wait(WAIT_STEP) for event in pygame.event.get(QUIT): print "QUIT" instruction_mask.hide() quit() pygame.quit() sys.quit() for event in pygame.event.get(pygame.KEYDOWN): print "KEY DOWN" if event.key == pygame.K_ESCAPE: instruction_mask.hide() quit() pygame.quit() sys.quit() for event in pygame.event.get(): print event pygame.event.clear() if event.type == pygame.MOUSEBUTTONDOWN: pygame.event.clear() if event.button == 1: # LMB #Left for Re-capture pygame.event.clear() print_choice = 1 # Print if event.button == 3: # RMB #Right for Abort pygame.event.clear() print_choice = 2 # Re capture, don't reselect the frame pygame.event.clear() self_timer = self_timer + 1 # timer ++ # print self_timer # print STAGE_LIMIT_CNT instruction_mask.hide() return print_choice # if while loop expired, return current value
def open(self): switches='-v' if self.keyfile: switches='%s -i %s' % (switches,self.keyfile) if self.port: switches='%s -P %s' % (switches,self.port) if self.username: switches='%s -l %s' % (switches,self.username) if self.ip_version: switches='%s -%s' % (switches,self.ip_version) if self.compression: switches='%s -C' % switches if self.socks_port: switches='%s -D %s' % (switches,self.socks_port) if self.x11: switches='%s -X' % switches if self.agent: switches='%s -agent' % switches else: switches='%s -noagent' % switches if not self.shell: switches='%s -N' % switches if not self.pty: switches='%s -T' % switches for tunnel in self.tunnels: if tunnel.remote: switches='%s -R ' % switches else: switches='%s -L ' % switches if tunnel.listen_addr: switches='%s%s:' % (switches,tunnel.listen_addr) switches='%s%s:' % (switches,tunnel.listen_port) switches='%s%s:' % (switches,tunnel.host_addr) switches='%s%s' % (switches,tunnel.host_port) if self.host: command_line='plink %s %s' % (switches, self.host) else: sys.quit() child=spawn(command_line) self.write_log('Launching command: %s' % command_line) if self.password: child.expect('password:'******'Opened channel for session') self.write_log(child.before) msg='' while child.isalive(): try: ch=child.read(size=1) except TIMEOUT: pass if ch=='\n': self.write_log(msg) msg='' else: msg=msg+ch
def input_data() -> (int, int, str): M = int(input("Enter the value of M: ")) S = int(input("Enter the value of S[0-5]: ")) if S not in range(0, 6): print("S should be in the range of [0-5]") sys.quit() fname = input("Enter the file name: ") return M, S, fname
def game_start(): generate_seed(board_enemy) WIDTH = 20 HEIGHT = 20 MARGIN = 5 #just the intro screen title() pick_ship() #main game loop finish = True choosen = False currentP = True global turn global score_a global score_h global targetMode global shotStack global ai_b targetMode = False shotStack = [] while finish: for event in pygame.event.get(): if score_a == 17 or score_h == 17 or event.type == pygame.QUIT or (event.type == KEYUP and event.key == K_ESCAPE): if score_a == 17 or score_h == 17: winner() pygame.time.wait(5000) pygame.quit() #note this is creates an error in Visual studio but works in a python environment sys.quit() elif event.type == MOUSEBUTTONUP: pos = pygame.mouse.get_pos() if(pos[0]>= 50 and pos[0]<=305 and pos[1]>=200 and pos[1] <= 455 and choosen == False): x = (pos[0]-50) // (WIDTH + MARGIN) y = (pos[1]-200) // (HEIGHT + MARGIN) if x == 10: x = 9 if hit_board[y][x] == "O": hit_board[y][x] = "C" choosen = True else: choosen = False elif(pos[0]>= 355 and pos[0]<=445 and pos[1]>=522 and pos[1] <= 582 and choosen == True and currentP == True): #this is the fire button shot_human(board_enemy,y,x) if ai_b == True: shot_AI_brute(board_mine) else: shot_AI_hunt(board_mine) choosen = False turn = turn + 1 elif choosen == True: choosen = False hit_board[y][x] = "O" elif choosen == False: choosen = False display_board() pygame.display.update()
def power_buttom(self): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() self.screen.blit(pygame.transform.smoothscale(self.exit, (25, 25)), (500, 30)) if click[0] == 1 and 500 <= mouse[0] <= 525 and 30 <= mouse[1] <= 55: pygame.quit() sys.quit()
def DiskTorusT(self, a, zeta): """ The temperature of the torus varies with zeta but not a. There are currently two possibilities for the zeta dependence 1) SINUSOID T = 0.5 * (Tmax + Tmin) + 0.5* (Tmax - Tmin) * cos( zeta - zetaTmax ); 2) POINT The disk torus height and temperature is defined by a set of points, one point per DISKTORUSPARS= line in the parameter file: DISKTORUSPARS= POINT Zeta1 H1 T1 DISKTORUSPARS= POINT Zeta2 H2 T2 . . . . . . . . . . The temperatures are linearly interpolated between the specified points. The Zetas must be in increasing order and disktorus.PointZeta[1] must be 0 degrees (this avoids messy computer code). """ if( zeta > 2*math.pi ): sys.exit("zeta greater than TWOPI in DiskTorusT.") if( zeta < 0.0 ): sys.exit("zeta less than zero in DiskTorusT.") if( a < (disktorusparams.azero - 0.5 * disktorusparams.awidth) ): temperature = 0.0 return temperature if( a > (disktorusparams.azero + 0.5 * disktorusparams.awidth) ): temperature = 0.0 return temperature if( disktorusparams.type == "SINUSOID"): temperature = 0.5 * ( disktorusparams.Tmax + disktorusparams.Tmin ) + 0.5 * ( disktorusparams.Tmax - disktorusparams.Tmin ) * math.cos( zeta - disktorusparams.ZetaTmax ) elif( disktorusparams.type == "POINT"): if( disktorusparams.points == 1 ): temperature = disktorusparams.PointT[1] else: for i in range(disktorusparams.points): zetalow = disktorusparams.PointZeta[i] Tlow = disktorusparams.PointT[i] if( i < disktorusparams.points ): zetahigh = disktorusparams.PointZeta[i+1] Thigh = disktorusparams.PointT[i+1] else: zetahigh = 2*math.pi Thigh = disktorusparams.PointT[1] if( (zeta >= zetalow) and (zeta < zetahigh) ): slope = (Thigh - Tlow) / (zetahigh - zetalow) temperature = Tlow + slope * (zeta - zetalow) break else: sys.quit("Unrecognized disk torus type in DiskTorusT.") return temperature
def check_events(): # loop through all events for event in pygame.event.get(): # window close event? if event.type == pygame.QUIT: sys.quit() # mouse button clicked? if event.type == pygame.MOUSEBUTTONDOWN: global discCol discCol = [255,0,0] # red
def p2e(u): pd = np.size(u, 0) if pd == 3: u_ = u[:2, :] / u[2, :] return u_ elif pd == 2: return u else: print('wrong point format!') sys.quit(1)
def createNewProfile(): newCustomer = raw_input("Are you a new customer? please answer Yes/ No: ") if newCustomer == "Yes": #dbvar = MySQLdb.connect("localhost","root","admin","test") tablepointer = dbvar.cursor() tablepointer.execute("insert into profile (name,lastname,DOB,emailID,address,contactNo,emergencyContactName,emergencyContactNo) values (%s,%s,%s,%s,%s,%s,%s,%s)",(getName(),getlastName(),getdOb(),getemailId(),getAddress(),setContactNum(),setEnergencyContactName(),setEmergencyContactNo())) dbvar.commit() elif newCustomer=="No" or newCustomer=='': print ("Thanks for your time.") sys.quit()
def tag_content(self, line, tag): """returns the content of the tag""" if self.debud_mode: print("text_analyzer.tag_content() , ling:'%s', tag:'%s'" % (line, tag)) try: return line.split('<%s>' % tag)[1].rsplit('</%s>' % tag, 1)[0] except IndexError: print("tag_content out of index:", line.split('<%s>' % tag)) print("from line \n\n%s" % line) import sys sys.quit()
def handle_events(self): for event in pygame.event.get(): if event.type == QUIT: self.running = False elif event.type == KEYUP: if event.key == K_ESCAPE: self.running = False sys.quit() elif event.type == MOUSEBUTTONUP: for btn in self.buttons: if self.buttons[btn].mouse_over_button(event.pos): self.buttons[btn].on_click()
def move(): home = getHome() code = subprocess.call(["mv", "*", home]) subprocess.call(["chmod", "a+x", "jsh"]) if code != 0: subprocess.check_output(["mv", "*", home], stderr=sys.stdout) else: print "Please enter your password so this can install a link to /usr/bin/jsh" code = subprocess.call(["sudo", "ln", "-s", "jsh", "/usr/bin"]) if code == 0: print "Done!" sys.quit(0) else: print "The sudo command failed."
def run(self): self.logger.info("Interactive cli interface to JamesII (%s:%s) online." % ( self.plugin.core.brokerconfig['host'], self.plugin.core.brokerconfig['port'])) while (not self.terminated): self.plugin.worker_lock.acquire() if self.plugin.worker_exit: self.plugin.worker_lock.release() self.terminated = True sys.quit() break self.plugin.worker_lock.release() # check for keyboard interrupt try: line = raw_input() except KeyboardInterrupt: # http://bytes.com/topic/python/answers/43936-canceling-interrupting-raw_input self.plugin.core.add_timeout(0, self.plugin.core.terminate) self.terminated = True break except EOFError: self.plugin.core.add_timeout(0, self.plugin.core.terminate) self.terminated = True break line = line.strip() if len(line.rstrip()) > 0: args = line.split() if not self.plugin.commands.process_args(args): if args[0] in self.plugin.core.config['core']['command_aliases']: self.plugin.send_command(args) elif str(self.plugin.core.data_commands.get_best_match(args)) != 'data': self.plugin.send_command(args) else: best_match = self.plugin.core.ghost_commands.get_best_match(args) if best_match == self.plugin.core.ghost_commands: self.plugin.commands.process_args(['help'] + args) else: if len(best_match.subcommands) > 0: self.plugin.commands.process_args(['help'] + args) else: self.plugin.send_command(args) else: print("Enter 'help' for a list of available commands.")
def runTranslate(queryText): requestURL = "https://www.googleapis.com/language/translate/v2?" queryParams = { 'key': '{{API_KEY}}', 'source': 'ru', 'target': 'en', 'q': queryText} r = requests.get(requestURL, params = queryParams) if r.status_code == 200: queryResponse = r.text else: sys.quit() translatedText = jsonParse(queryResponse) return translatedText
def actual_breakage(P,s,gamma_dot,z,x): if random.random() < P.k_b*gamma_dot[z,x]*P.dt: if P.breakage_mode == 'normal': s[z,x,0] *= random.random() # 'normal' elif P.breakage_mode == 'limited': s[z,x,0] *= 0.0001/s[z,x,0] + (1.-0.0001/s[z,x,0])*(random.random()**1.) # minimum size limited elif P.breakage_mode == 'cascade':e0 s[z,x,0] *= 0.5 + 0.5*random.random() # cascade elif P.breakage_mode == 'lognormal': s[z,x,0] *= minimum(1.,random.lognormal(-0.75,0.2)) elif P.breakage_mode == 'constant': s[z,x,0] *= 0.5 else: sys.quit('No breakage mode.') s[z,x,1] += 1
def set_settings(self, file_name, settings): """gets the file to reconfigure and the settings to change) settings is a list of lists [[setting_name, setting_value],...] To remove a setting pass it as [setting_name, None] see self.config_graber() for details on available options in config files. I don't want to maintain the list in two places.""" #we are checking if we are updating or creating a file. full_file_path = self.get_full_path_to_file(file_name) if os.path.isfile(full_file_path): self.backup_file(file_name) #here we are updating a file. settings_file = open(full_file_path, 'r') file_data = settings_file.readlines() settings_file.close() settings_file = open(full_file_path, 'w') for line in file_data: for setting in settings: if setting[0] in line.split('=')[0]: line = '%s=%s\n' % (setting[0], setting[1]) settings.remove(setting) if not setting[1] == None: settings_file.write(line) for setting in settings: if not setting[1] == None: line = '\n%s=%s' % (setting[0], setting[1]) settings_file.write(line) settings_file.close() else: #here we are creating a new file. settings_file = open(full_file_path, 'w') no_time_set = True#as we are creating a new file here we must make sure we have a time set. no_feed_set = True#as we are creating a new file here we must raise an error if no url feed was given. for setting in settings: line = '%s=%s\n' % (setting[0], setting[1]) if 'last_update' in setting[0]: no_time_set = False elif 'url' in setting[0]: no_feed_set = False settings_file.write(line) if no_time_set and not file_name == 'rssgraber.conf': settings_file.write('last_update=%s\n' % time.asctime(time.gmtime())) if no_feed_set and not file_name == 'rssgraber.conf': print('You are doing it wrong, to create a new feed you also need to give me a URL, but you forgot to give me one! so I will just go kill my self now and take the newly created file with me. you tried to create the following file:%s' % file_name) settings_file.close() os.remove(settings_file) sys.quit() settings_file.close()
def parseInput(inputIntervals): """ This function take the input inserted by the user and return a list of intervals """ validatedIntervals=[] intervals=inputIntervals.replace('),', ')*').replace('],',']*').split('*') if inputIntervals.strip('0123456789(,)[]- ') or inputIntervals=="": print "wrong format for interval string" print "The input string should be like this:\n [-10,-7], (-4,1], [3,6), (8,12), [15,23]" sys.exit() else: for intervalInList in intervals: try: intervalInstance = interval(intervalInList.strip()) except NotValidBoundError, e: sys.quit() validatedIntervals.append(intervalInstance)
def start(self): DISPLAYSURF.fill(self.background) START_SURF, START_RECT = makeText('New Game', WHITE, GREEN, WINDOWWIDTH*0.3, WINDOWHEIGHT*0.7) EXIT_SURF, EXIT_RECT = makeText('Exit', WHITE, GREEN, WINDOWWIDTH*0.6, WINDOWHEIGHT*0.7) DISPLAYSURF.blit(START_SURF, START_RECT) DISPLAYSURF.blit(EXIT_SURF, EXIT_RECT) pygame.display.update() FPSCLOCK.tick(FPS) for event in pygame.event.get(): # event handling loop if event.type == MOUSEBUTTONUP: if START_RECT.collidepoint(event.pos): self.room = 'world' self.playable = True if EXIT_RECT.collidepoint(event.pos): pygame.exit() sys.quit()
def resolve_conflict(self, conflict): fixes = [] if len(conflict) > 0: main_uav = self.uav_record["uav{}".format(conflict[0])] temp_region = copy.copy(main_uav.region_rect) main_uav.update_region(main_uav.dpos) main_uav.shrink_regions() second_uav = self.uav_record["uav{}".format(conflict[2])] fixes.append(second_uav.shrink_regions) fixes.append(second_uav.send_away) fixes.append(second_uav.shrink_regions) i = 0 while(_collide(temp_region, second_uav.region_rect)): if i == 90: sys.quit() fixes[0]() fixes[1]() fixes[2]() main_uav.region_rect = temp_region
def handleEvents(self, events, my_turn, chessgame): LEFT = 1 #REFACTOR: move mousecontrols somewhere else? At least move LEFT etc definition somewhere else.. MIDDLE = 2 RIGHT = 3 for event in events: if event.type == QUIT: chessgame.running = False elif event.type == KEYDOWN: chessgame.keyDown(event.key) elif event.type == KEYUP: if event.key == K_ESCAPE: chessgame.running = False sys.quit() chessgame.keyUp(event.key) elif event.type == MOUSEBUTTONDOWN: if self.team_color == "black": # select a piece for piece in chessgame.black_pieces: if piece.mouse_on_piece(event.pos): self.selected_piece = piece piece.update_possible_moves(chessgame.game_board.board) elif self.team_color == "white": for piece in chessgame.white_pieces: if piece.mouse_on_piece(event.pos): self.selected_piece = piece piece.update_possible_moves(chessgame.game_board.board) elif event.type == MOUSEBUTTONUP: if my_turn: if event.button == RIGHT: self.latest_move = self.move(event.pos) elif event.type == MOUSEMOTION: for tiles in chessgame.game_board.board: for tile in tiles: if tile.mouse_on_tile(event.pos): chessgame.board_pos_mouseover_label = render_text(str(tile.board_x+1) + " / " + str(8 - tile.board_y), (100, 100, 200)) break
def runGame(): startx = 3 starty = 3 coords = [{'x':startx,'y':starty}] dirc = RIGHT while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.quit() if event.type == KEYDOWN: if event.key == K_LEFT: dirc = LEFT if event.type == K_RIGHT: dirc = RIGHT if event.type == K_UP: dirc = UP if event.type == K_DOWN: dirc = DOWN if dirc == UP: newCell = {'x':coords[0] ['x'],'y':coords[0]['y']-1} elif dirc == DOWN: newCell = {'x':coords[0] ['x'],'y':coords[0]['y']+1} elif dirc == LEFT: newCell = {'x':coords[0] ['x']-1,'y':coords[0]['y']} elif dirc == RIGHT: newCell = {'x':coords[0] ['x']+1,'y':coords[0]['y']} del coords[-1] coords.insert(0, newCell) setDisplay.fill(BKG) drawCell(coords) pygame.display.update() fpsTime.tick(fps)
def login(driver, username, password): driver.get("https://www.shipito.com/en/account/login") WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME,"login-footer"))) try: print(' binding form elements') name = driver.find_element_by_name('customer.email') pwd = driver.find_element_by_name('customer.password') button = driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/form/input[7]") print(' filling the form') name.send_keys(username) pwd.send_keys(password) print(' submitting login data') button.click() try: WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME, "footer"))) print (' login completed!') except: pass except TimeoutException: print(" form filling failed! Aborting...") import sys sys.quit(0)
def __init__(self, sequence_generator, output_dir=None, verbose=False): self.generator = sequence_generator assert output_dir is not None # required self.output_dir = output_dir if os.path.exists(output_dir + '/hdf5_chunk_list.txt'): print('Output directory already exists: ' + output_dir) while True: sys.stdout.write('Do you want to overwrite it? [Y/n] ') choice = raw_input().lower() try: if distutils.util.strtobool(choice): break else: print "Exiting" sys.quit(0) except ValueError: pass if not os.path.exists(output_dir): os.makedirs(output_dir) self.verbose = verbose self.filenames = [] self.batch_index = 0
def exit(): '''Quit application.''' print '\nYou have chosen to quit this application.' print 'Goodbye ...' quit()
def stop(self): self.gps_ser.close() self._stop.set() sys.quit()
# 10: The mask length in BITS for doing the inventory # numMaskBits = maskStack.pop() # Mask length in bits read_transponder_details.extend([0x11, 0x07, 0x01, numMaskBits]) # # At this point, we should check to see that the mask is not 64 bits # in length. Such a condition can only occur if there are two identical # tags in the field, or some other very strange fault. # if numMaskBits == 64: print ("Identical (cloned) tags or operational fault!") tiser.close() sys.quit() # bail out # Continue numMaskBytes = numMaskBits / 8 # compute number of mask bytes to pop if (numMaskBits % 8) != 0: # adjust if a MS nibble exists numMaskBytes += 1 # # Next form the mask. It goes into the command LSBs first, # but the MSBs are popped off the stack first. As we know # how many bytes there should be, we just adjust how they # are put into the command to account for this. Fortunately # python's pop method makes this very easy by using a negative # index. #
def terminate(): pygame.quit() sys.quit()
# TODO: is += possible here? date = date + datetime.timedelta(seconds = choice(timeSpan) * (sin((date.hour) / 24 * pi) + 1.5)) # write log closing message log.writeLogClosing(date) # close log file log.lfs[0].close() def profileMain(): cProfile.run('ircsimul.main()') if __name__ == "__main__": if sys.version_info[0] < 3: print("This script needs to be run on Python 3! (It's being tested on 3.3 currently)") sys.quit(1) parser = argparse.ArgumentParser() parser.add_argument("-l", "--lines", help="number of lines to be generated, -1 --> infinite lines", type=int) parser.add_argument("-o", "--output", help="sets output file (if not given, logs to ircsimul.log)", type=str) parser.add_argument("--stdout", help="toggles output to stdout", action="store_true") parser.add_argument("--realtime", help="toggles output to stdout", action="store_true") parser.add_argument("--loginitpop", help="log initial population of channel, use Ctrl+C to quit", action="store_true") args = parser.parse_args() # TODO: make this less messy if args.lines: lineMax = args.lines else: lineMax = 50000 if args.output:
def actionManagerKey(currentMap, playerPosX, playerPosY, inventory, skills, screen, activeQuests, modulePositions, textToDisplay, prayerPoints, key): textToDisplay = [] playerMoveDirection = ('x','y') keyPressed = chr(key) if keyPressed == 'Q': sys.quit() if key == curses.KEY_LEFT: playerMoveDirection = (-1,0) elif key == curses.KEY_RIGHT: playerMoveDirection = (1,0) elif key == curses.KEY_UP: playerMoveDirection = (0,-1) elif key == curses.KEY_DOWN: playerMoveDirection = (0,1) elif keyPressed == 'w': playerMoveDirection = (0,0) elif keyPressed in '123456789': modulePositions = moduleReposition(key, modulePositions, screen) elif currentMap[playerPosX][playerPosY] == "grass": if itemPresentInInventory("seeds", inventory): if tileNextTo(currentMap, playerPosX, playerPosY, 'water', 3): textToDisplay.append(("Press 'p' to plant seed", 16)) if keyPressed == 'p': currentMap[playerPosX][playerPosY] = "seed" skills = skillManagerExperience(skills, 'farming', 23) if itemPresentInInventory("shovel", inventory): textToDisplay.append(("Press 'd' to dig a hole", 16)) if keyPressed == 'd': if random.randint(1, 5) == 1: inventory.append("bones") currentMap[playerPosX][playerPosY] = "hole" inventory.append("dirt") skills = skillManagerExperience(skills, 'strength', 2) skills = skillManagerExperience(skills, 'terraforming', 10) if 'terraforming' in skills: if skillManagerLevel(skills['terraforming']) > 4: textToDisplay.append(("Press 'b' to dig a big hole", 16)) if keyPressed == 'b': currentMap = changeTile(currentMap, playerPosX, playerPosY, "hole", 2) inventory.append("dirt") skills = skillManagerExperience(skills, 'strength', 2) skills = skillManagerExperience(skills, 'terraforming', 40) if itemPresentInInventory("logs", inventory): textToDisplay.append(("Press 'f' to start a fire" , 3)) if keyPressed == 'f': currentMap[playerPosX][playerPosY] = "fire" inventory = removeItemFromInventory("logs", inventory, 1) skills = skillManagerExperience(skills, 'firemaking', 10) if itemPresentInInventory("bones", inventory): textToDisplay.append(("Press 'b' to bury bones", 3)) if keyPressed == 'b': skills = skillManagerExperience(skills, 'praying', 8) prayerPoints += 10 elif currentMap[playerPosX][playerPosY] == "seed": textToDisplay.append(("Press 't' to trample seed", 3)) if keyPressed == 't': currentMap[playerPosX][playerPosY] = "grass" if itemPresentInInventory("corrupt dust", inventory): textToDisplay.append(("Press 'p' to add corrupt dust to tree", 3)) if keyPressed == 'p': currentMap[playerPosX][playerPosY] = "evilSeed" elif currentMap[playerPosX][playerPosY] == "tree": if itemPresentInInventory("axe", inventory): textToDisplay.append(("Press 'c' to chop down tree", 3)) if keyPressed == 'c': if random.randint(1, 2) == 1: inventory.append("seeds") currentMap[playerPosX][playerPosY] = "grass" inventory.append("logs") skills = skillManagerExperience(skills, 'woodcutting', 10) elif currentMap[playerPosX][playerPosY] == "town": textToDisplay.append(("Press 't' to talk", 16)) textToDisplay.append(("Press 'q' to start a quest", 15)) if keyPressed == 'q': currentMap, activeQuests = questManagerNew(currentMap, activeQuests, playerPosX, playerPosY) skillManagerExperience(skills, 'questing', -25) for quest in activeQuests: if quest[2] == "return" and quest[0] == str(playerPosX) + "," + str(playerPosY): textToDisplay.append(("Press 'c' to complete quest", 15)) if keyPressed == 'c': for i in range(0,int(quest[4])): inventory.append(quest[3]) activeQuests.remove(quest) skillManagerExperience(skills, 'questing', 50) elif currentMap[playerPosX][playerPosY] == "shop": textToDisplay.append(("Press 's' to shop", 3)) textToDisplay.append(("Press 'r' to rob shop", 3)) textToDisplay.append(("Press 'i' to invest in shop", 3)) if keyPressed == 's': shopManagerManager(inventory, screen) elif currentMap[playerPosX][playerPosY] == "monster": textToDisplay.append(("Press 'a' to attack monster", 3)) textToDisplay.append(("Press 't' to train monster", 3)) textToDisplay.append(("Press 'f' to flee monster", 3)) textToDisplay.append(("Press 'd' to defend against monster", 3)) textToDisplay.append(("Press 'h' to hide from monster", 3)) if keyPressed == 'a': inventory.append("gold") currentMap[playerPosX][playerPosY] = "grass" skills = skillManagerExperience(skills, 'attack', 10) elif currentMap[playerPosX][playerPosY] == "quest": for quest in activeQuests: if quest[1] == str(playerPosX) + "," + str(playerPosY): if keyPressed == 'q': updatedQuest = (quest[0],quest[1],"return",quest[3],quest[4]) activeQuests.remove(quest) activeQuests.append(updatedQuest) currentMap[playerPosX][playerPosY] = "grass" elif currentMap[playerPosX][playerPosY] == "water": if itemPresentInInventory("fishingRod", inventory): textToDisplay.append(("Press 'f' to fish water", 15)) if keyPressed == 'f': inventory.append("fish") inventory = removeItemFromInventory("fishingRod", inventory, 1) skills = skillManagerExperience(skills, 'fishing', 8) elif itemPresentInInventory("bucket", inventory): textToDisplay.append(("Press 'p' to pickup water", 15)) if keyPressed == 'p': inventory.append("water bucket") inventory = removeItemFromInventory("bucket", inventory, 1) currentMap[playerPosX][playerPosY] = "hole" elif currentMap[playerPosX][playerPosY] == "hole": if itemPresentInInventory("water bucket", inventory): textToDisplay.append(("Press 'p' to put down water", 15)) if keyPressed == 'p': inventory.append("bucket") inventory = removeItemFromInventory("water bucket", inventory, 1) currentMap[playerPosX][playerPosY] = "water" elif currentMap[playerPosX][playerPosY] == "alter": if prayerPoints > 15: textToDisplay.append(("Press 'w' to pray to the god of staff", 3)) textToDisplay.append(("Press 's' to pray to the god of sword", 5)) textToDisplay.append(("Press 'x' to pray to the god of arrow", 10)) if keyPressed == 'w': prayerPoints -= 15 inventory.append("staff") elif keyPressed == 's': prayerPoints -= 15 inventory.append("sword") elif keyPressed == 'x': prayerPoints -= 15 inventory.append("bow") for i in range(10): inventory.append("arrows") return currentMap, inventory, skills, activeQuests, modulePositions, textToDisplay, prayerPoints, playerMoveDirection
def checkForError(self, text): temp = text.decode('utf-8') if "bcmCNTR" in temp: self.logOutput(temp) self.logOutput("**********ERROR FOUND! Exiting program...**********") sys.quit()
wakingbackword = False if event.key == ord("a"): wakingleft = False if event.key == ord("d"): wakingright = False #play backgrund musick if backgrundmusicplaying = True if backgrundmusicplaying == False and backgrundmusicon == True: pygame.mixer.music.play(-1. 0.0) backgrundmusicplaying = True elif backgrundmusicplaying == True and backgrundmusicon == True: pygame.mixer.music.stop() backgrundmusicplaying = False #change position variabels if wakingforword == True: playerx = playerx + 1 if wakingbackword == True: playerx = playerx - 1 if wakingleft == True: playery = playery - 1 if wakingright == True: platery = playery + 1 #renders the imge thread.start_new_thread(render(), ) mainClock.tick(40) #main loop ended quiting pygame.quit() sys.quit()
def set_dpos(self, dpos, safe = True): if safe and self.in_region(dpos): self.dpos = dpos self.pos = dpos2pos(self.dpos) else: sys.quit()