def start_pipeline(): """ Main function to start the pipeline. :return: """ user_input = UserInput() poly_fit = 1 # default as 1 while (True): if user_input.obs_mode == 1 and user_input.instrument == 1: spectrometer_task = SpectrometerDataProcessTask( obj_name=user_input.obj_name, freq=user_input.freq, bsl_flag=user_input.bsl_flag, smooth_box=user_input.smooth_box, polyfit_deg=poly_fit) spectrometer_task.level1_process() spectrometer_task.plot_result() if user_input.obs_mode == 1 and user_input.instrument == 2: crane_task = CraneDataProcessTask(obj_name=user_input.obj_name, bsl_flag=user_input.bsl_flag, smooth_box=user_input.smooth_box, polyfit_deg=poly_fit) crane_task.subtract_bandpass() crane_task.level1_process() crane_task.plot_result() poly_fit = user_input.prompt_poly_fit() if poly_fit == 0: # means poly fit degree accepted break print('Pipeline finished successfully!')
def commit_viewer(): # Get url, branch and number of commits from request r = flask.request.get_json() url = str(r['url']) branch = str(r['branch']) if 'branch' in r else 'master' num_commits = int(r['num_commits']) if 'num_commits' in r else 2 # Validate url uinput = UserInput() if not uinput.validate_url(url): return flask.jsonify({'failure': 'Invalid url'}) # Retrieve list of commits github_api = GithubApiCommitRetriever(url) if github_api.request_successful(): commit_list = github_api.get_commits() error = '' else: logging.warning('Retrieve commit list using GitHub API failed') gitcli = GitCLICommitRetriever(url, branch) commit_list, error = gitcli.get_commits() # Return error message if retriever fails if error: return flask.jsonify({'failure': error}) # Respond with restricted number of commits elif len(commit_list) > num_commits: commit_list_short = commit_list[:num_commits] return flask.jsonify({'commit_list': commit_list_short, 'total_num_commits': len(commit_list)}) # Respond with unrestricted number of commits else: return flask.jsonify({'commit_list': commit_list})
def promptAndGetContainer(self): while True: capacity = UserInput().getFloatInput( "Container's actual capacity (cuft): ", 0, sys.float_info.max) ratedPressure = UserInput().getFloatInput( "Container's rated pressure (psi): ", 0, sys.float_info.max) currentPressure = UserInput().getFloatInput( "Container's current pressure (psi): ", 0, sys.float_info.max) fo2 = UserInput().getFloatInput( "Percentage of oxygen in the container (21% = 0.21): ", 0, 1) print() # Convert capacity in cuft to cuin cubicFtToCubicInConversionRatio = 1728 capacity = capacity * cubicFtToCubicInConversionRatio container = Container(capacity, ratedPressure, currentPressure, fo2) print(container) if input( "Is the above information accurate and would you like to use this container? [y/N]: " ) == 'y': print("Gas will be used.\n") return container else: print("Gas will be used.\n")
def __call__(self, string_input: str) -> None: """Called and handles the raw string input from command line.""" try: user_input = UserInput(string_input) # We need to split the raw string up into elements. Group numbers >9 together and clean up white space. parsed_input = user_input.get_parsed_input() # Process the input now it is nicely split up. self._process_parsed_string(parsed_input) except SRPNException as e: # Something unexpected has happened if the program reaches here. raise e
def gather_startup_data(): global api, camera_esn, namespace print(banner) username, password = UserInput.get_login_data() print("Authenticating & Authorizing the User...") api = API(username, password) camera_esn, namespace = UserInput.get_camera_data()
def __init__(self): """ Creates application object. """ self.is_running = True self.user_input = UserInput() self.view = View() self.csv_file_path = ""
def classify(self, sentence): inp = UserInput(sentence, lexicon=self.intents.lexicon) predictions = self.model.model.predict( inp.bag.reshape(1, len(self.intents.lexicon)))[0] # filter out predictions below a threshold predictions = [[i, p] for i, p in enumerate(predictions) if p > self.ERROR_THRESHOLD] prediction = max(predictions) # return tuple of prediction and probability return self.intents.classes[prediction[0]], prediction[1]
def main(): """Entry point. Gets user input, runs GUI or task manager depending on the input""" user_input = UserInput() if user_input.gui_flag: g = Gui(user_input.get_file(), user_input.get_docid(), user_input.get_userid()) g.run() else: manager = TaskManager(user_input.get_file(), user_input.get_docid(), user_input.get_userid()) task = user_input.task manager.run(task)
def start(self): while True: try: line = raw_input("shop> ") line = line.strip() if line: if line[0] == 'q': return cmd = UserInput(line) self.createHandler(cmd.command).run(cmd) except Exception as e: print "ERROR: " + str(e)
def read_data(): list_file_path = values['_input_file_'] output_file_path = values['_output_file_'] directory = values['_folder_'] distance_multiplier = values['_distance_'] column = values['_column_'] row_range = (values['_firstrow_'], values['_lastrow_']) user_input = UserInput(list_file_path, output_file_path, directory, distance_multiplier, column, row_range) return user_input
def main(): """Main method for airplane""" country_c, currency_c, airport_c, aircraft_c = DataCleanse.initialize() DataCleanse.start_clean() #print(airport_c.airport_cc_df.head(n=3)) # Initialize the Airport class: print() airports_dict = AirportAtlas.load_data(airport_c.airport_file_merged) KJFK = airports_dict['JFK'] print('Number of airports initialized:', len(airports_dict)) # KJFK.tostring() aircraft_dict = LoadAircraft.load_data(aircraft_c.aircraft_file_clean) print() print('Number of aircraft initialized:', len(aircraft_dict)) # aircraft_dict['BAE146'].tostring print() print() new_input = UserInput(airports_dict) new_input.desc_program() new_input.itinerary_size() new_input.itinerary_input() unordered_itinerary = new_input.itinerary_dict # Call function to add coordinates to the unordered_itinerary dictionary unordered_itinerary = obtain_coordinates(unordered_itinerary, airports_dict) # Create an instance of the PathCalculation class path_calc = PathCalculation(unordered_itinerary) shortest_path, price = path_calc.create_permutations() print("Shortest path (cheapest flight):", shortest_path, "EUR", price)
class BmiEngine: def __init__(self): pass input = UserInput() category = BmiCategroy() def start_bmi(self): gender = self.getGender() height, height_unit = self.getHeight() weight = self.getWeight() bmi_ = self.bmi.calculate_bmi(height, height_unit, weight) print("Your BMI: %s" % bmi_) bfp_category = self.bmi.body_fat_category(_bfp=bfp, _gender=gender) print("Boby Fat Percentage Category: %s" % bfp_category)
class TestUserInput(unittest.TestCase): def setUp(self): self.user_input = UserInput() self.user_input.errors = [] def test___init__(self): parameters = (root + st.gui_default_input_path, root + st.gui_default_output_path, root + st.gui_default_audio_folder, 3.0, "c", ('2', '8')) self.user_input = UserInput(*parameters) self.assertFalse(self.user_input.errors) def test_validate_list_file_not_a_file(self): result = self.user_input.validate_list_file("Test_string") self.assertEqual(result, ("Test_string", None)) self.assertIn("Input file not found.", self.user_input.errors) def test_validate_list_file_good_file(self): test_file = root + st.gui_default_input_path fpath, ftype = self.user_input.validate_list_file(test_file) print(fpath, ftype) self.assertEqual(fpath, test_file) self.assertEqual(ftype, 'spreadsheet') self.assertFalse(self.user_input.errors) def test_get_list_file_type_wrong_type(self): self.user_input.get_list_file_type("ciapki.csv") self.assertEqual("Unknown input file type.", self.user_input.errors[-1]) def test_get_list_file_type_excel(self): test_file = root + st.gui_default_input_path result = self.user_input.get_list_file_type(test_file) self.assertEqual(result, "spreadsheet") def test_get_list_file_type_txt(self): test_file = root + "test/resources/input_files/file_list.txt" result = self.user_input.get_list_file_type(test_file) self.assertEqual(result, "text") def test_validate_output_file_not_a_path(self): self.user_input = UserInput() self.user_input.validate_output_file("None") self.assertEqual("Wrong output file path.", self.user_input.errors[-1]) def test_validate_output_file_type(self): result = self.user_input.validate_output_file_type("test.rpp") self.assertFalse(self.user_input.errors) self.assertEqual(result, "Reaper") def test_validate_directory_wrong_directory(self): result = self.user_input.validate_directory("Test directory") self.assertIn("Invalid audio directory path.", self.user_input.errors) self.assertEqual(result, None) def test_validate_directory_good_directory(self): result = self.user_input.validate_directory("/usr/bin") self.assertEqual("/usr/bin", result) self.assertFalse(self.user_input.errors) def test_validate_distance_multiplier(self): pass def test_validate_excel_range(self): pass
def test_get_coffee_type_3(self): userInput = UserInput() with patch("builtins.input", return_value=3): assert userInput.get_coffee_type() == "latte macchiato"
def test___init__(self): parameters = (root + st.gui_default_input_path, root + st.gui_default_output_path, root + st.gui_default_audio_folder, 3.0, "c", ('2', '8')) self.user_input = UserInput(*parameters) self.assertFalse(self.user_input.errors)
def test_validate_output_file_not_a_path(self): self.user_input = UserInput() self.user_input.validate_output_file("None") self.assertEqual("Wrong output file path.", self.user_input.errors[-1])
def test_get_coffe_type_1(self): userInput = UserInput() with patch("builtins.input", return_value=1): assert userInput.get_coffee_type() == "espresso"
def setUp(self): self.user_input = UserInput() self.user_input.errors = []
# -*- coding: utf-8 -*- # solve path problem import sys import os # get source file directory so that the program can be executable from anywhere dir_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '.')) sys.path.append(dir_root) # Begin importing packages from user_input import UserInput from get_ab import GetAB from dialog import Dialog from plot import PlotFig # aliases inp = UserInput() init = GetAB() dia = Dialog() pf = PlotFig() # constants R = 8.314 # get input value for T_c and p_c T_c, p_c = inp.init_input_tp() # calculate a and b a, b, V_M = init.get_ab_from_tp(T_c, p_c, R) print('a =', a, 'b =', b, 'V_M =', V_M, '\n') dia.cont_or_not()
import logging from user_input import UserInput from retriever import CommitRetriever if __name__ == '__main__': logging.info('Start Commit Viewer') # Request and validate user input logging.info('Start User Input Request') uinput = UserInput() url, branch = uinput.get() # Retrieve list of commits logging.info('Start Commit Retriever') retriever = CommitRetriever(url, branch) print(retriever.get_commits())
#!/usr/bin/env python import sys from user_input import UserInput from aws_actions import AwsActions if __name__ == '__main__': # parse the args ui = UserInput(sys.argv[1:]) # collect the parsed args into a dict data = ui.get_args_as_dict() # throw that dict at the ElbTool to do stuff with the AWS api action = AwsActions(**data) action.run()
class Game: def __init__(self): # initialize the pygame module pygame.init() logo_name = os.path.join('assets', "logo.png") logo = pygame.image.load(logo_name) pygame.display.set_icon(logo) pygame.display.set_caption("Escape") self.screen = pygame.display.set_mode(SCREEN_SIZE) self.black_surface = self.screen.copy() self.black_surface.fill(pygame.Color("black")) # default font used for the timer self.font = pygame.font.Font(None, 100) self.subtext_font = pygame.font.Font(None, 25) self.notification_font = pygame.font.Font(None, 25) # specifies the middle of the screen self.character = Character("avatar/MC-front.png", 0, 0) self.camera = Coords(CHARACTER_START[X], CHARACTER_START[Y]) # saves the camera for when enering the building self.camera_save = None self.user_input = UserInput() # sound self.ambient = pygame.mixer.Sound("assets/ambient.wav") self.ambient_channel = pygame.mixer.Channel(1) self.wind = pygame.mixer.Sound("assets/wind.wav") self.wind.play(-1) # a shit ton of time related stuff self.clock = pygame.time.Clock() self.countdown = Countdown() self.ticker = Ticker() self.fade_in_timer = Timer() self.display_timer = Timer() self.notification_timer = Timer() self.fade_out_timer = Timer() # variables for when you're in some building self.current_building = None self.buildings = create_buildings() self.well_area = ScaledRect(208, 354, 60, 51) # define a variable to control the main loop # where it is really only set to false if the player exits or the X button is pressed self.running = True self.state = None self.fade_into_main_menu() self.wins = create_wins() self.subtext_value = "" self.notification_value = "" # self.ended = False # self.show_ending = False self.end_image = None self.begin_image = load_image("beginlol.png", use_scale=False, return_rect=False) self.begin_image = pygame.transform.scale(self.begin_image, SCREEN_SIZE) self.default_background = load_image('background.png', return_rect=False) self.building_wall_mask = load_image('background_outline.png', convert_alpha=True, return_rect=False) # background can change to default background or house background self.background = self.default_background # creates the start menus self.pause_menu = PauseMenu(self.screen) self.main_menu = MainMenu(self.screen) self.temp = [] @property def in_building(self): return self.current_building is not None def play(self): while self.running: if DEBUG: print(STATE_DICT[self.state]) self.handle_event() self.update() self.draw() self.clock.tick(60) if DEBUG: print("debug: temp =", self.temp) print("collected {}".format(self.character.items)) def handle_event(self): self.user_input.update() self.ticker.update() # can only pause when you're in the f*****g game matey lmao if self.state == GAME_PLAY and self.user_input.clicked_pause( self.ticker.tick): self.pause() elif self.state == GAME_PAUSE: if self.user_input.clicked_mouse(): pos = pygame.mouse.get_pos() if self.pause_menu.resume_button.border.collidepoint(pos): self.unpause() if self.pause_menu.exit_button.border.collidepoint(pos): self.running = False if self.user_input.clicked_pause(self.ticker.tick): self.unpause() # checks for main menu clicks if self.state == MAIN_MENU: if self.user_input.clicked_mouse(): pos = pygame.mouse.get_pos() if self.main_menu.play_button.border.collidepoint(pos): self.fade_outof_main_menu() if self.main_menu.exit_button.border.collidepoint(pos): self.running = False return if self.user_input.clicked_interact(self.ticker.tick): self.fade_outof_main_menu() # only do something if the event is of type QUIT if self.user_input.clicked_quit(): # change the value to False, to exit the main loop self.running = False return # if the player presses interact and it's during one of the display screens if self.user_input.clicked_interact(self.ticker.tick): if BEGIN_FADE_IN <= self.state <= BEGIN_FADE_OUT: self.start_game_fade_in() if END_FADE_IN <= self.state <= END_FADE_OUT: self.fade_into_main_menu() if self.state in STATES_DISPLAY: if self.display_timer.ended: if self.state == BEGIN_DISPLAY: # begin display -> fade out begin display self.state = BEGIN_FADE_OUT self.fade_out_timer.start(BEGIN_FADE_OUT_TIME) elif self.state == END_DISPLAY: # end display -> fade out end display self.state = END_FADE_OUT self.fade_out_timer.start(END_FADE_OUT_TIME) if self.state in STATES_FADE_IN: if self.fade_in_timer.ended: if self.state == MAIN_MENU_FADE_IN: # menu fade in to main menu self.to_main_menu() elif self.state == BEGIN_FADE_IN: # end instruction fade in self.state = BEGIN_DISPLAY self.display_timer.start(BEGIN_DISPLAY_TIME) elif self.state == GAME_FADE_IN: # starts the game here (end fade in) self.countdown.start() self.ambient_channel.play(self.ambient) self.state = GAME_PLAY elif self.state == END_FADE_IN: # end the ending fade in self.state = END_DISPLAY self.display_timer.start(END_DISPLAY_TIME) if self.state in STATES_FADE_OUT: if self.fade_out_timer.ended: if self.state == MAIN_MENU_FADE_OUT: # menu fade out -> begin fade in self.state = BEGIN_FADE_IN self.fade_in_timer.start(BEGIN_FADE_IN_TIME) elif self.state == BEGIN_FADE_OUT: # begin fade out -> game fade in self.start_game_fade_in() elif self.state == GAME_FADE_OUT: # already ended the game, shows display self.state = END_FADE_IN self.fade_in_timer.start(END_FADE_IN_TIME) elif self.state == END_FADE_OUT: self.fade_into_main_menu() # countdown ends: game ends if self.state == GAME_PLAY and self.countdown.ended: self.end() def update(self): if self.state == GAME_PLAY: self.countdown.update() velocity = self.user_input.get_velocity() self.camera.store_previous() self.camera += velocity if DEBUG: coords = self.character.get_pixel_at_feet(self.camera) print(coords) if self.user_input.clicked_debug(self.ticker.tick): self.temp.append(coords) self.character.update(velocity, self.ticker.tick) if not self.in_building: # detects collision with walls and buildings pixel = (self.building_wall_mask.get_at( tuple(self.character.get_pixel_at_feet(self.camera)))) if pixel[3] > ALPHA_THRESHOLD: # TODO make less sticky if possible if COLLIDES: # checks for each x and y if they can work current_x = self.camera.x current_y = self.camera.y self.camera.x = self.camera.previous_x self.camera.y = self.camera.previous_y coords = Coords(current_x, current_y) coords.x = self.camera.previous_x # gets the new y coordinate and keeps x constant pixel = (self.building_wall_mask.get_at( tuple(self.character.get_pixel_at_feet(coords)))) if not (pixel[3] > ALPHA_THRESHOLD ): # if the new y coordinate is free self.camera.y = coords.y coords = Coords(current_x, current_y) coords.y = self.camera.previous_y pixel = (self.building_wall_mask.get_at( tuple(self.character.get_pixel_at_feet(coords)))) if not pixel[3] > ALPHA_THRESHOLD: self.camera.x = coords.x # checks for collecting water at the well if (self.well_area.collide(self.camera, self.character.proper_size) and self.character.items["water_skin"] >= 1): self.subtext_value = "Press {} to fill your water skin".format( INTERACT_KEY) if self.user_input.clicked_interact(self.ticker.tick): self.character.items["water_skin"] -= 1 self.character.items["filled_water_skin"] += 1 self.notification_value = "Filled your water skin" self.notification_timer.start(NOTIFICATION_TIME) # checks for the building shit for building in self.buildings: if building.enters(self.character, self.camera): self.subtext_value = "Press {} to enter ".format( INTERACT_KEY) + building.name if self.user_input.clicked_interact(self.ticker.tick): self.notification_value = "Entered " + building.name self.notification_timer.start(NOTIFICATION_TIME) self.current_building = building self.background = building.background self.camera_save = self.camera.copy() # resets the camera building_exit_coords = building.camera_exit_coords building_exit_coords.y -= self.character.rect.height // 2 self.camera = building_exit_coords # collides with any win for win in self.wins: if win.collide(self.camera, self.character.get_rect_at_feet()): # set player to escaped self.character.escaped = True # ambient fades out only here self.ambient_channel.fadeout(AMBIENT_FADE_OUT) self.end() else: # detects collision with the building walls by checking # if the player leaves the given rect coords = tuple(self.character.get_pixel_at_feet(self.camera)) if not self.current_building.walls.rect.collidepoint(coords): # TODO make less sticky if possible if COLLIDES: # checks for each x and y if they can work current_x = self.camera.x current_y = self.camera.y self.camera.x = self.camera.previous_x self.camera.y = self.camera.previous_y coords2 = Coords(current_x, current_y) coords2.x = self.camera.previous_x # gets the new y coordinate and keeps x constant if self.current_building.walls.rect.collidepoint( tuple(self.character.get_pixel_at_feet( coords2))): self.camera.y = coords2.y coords2 = Coords(current_x, current_y) coords2.y = self.camera.previous_y if self.current_building.walls.rect.collidepoint( tuple(self.character.get_pixel_at_feet( coords2))): self.camera.x = coords2.x # detects collision for furniture for furniture in self.current_building.furniture.values(): if furniture.rect.collidepoint(coords): # TODO make less sticky if possible if COLLIDES: # checks for each x and y if they can work current_x = self.camera.x current_y = self.camera.y self.camera.x = self.camera.previous_x self.camera.y = self.camera.previous_y coords2 = Coords(current_x, current_y) coords2.x = self.camera.previous_x # gets the new y coordinate and keeps x constant if not furniture.rect.collidepoint( tuple( self.character.get_pixel_at_feet( coords2))): self.camera.y = coords2.y coords2 = Coords(current_x, current_y) coords2.y = self.camera.previous_y if not furniture.rect.collidepoint( tuple( self.character.get_pixel_at_feet( coords2))): self.camera.x = coords2.x # checks for collectibles for collectible in self.current_building.collectibles: if collectible.collides(self.character, self.camera): self.subtext_value = "Collect " + collectible.display_name if self.user_input.clicked_interact(self.ticker.tick): collectible.pick_up() self.notification_value = "Collected " + collectible.display_name self.notification_timer.start(NOTIFICATION_TIME) self.character.items[collectible.type] += 1 #self.character.points += collectible.points #self.character.weight += collectible.weight # checks whether they have left the building if self.current_building.exit_area.collide( self.camera, self.character.get_rect_at_feet()): self.subtext_value = "Press {} to leave ".format( INTERACT_KEY) + self.current_building.name if self.user_input.clicked_interact(self.ticker.tick): self.notification_value = "Left " + self.current_building.name self.notification_timer.start(NOTIFICATION_TIME) self.camera = self.camera_save self.current_building = None self.background = self.default_background def draw(self): self.screen.fill((0, 0, 0)) # draws the background relative to the character and countdown if GAME_FADE_IN <= self.state <= GAME_FADE_OUT: self.screen.blit(self.background, (SCREEN_SIZE[X] // 2 - self.camera.x, SCREEN_SIZE[Y] // 2 - self.camera.y)) self.countdown.draw(self.screen, self.font) if not self.in_building: if DEBUG: for building in self.buildings: building.debug_draw_position(self.screen, self.camera) for win in self.wins: win.debug_draw(self.camera, self.screen) self.well_area.debug_draw(self.camera, self.screen, "pink") else: # in building if DEBUG: self.current_building.debug_draw_inner( self.screen, self.camera) # draws all collectibles within a building self.current_building.collectibles.draw( self.screen, self.camera) # draws character at the last lmao self.character.draw(self.screen) if DEBUG: self.character.draw_pixel(self.screen, self.camera) if self.state == GAME_PAUSE: self.pause_menu.draw(self.screen) # renders the display name on the bottom right of the screen if self.subtext_value: text_render = self.subtext_font.render(self.subtext_value, True, pygame.Color("orange")) # text_render = pygame.transform.scale(text_render, (text_render.get_width()*3, text_render.get_height()*3)) text_pos = text_render.get_rect() text_pos.bottomleft = self.screen.get_rect().bottomleft self.screen.blit(text_render, text_pos) self.subtext_value = "" if self.notification_value: if self.notification_timer.ended: self.notification_value = "" else: text_render = self.notification_font.render( self.notification_value, True, pygame.Color("orange")) # text_render = pygame.transform.scale(text_render, (text_render.get_width()*3, text_render.get_height()*3)) text_pos = text_render.get_rect() text_pos.bottomleft = self.screen.get_rect().bottomleft text_pos.y -= 25 self.screen.blit(text_render, text_pos) # displays the beginning image if BEGIN_FADE_IN <= self.state <= BEGIN_FADE_OUT: self.screen.blit(self.begin_image, (0, 0)) # displays the ending image if END_FADE_IN <= self.state <= END_FADE_OUT: self.screen.blit(self.end_image, (0, 0)) # displays the main menu if self.state in (MAIN_MENU_FADE_IN, MAIN_MENU, MAIN_MENU_FADE_OUT): self.main_menu.draw(self.screen) if self.state in STATES_FADE_IN or self.state in STATES_FADE_OUT: if self.state in STATES_FADE_IN: # goes from black to normal alpha_value = int(255 * (self.fade_in_timer.get())) else: # goes from normal to black alpha_value = int(255 - 255 * (self.fade_out_timer.get())) self.black_surface.set_alpha(alpha_value) self.screen.blit(self.black_surface, (0, 0)) pygame.display.flip() def start_game_fade_in(self): self.state = GAME_FADE_IN self.fade_in_timer.start(GAME_FADE_IN_TIME) def pause(self): #pygame.mixer.pause() self.ambient_channel.pause() self.countdown.pause() self.state = GAME_PAUSE def unpause(self): #pygame.mixer.unpause() self.ambient_channel.unpause() self.countdown.unpause() self.state = GAME_PLAY def fade_into_main_menu(self): # does the majority of resetting here if necessary # fades out if there's still sound for some reason self.countdown.start() self.countdown.pause() self.ambient_channel.fadeout(2) self.character.reset() for building in self.buildings: for collectible in building.collectibles: collectible.reset() self.camera = Coords(CHARACTER_START[X], CHARACTER_START[Y]) self.fade_in_timer.start(MAIN_MENU_FADE_IN_TIME) self.state = MAIN_MENU_FADE_IN def to_main_menu(self): self.state = MAIN_MENU def fade_outof_main_menu(self): self.state = MAIN_MENU_FADE_OUT self.fade_out_timer.start(MAIN_MENU_FADE_OUT_TIME) def end(self): if not self.countdown.ended: self.countdown.pause() self.state = GAME_FADE_OUT self.fade_out_timer.start(GAME_FADE_OUT_TIME) # gets the end image if not self.character.escaped: self.end_image = load_image("endings/stay_death.png", return_rect=False) elif sum(self.character.items.values()) <= 2: self.end_image = load_image("endings/missing_lots_death.png", return_rect=False) elif self.character.has_no_items("filled_water_skin"): self.end_image = load_image("endings/thirst_death.png", return_rect=False) elif self.character.has_no_items("ugly_green_scarf"): self.end_image = load_image("endings/cold_death.png", return_rect=False) elif self.character.has_no_items("bread", "cheese", "jerky"): self.end_image = load_image("endings/starvation_death.png", return_rect=False) elif self.character.has_no_items("bandages", "bow_arrow", "cheese"): self.end_image = load_image("endings/bandits_death.png", return_rect=False) elif self.character.has_no_items("pileogold"): self.end_image = load_image("endings/no_money_death.png", return_rect=False) else: self.end_image = load_image("endings/win_happy.png", return_rect=False) self.end_image = pygame.transform.scale(self.end_image, SCREEN_SIZE) if DEBUG: print("ended!")
def test_get_coffee_strength_4(self): userInput = UserInput() with patch("builtins.input", return_value="foo"): self.assertRaises(ValueError, userInput.get_coffee_strength())
def __init__(self): # initialize the pygame module pygame.init() logo_name = os.path.join('assets', "logo.png") logo = pygame.image.load(logo_name) pygame.display.set_icon(logo) pygame.display.set_caption("Escape") self.screen = pygame.display.set_mode(SCREEN_SIZE) self.black_surface = self.screen.copy() self.black_surface.fill(pygame.Color("black")) # default font used for the timer self.font = pygame.font.Font(None, 100) self.subtext_font = pygame.font.Font(None, 25) self.notification_font = pygame.font.Font(None, 25) # specifies the middle of the screen self.character = Character("avatar/MC-front.png", 0, 0) self.camera = Coords(CHARACTER_START[X], CHARACTER_START[Y]) # saves the camera for when enering the building self.camera_save = None self.user_input = UserInput() # sound self.ambient = pygame.mixer.Sound("assets/ambient.wav") self.ambient_channel = pygame.mixer.Channel(1) self.wind = pygame.mixer.Sound("assets/wind.wav") self.wind.play(-1) # a shit ton of time related stuff self.clock = pygame.time.Clock() self.countdown = Countdown() self.ticker = Ticker() self.fade_in_timer = Timer() self.display_timer = Timer() self.notification_timer = Timer() self.fade_out_timer = Timer() # variables for when you're in some building self.current_building = None self.buildings = create_buildings() self.well_area = ScaledRect(208, 354, 60, 51) # define a variable to control the main loop # where it is really only set to false if the player exits or the X button is pressed self.running = True self.state = None self.fade_into_main_menu() self.wins = create_wins() self.subtext_value = "" self.notification_value = "" # self.ended = False # self.show_ending = False self.end_image = None self.begin_image = load_image("beginlol.png", use_scale=False, return_rect=False) self.begin_image = pygame.transform.scale(self.begin_image, SCREEN_SIZE) self.default_background = load_image('background.png', return_rect=False) self.building_wall_mask = load_image('background_outline.png', convert_alpha=True, return_rect=False) # background can change to default background or house background self.background = self.default_background # creates the start menus self.pause_menu = PauseMenu(self.screen) self.main_menu = MainMenu(self.screen) self.temp = []
from game import Game from user_input import UserInput player_name = UserInput.get_player_warrior_name() enemy_name = UserInput.get_enemy_warrior_name() max_health = UserInput.get_warriors_max_health() if __name__ == "__main__": game = Game(player_name, enemy_name, max_health) game.start()
from prettytable import PrettyTable import constants as CONST from user_input import UserInput from gas import Gas extended_mode = False if input("Enter extended gas info mode [y/N]? ") == 'y': exec(open("gas_info_extended.py").read()) extended_mode = True while not extended_mode: print("") f_o2 = UserInput().getFloatInput("Fraction of oxygen (decimal) [0.21]: ", 0.01, 1, default_value=0.21) f_he = UserInput().getFloatInput("Fraction of helium (decimal) [0]: ", 0, (1 - f_o2), default_value=0) surf_pressure = UserInput().getFloatInput( "Surface pressure (decimal, bar) [1]: ", 0, 1.1, default_value=1) f_n = 1 - f_o2 - f_he gas = Gas(f_o2, f_n, f_he) fresh_min_od = gas.get_mod(CONST.MIN_PPO2, CONST.DENSITY_FRESHWATER, surf_pressure=surf_pressure) fresh_mod = gas.get_mod(CONST.MAX_PPO2, CONST.DENSITY_FRESHWATER,
def test_get_coffe_type_5(self): userInput = UserInput() with patch("builtins.input", return_value="foo"): assert not userInput.get_coffee_type()
import sys from user_input import UserInput from nitrox_calculations import NitroxCalculations while True: print("") start_mix = UserInput().getFloatInput("Enter the starting mix (decimal): ", 0, 1) start_pressure = UserInput().getFloatInput("Enter the starting pressure (psi): ", 0, sys.float_info.max) desired_mix = UserInput().getFloatInput("Enter the desired mix in (decimal): ", 0, 1) desired_pressure = UserInput().getFloatInput("Enter the desired pressure (psi): ", 0, sys.float_info.max) fill_mix = UserInput().getFloatInput("Enter the fill mix (decimal): ", 0, 1) top_off_mix = .21 print("") print("Starting with " + str(start_pressure) + " psi of " + str(start_mix*100) + "% nitrox.") print("Trying to make " + str(desired_pressure) + " psi of " + str(desired_mix*100) + "% nitrox.") print("With a fill mix of " + str(fill_mix*100) + "% nitrox") print("With a top-off mix of " + str(top_off_mix*100) + "% nitrox") print("") try: fill_instructions = NitroxCalculations().getFillInstructions(start_pressure, start_mix, desired_pressure, desired_mix, fill_mix, top_off_mix) pressure_in_tank = start_pressure while len(fill_instructions) > 0: fill_instruction = fill_instructions.pop(0) pressure_in_tank = pressure_in_tank + fill_instruction[0] if fill_instruction[0] > 0: print("Fill to " + str(round(pressure_in_tank)) + " psi with " + str(round(fill_instruction[1] * 100, 2)) + "% nitrox. (Δ+" + str(round(fill_instruction[0])) + " psi)")
def test_get_coffee_strength_3(self): userInput = UserInput() with patch("builtins.input", return_value=3): assert userInput.get_coffee_strength() == 7
logging.info(" ======= Containers state ======= ") containers = { coffee_container: coffee_container.how_many_ingredient_in_container(), water_container: water_container.how_many_ingredient_in_container(), milk_container: milk_container.how_many_ingredient_in_container(), grounds_container: grounds_container.how_many_ingredient_in_container() } for container in containers: container.print_container_state_progres_bar( ingredient_available=containers[container]) print("") time.sleep(1) user_input = UserInput() drink_type = user_input.get_coffee_type() coffee_strength = user_input.get_coffee_strength() pb1 = ProgressBar(total=100, prefix="Containers preparing", suffix="Complete", decimals=0, length=50, zfill='-') sleep_time = 0.7 coffee_container.take_needed_ingredient_amount(needed_ingredient_amount=3) pb1.print_progress_bar(20) time.sleep(sleep_time)
import sys import constants as CONST from user_input import UserInput from gas import Gas from pressure_calcs import PressureCalcs while True: print("") f_o2 = UserInput().getFloatInput("Fraction of oxygen (decimal) [0.21]: ", 0.01, 1, default_value=0.21) f_he = UserInput().getFloatInput("Fraction of helium (decimal) [0]: ", 0, (1 - f_o2), default_value=0) surf_pressure = UserInput().getFloatInput( "Surface pressure (decimal, bar) [1]: ", 0, 100, default_value=1) density = UserInput().getFloatInput( "Density of the fluid diving in (decimal, kg/m^3) [1000]: ", 0, 15000, default_value=1000) gravity = UserInput().getFloatInput( "Gravitational acceleration (decimal, m/s^2) [9.81]: ", 0, 25, default_value=9.81) ppo2 = UserInput().getFloatInput("Max PPO2 (decimal, bar) [1.4]: ", 0, 100, default_value=1.4)