def main(): print("Welcome to Pyzaak") print("A python Pazaak game") print("May the Force be with you.\n") print("--------\n") playerName = input("Please enter your name: ") print("\n\n\n\n\n") P = Player(playerName) M = Menus(P) M.menu()
def __init__(self, log, settings): self.log = log self.settings = settings # log.debug("App Class Initializing") # Setup home_dir and temp_dir self.home_dir = os.path.expanduser("~") tempfile.tempdir = self.home_dir self.temp_dir = tempfile.TemporaryDirectory() # log.debug('temp_dir: %s', self.temp_dir) # Initialize Frame self.frame = Urwid.Frame( Urwid.Filler(W.get_text('body', 'Loading...Please Wait', 'center'))) # Initialize MainLoop self.loop = Urwid.MainLoop(self.frame, self.settings.display['palette'], unhandled_input=self.unhandled_input, handle_mouse=False) self.errors = 0 self.state = State(self, self.log) self.menus = Menus(self) self.views = Views(self) self.actions = Actions(self) self.views.activate(self, {'view': 'home'}) self.action_pipes = []
def __init__(self, api_key, api_secret): """ Initializes the AWhereAPI class, which is used to perform HTTP requests to the aWhere V2 API. Docs: http://developer.awhere.com/api/reference """ self._fields_url = 'https://api.awhere.com/v2/fields' self._weather_url = 'https://api.awhere.com/v2/weather/fields' self.api_key = api_key self.api_secret = api_secret self.base_64_encoded_secret_key = self.encode_secret_and_key( self.api_key, self.api_secret) self.auth_token = self.get_oauth_token(self.base_64_encoded_secret_key) self._menu = Menus()
def bootstrap(self): self.game_settings.load_settings() self.keys_settings.load_settings() self.display = BasicDisplayUtils() self.input_manager = InputManager(self.keys_settings, self.display) self.menus = Menus(self.input_manager, self.display, self.game_settings, self.keys_settings, self.start_new_game, self.quit)
def __init__(self): self.new_tool = Tools() self.matrix_play = [] self.row = 0 self.column = 0 self.value = 0 self.new_menu = Menus() self.return_game = "" self.boards = integrator.integrator()
def __init__(self,parent, iface,core): self.menu = Menus(iface,core) QtGui.QDialog.__init__(self) self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.parent, self.iface, self.core = parent, iface, core self.linesDic,self.linesCommDic = {},{} for mod in core.modelList: self.linesDic[mod] = core.diczone[mod].getLinesDic() self.linesCommDic[mod] = core.diczone[mod].getLinesCommDic() self.ui = Ui_Main() self.ui.setupUi(self,iface,core) self.ui.pFile.comboFile.activated['QString'].connect(self.fileChange) self.ui.pVar.comboModel.activated['QString'].connect(self.modelChange) self.ui.pVar.comboGroup.activated['QString'].connect(self.groupChange) self.ui.pVar.comboLine.activated['QString'].connect(self.lineChange) self.ui.pVar.comboType.activated['QString'].connect(self.typeChange)
def __init__(self, settings): L.debug("App Class Initializing") self.settings = settings self.frame = U.Frame( U.Filler(W.get_text('body', 'Loading...Please Wait', 'center'))) self.loop = U.MainLoop(self.frame, self.settings.display['palette'], unhandled_input=self.unhandled_input, handle_mouse=False) self.state = State(self) self.views = Views(self) self.menus = Menus(self)
def __init__(self, puzzle): self.sudoku_game = puzzle self.new_tool = Tools() self.matrix = self.new_tool.convert_str_to_matrix(self.sudoku_game, 9, 9) self.new_menus = Menus() self.new_configuration = Configuration() self.new_sudoku_play = SudokuPlay() self.path_of_file = os.getcwd() + "\\configurations\\" self.matrix_play = self.matrix self.row = 0 self.column = 0 self.value = 0 self.algorithm = "" self.difficulty = "" self.solved_out_put = ""
class ConsolePresentation: def __init__(self, puzzle): self.sudoku_game = puzzle self.new_tool = Tools() self.matrix = self.new_tool.convert_str_to_matrix(self.sudoku_game, 9, 9) self.new_menus = Menus() self.new_configuration = Configuration() self.new_sudoku_play = SudokuPlay() self.path_of_file = os.getcwd() + "\\configurations\\" self.matrix_play = self.matrix self.row = 0 self.column = 0 self.value = 0 self.algorithm = "" self.difficulty = "" self.solved_out_put = "" def read_xml(self, file_name): """ It receives an xml file and return root, it has the xml file data """ try: self.tree = xmltree.parse(self.path_of_file + file_name) except: self.tree = xmltree.parse(self.path_of_file+self.name_of_file) self.root = self.tree.getroot() return self.root def get_difficulty_levels(self, root): """ This method we did because we start writing code instead write a unit TC before; so this is an example of what we should not do it. """ list_tmp = "" matrix = [] for levels in root.iter('level'): xml_read = levels.attrib id_xml = xml_read['id'] name_xml = xml_read['name'] min_xml = xml_read['min'] max_xml = xml_read['max'] list_tmp = id_xml, name_xml, min_xml, max_xml matrix.append(list_tmp) return matrix def start_end_menus(self, menu): os.system('cls') self.new_tool.display_board(self.matrix) if menu == "main": self.new_menus.print_main_menu() elif menu == "game": self.new_menus.print_sub_menu_game() elif menu == "play": self.new_menus.print_sub_menu_play() elif menu == "read": self.new_menus.print_sub_menu_read() elif menu == "save": self.new_menus.print_sub_menu_save() elif menu == "options": self.new_menus.print_sub_menu_options() elif menu == "algorithm": self.new_menus.print_sub_menu_algorithm() elif menu == "difficulty": self.new_menus.print_list_difficulty() self.new_menus.print_sub_menu_difficulty() elif menu == "solved_out_put": self.new_menus.print_sub_menu_solved_out_put() elif menu == "edit": self.new_menus.print_sub_menu_edit() if menu == 'play': return raw_input("make your play: ") else: return raw_input("choose: ") def count_zeros(self, matrix): rows = len(matrix) columns = len(matrix[0]) cont_zeros = 0 for row in range(rows): for col in range(columns): if matrix[row][col] == 0: cont_zeros += 1 return cont_zeros def verify_game_completed(self, game_matrix): if self.count_zeros(game_matrix) == 0: return True else: return False def print_main_menu(self, puzzle): read_key = self.start_end_menus("main") while read_key != "X": if read_key == "p": self.new_sudoku_play.play_the_game(puzzle) elif read_key == "o": self.print_sub_menu_options() elif read_key == "x": print "" print "!!! Game Over !!!, ", print "you press key %s..." %(read_key) break else: read_key = raw_input("choose another option.") read_key = self.start_end_menus("main") def print_sub_menu_game(self): read_key = self.start_end_menus("game") while read_key != "B": if read_key == "p": self.play_the_game() elif read_key == "g": print "you press key %s" %(read_key) elif read_key == "l": print "You press key %s" % read_key elif read_key == "r": self.print_sub_menu_read() elif read_key == "s": self.print_sub_menu_save() elif read_key == "t": print "you press key %s" %(read_key) elif read_key == "b": break else: read_key = raw_input("choose another option.") read_key = self.start_end_menus("game") def print_sub_menu_read(self): read_key = self.start_end_menus("read") while read_key != "B": if read_key == "t": print "you press key %s" %(read_key) elif read_key == "v": print "you press key %s" %(read_key) elif read_key == "c": print "you press key %s" %(read_key) elif read_key == "b": break else: read_key = raw_input("choose another option.") read_key = self.start_end_menus("read") def print_sub_menu_save(self): read_key = self.start_end_menus("save") while read_key != "B": if read_key == "t": print "You press key %s" % read_key elif read_key == "c": print "you press key %s" %(read_key) elif read_key == "h": print "You press key %s" % read_key elif read_key == "b": break else: read_key = raw_input("choose another option.") read_key = self.start_end_menus("save") def print_sub_menu_options(self): read_key = self.start_end_menus("options") while read_key != "B": if read_key == "a": self.print_sub_menu_algorithm() elif read_key == "d": self.print_sub_menu_difficulty() elif read_key == "v": self.print_sub_menu_solved_out_put() elif read_key == "b": break else: read_key = raw_input("choose another option.") read_key = self.start_end_menus("options") def print_sub_menu_algorithm(self): read_key = self.start_end_menus("algorithm") while read_key != "B": if read_key == "k": self.algorithm = "backtracking" self.new_configuration.modify_value_in_xml(self.algorithm,"algorithm") raw_input ("you chose " +self.algorithm + " Algorithm") break elif read_key == "n": self.algorithm = "peternorvig" self.new_configuration.modify_value_in_xml(self.algorithm,"algorithm") raw_input ("you chose " + "Peter Norvig" + " Algorithm") break elif read_key == "i": self.algorithm = "recursive" self.new_configuration.modify_value_in_xml(self.algorithm,"algorithm") raw_input ("you chose " +self.algorithm + " Algorithm") break elif read_key == "b": break else: read_key = raw_input("choose another option.") read_key = self.start_end_menus("algorithm") def print_sub_menu_difficulty(self): read_key = self.start_end_menus("difficulty") difficulty_matrix = self.new_menus.get_difficulty_matrix() while read_key != "B": if read_key == "e": self.print_sub_menu_edit() try: if read_key == "e": self.print_sub_menu_edit() elif read_key == "0": self.difficulty = difficulty_matrix[0][1] self.new_configuration.modify_value_in_xml(self.difficulty,"difficulty") raw_input ("You chose " + self.difficulty + " as difficulty level") break elif read_key == "1": self.difficulty = difficulty_matrix[1][1] self.new_configuration.modify_value_in_xml(self.difficulty,"difficulty") raw_input ("You chose "+ self.difficulty + " as difficulty level") break elif read_key == "2": self.difficulty = difficulty_matrix[2][1] self.new_configuration.modify_value_in_xml(self.difficulty,"difficulty") raw_input ("You chose "+ self.difficulty + " as difficulty level") break elif read_key == "3": self.difficulty = difficulty_matrix[3][1] self.new_configuration.modify_value_in_xml(self.difficulty,"difficulty") raw_input ("You chose "+ self.difficulty + " as difficulty level") break elif read_key == "4": self.difficulty = difficulty_matrix[4][1] self.new_configuration.modify_value_in_xml(self.difficulty,"difficulty") raw_input ("You chose "+ self.difficulty + " as difficulty level") break elif read_key == "5": self.difficulty = difficulty_matrix[5][1] self.new_configuration.modify_value_in_xml(self.difficulty,"difficulty") raw_input ("You chose "+ self.difficulty + " as difficulty level") break elif read_key == "b": break else: read_key = raw_input("choose another option.") except: raw_input("Choose another option") read_key = self.start_end_menus("difficulty") def print_sub_menu_solved_out_put(self): read_key = self.start_end_menus("solved_out_put") difficulty_matrix = self.new_menus.get_difficulty_matrix() while read_key != "B": if read_key == "e": self.print_sub_menu_edit() try: if read_key == "t": self.solved_out_put = "txt" self.new_configuration.modify_value_in_xml(self.solved_out_put,"solver_output_type") raw_input ("You chose " + self.solved_out_put + " as solver output type") break elif read_key == "c": self.solved_out_put = "csv" self.new_configuration.modify_value_in_xml(self.solved_out_put,"solver_output_type") raw_input ("You chose "+ self.solved_out_put + " as solver output type") break elif read_key == "h": self.solved_out_put = "html" self.new_configuration.modify_value_in_xml(self.solved_out_put,"solver_output_type") raw_input ("You chose "+ self.solved_out_put + " as solver output type ") break elif read_key == "b": break else: read_key = raw_input("choose another option.") except: raw_input("Choose another option") read_key = self.start_end_menus("difficulty") def print_sub_menu_edit(self): read_key = self.start_end_menus("edit") while read_key != "B": if read_key == "n": print "You press key %s" % read_key elif read_key == "c": print "you press key %s" %(read_key) elif read_key == "b": break else: read_key = raw_input("choose another option.") read_key = self.start_end_menus("edit") def run_app(self, puzzle): self.print_main_menu(puzzle)
def refresh_content(self, signal, frame): Menus.load() for handler in self.handlers: handler.reload()
def run(self): running = True tower_menu = Menus() frame = 1000 tick = 16 spawn_tick = 250 #proof = Towers((5, 5)) tower_menu.draw(screen) ground = self.load_level(2) sprite_terrain.draw(background) # Draws background terrain window.blit(background, (0, 0)) pygame.display.update() grid = pathfinder.AStar() grid.init_path(grid_row, grid_col, self.road, self.start, self.end) route = grid.process() render_sprites = pygame.sprite.LayeredUpdates(sprite_terrain, sprite_path, layer=1) while running: for event in pygame.event.get(): mouse_pos = pygame.mouse.get_pos() ratio_x = (window.get_width() / screen.get_width()) ratio_y = (window.get_height() / screen.get_height()) mouse_scaled = (mouse_pos[0] / ratio_x, mouse_pos[1] / ratio_y) if event.type == pygame.QUIT: running = False sys.exit(0) if event.type == pygame.MOUSEBUTTONDOWN: # check for left button if event.button == 1: # if tower_menu.basic_tower_button.collidepoint(mouse_scaled): # tower_menu.click(screen, tower_menu.basic_tower_button, True) # elif tower_menu.ice_tower_button.collidepoint(mouse_scaled): # tower_menu.click(screen, tower_menu.ice_tower_button, True) for x in range(grid_col): for y in range(grid_row): if pygame.Rect(ground[x][y].location).collidepoint(mouse_scaled): if ground[x][y].can_place: self.towers.append(Towers(ground[x][y].location)) ground[x][y].can_place = False render_sprites.add(sprite_towers, layer=2) for num in range(len(self.minion)): if self.minion[num].sprite.rect.collidepoint(mouse_scaled): self.minion[num].health = 0 # if event.type == pygame.MOUSEBUTTONUP: # if event.button == 1: # # if tower_menu.state: # # tower_menu.click(screen, tower_menu.basic_tower_button, False) # # if tower_menu.basic_tower_button.collidepoint(mouse_scaled) and not tower_menu.over: # # tower_menu.hover(screen, tower_menu.basic_tower_button) # # elif tower_menu.over and not tower_menu.basic_tower_button.collidepoint(mouse_scaled): # # tower_menu.hover_off(screen, tower_menu.basic_tower_button) if time() > tick: tick = time() + 17 kill = [] minion_hitboxs = [] for num in range(len(self.minion)): if self.minion[num]: if not self.minion[num].alive: kill.append(num) elif self.minion[num].health > 0: self.minion[num].update_location(route) minion_hitboxs.append(self.minion[num].sprite.rect) if len(kill) > 0: # If there are minions to kill in the list this del them for d in range(len(kill)): del self.minion[kill[d]] kill = [] for num in range(len(self.towers)): current_tower = self.towers[num] collision_index = current_tower.hit_box.rect.collidelist(minion_hitboxs) if not collision_index == -1 and current_tower.target == None: current_tower.target = collision_index elif not current_tower.target == collision_index: current_tower.target = None if not current_tower.target == None: self.minion[current_tower.target].health -= current_tower.damage #Clears then render sprites to display render_sprites.remove_sprites_of_layer(3) render_sprites.add(sprite_creeps, layer=3) if time() > frame: # Update minion animation frames frame = 80 + time() for num in range(len(self.minion)): if self.minion[num].health <= 0: if self.minion[num].update(12) == "dead": self.minion[num].alive = False else: self.minion[num].update() for num in range(len(self.towers)): self.towers[num].update() if time() > spawn_tick: if wave_Count >= len(self.minion): spawn_type = random.choice([Dwarf, Deer, Satyr, Hunter, Druid, Pixie]) #spawn_type = [Dwarf, Deer, Satyr, Hunter, Druid, Pixie] self.minion.append(spawn_type(self.spawn)) spawn_tick = time() + 500 render_sprites.add(sprite_creeps, layer = 3) #if wave_Count >= len(self.minion): # self.minion.append(Deer(self.spawn)) # spawn_tick = time() + 500 #render_sprites.add(sprite_creeps) clock.tick() render_sprites.draw(screen) #for num in range(len(self.towers)): # screen.blit(self.towers[num].hit_box.image, (self.towers[num].sprite.rect.center)) fps = myfont.render(str(int(clock.get_fps())), 1, (255, 255, 255), (15, 210, 50)) screen.blit(fps, (20, screen_height - 30)) window.blit((render_to_window(screen)), (0, 0)) pygame.display.update()
from menus import Menus from game_regra import GameRegra menu = Menus() menu.mostrar_menu() gameRegra = GameRegra() if menu.opcao == 1: gameRegra.solicitar_cadastro() elif menu.opcao == 2: gameRegra.visualizar_cadastro() elif menu.opcao == 3: gameRegra.deletar() elif menu.opcao == 4: gameRegra.alterar() else: print('Obrigado e volte sempre!') exit(0)
field_id = menu.get_weather_field_id() aWhere.get_weather_by_id(field_id) elif user_input == 3: aWhere.create_test_field() elif user_input == 4: aWhere.get_fields() field_id = menu.get_delete_field_id() aWhere.delete_field_by_id(field_id) elif user_input == 0: quit_requested = True else: print('Invalid Selection! Please try again') quit_requested = False menu = Menus() # Enter your Api Key and Secret below: api_key = '' api_secret = '' # Main Entry Point if user_has_credentials(): aWhere = AWhereAPI(api_key, api_secret) menu.display_title() while not quit_requested: menu.display_menu() user_input = menu.get_user_input() menu.clear_screen() handle_user_input(user_input, aWhere)
class mainDialogGenerate(QtGui.QDialog): def __init__(self,parent, iface,core): self.menu = Menus(iface,core) QtGui.QDialog.__init__(self) self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.parent, self.iface, self.core = parent, iface, core self.linesDic,self.linesCommDic = {},{} for mod in core.modelList: self.linesDic[mod] = core.diczone[mod].getLinesDic() self.linesCommDic[mod] = core.diczone[mod].getLinesCommDic() self.ui = Ui_Main() self.ui.setupUi(self,iface,core) self.ui.pFile.comboFile.activated['QString'].connect(self.fileChange) self.ui.pVar.comboModel.activated['QString'].connect(self.modelChange) self.ui.pVar.comboGroup.activated['QString'].connect(self.groupChange) self.ui.pVar.comboLine.activated['QString'].connect(self.lineChange) self.ui.pVar.comboType.activated['QString'].connect(self.typeChange) def showDialogAndDisconnect(self): self.show() self.iface.actionToggleEditing().triggered.disconnect(self.showDialogAndDisconnect) def fileChange(self,value): if value=='Open': self.menu.OnOpen(self) self.parent.visu.clearLayers() self.parent.visu.initDomain() self.parent.visu.qgsCore2Zones() # set the show results part tl2 = self.core.getTlist2() # pb of shape of tl2 self.iface.onMessage(str(tl2)) self.ui.pShow.setNames('Aquifer_Tstep_L',tl2) listSpec = self.core.addin.pht3d.getListSpecies() # just the names self.ui.pShow.setChemSpecies(listSpec) if value=='Save': self.parent.visu.qgsZones2Core() self.menu.OnSave(self) #self.ui.pFile.comboImport.clear() #self.ui.pFile.comboImport.insertItems(0,['c','b']) def modelChange(self,model): self.model = model self.ui.pVar.comboGroup.clear() for i,n in enumerate(self.linesDic[model].keys()): self.ui.pVar.comboGroup.addItem("") self.ui.pVar.comboGroup.setItemText(i, QApplication.translate("Type", n, None, QApplication.UnicodeUTF8)) def groupChange(self,group): self.group = group self.ui.pVar.comboLine.clear() l1 = self.linesDic[self.model][group] l2 = self.linesCommDic[self.model][group] for i in range(len(l1)): self.ui.pVar.comboLine.addItem("") n = l1[i][:5]+' '+l2[i] self.ui.pVar.comboLine.setItemText(i, QApplication.translate("Type", n, None, QApplication.UnicodeUTF8)) def lineChange(self,line): self.line = line[:5] typeList = ['one_value','formula','zone','edit','interpolate','import'] typ = self.core.dictype[self.model][self.line][0] self.ui.pVar.comboType.setCurrentIndex(typeList.index(typ)) def typeChange(self,typ): self.core.dictype[self.model][self.line][0] = typ lines = self.linesDic[self.model][self.group] il = lines.index(self.line) layerName = lines[il] if typ == 'zone': self.parent.visu.createLayer(layerName)
class App: """App App is a simple class to manage the entire game. """ def __init__(self, resolution): pygame.init() self.settings = {} self.settings['sound_system'] = True self.settings['stage_music'] = True # TODO: implement this self.settings['music'] = True self.settings['music_vol'] = .4 self.settings['sounds'] = True # TODO: implement this # pygame.mixer.init(frequency=44100, size=-16, channels=2, # buffer=4096) if self.settings['sound_system']: print("initializing sound with volume " + str(self.settings['music_vol'])) pygame.mixer.init(frequency=44100, channels=2) pygame.mixer.music.set_volume(self.settings['music_vol']) else: self.settings['sounds'] = False self.settings['music'] = False if self.settings['music']: pygame.mixer.music.set_endevent(pygame.USEREVENT) else: self.settings['stage_music'] = False print("effective settings: " + str(self.settings)) self.music_name = None self.queued_music_name = None self.prev_offset = 0.0 self.prev_song_len = 0.0 self.music_loaded = None self.clock = pygame.time.Clock() self.music_count = -1 data_sub_dir = "data" ced = os.path.dirname(__file__) # current executable directory self.DATA_PATH = os.path.join(ced, data_sub_dir) self.screen = pygame.display.set_mode(resolution) pygame.display.set_caption("Pylaga " + __version__) self.world = World(self, self.screen) logo_image = self.load_file("screen-intro.png") cursor_image = self.load_file('pship0.png') about_string = ''' PYLAGA Code License: GPL 3.0 Media License: CC-BY-SA 4.0 International Original Creator: Derek Mcdonald FreeSansBold.ttf: Copyleft 2002, 2003, 2005, 2008, 2009, 2010 Free Software Foundation ([GPL License] (https://www.gnu.org/licenses/gpl-3.0.en.html)) PYLAGA fork [python 2] RJ Marsan (gmail RJMarsan) PYLAGA [Python 3] new graphics new enemies removed globalvars sound fx [own work] particles poikilos CRYSTAL-Regular.ttf: Felipe Munoz (CC-BY SA 4.0 International) Music MixMystery ''' help_string = ''' MOVE: move mouse FIRE: click/tap MENU: Escape ("Esc") key MENU controls: click/tap choice, or use arrows & enter key (Esc or q key to resume/retry) EXIT: In the menu, click EXIT (or select EXIT with arrows then press Enter key) ''' pages_dict = { 'ABOUT': { 'scroll_text': about_string }, 'HELP': { 'scroll_text': help_string } } # pages_dict['ABOUT']['scroll_text'] = about_string # pages_dict['HELP'] = {} # pages_dict['HELP']['scroll_text'] = help_string self.menus = Menus(self.world.statcounter, self, logo_image, cursor_image, pages_dict) init_menu_strings = ["PLAY", "ABOUT", "HELP", "EXIT"] self.menus.show_dialog(init_menu_strings) print("starting world...") self.world.start(self.menus) tries = 1 open_page = None caption = None retry_menu_strings = [ "RETRY", "ABOUT", "HELP", "EXIT", "Score: %s" % self.world.statcounter.get_val() ] if self.world.won: open_page = 'ABOUT' caption = self.world.won_msg # retry_menu_strings.insert(0, self.world.won_msg) else: caption = 'GAME OVER' # retry_menu_strings.insert(0, 'GAME OVER') while ((not self.menus.get_bool('exit')) and (self.menus.show_dialog(retry_menu_strings, cursor_spin=-1.0, open_page=open_page, caption=caption))): print("starting world (tries: " + str(tries) + ")...") self.world.start(self.menus) open_page = None retry_menu_strings = [ "RETRY", "ABOUT", "HELP", "EXIT", "Score: %s" % self.world.statcounter.get_val() ] if self.world.won: open_page = 'ABOUT' caption = self.world.won_msg # retry_menu_strings.insert(0, self.world.won_msg) else: caption = 'GAME OVER' # retry_menu_strings.insert(0, 'GAME OVER') tries += 1 self.world.on_exit() def get_fps(self): return 60 def queue_music(self, name, count): if self.settings['music']: if name is not None: print("queue_music: " + name) for i in range(count): pygame.mixer.music.queue(self.resource_find(name)) pygame.mixer.music.play() self.queued_music_name = name else: print("ERROR in queue_music: name is " + str(name)) # since queued explicitly, stop check_music: self.music_name = None def check_music(self): if self.settings['music']: if self.music_name is not None: if self.music_loaded != self.music_name: # get_pos does not take into account start time, # so account for that using self.prev_offset offset = pygame.mixer.music.get_pos() tmp = pygame.mixer.Sound( self.resource_find(self.music_name)) song_len = tmp.get_length() if offset > self.prev_song_len: # print("WARNING: offset " + str(offset) + # " > previous song_len" + # str(self.prev_song_len)) if self.prev_song_len > 0.0: offset = math.fmod(offset, self.prev_song_len) if offset > self.prev_offset: offset += self.prev_offset else: offset = offset - self.prev_offset if offset > song_len: print("WARNING: offset " + str(offset) + " > song_len " + str(song_len)) pygame.mixer.music.load(self.resource_find( self.music_name)) # only seemless if different variation of same loop: pygame.mixer.music.play(-1, start=offset) self.music_loaded = self.music_name # pygame.mixer.music.set_pos(offset) self.prev_offset = offset self.prev_song_len = song_len else: if self.music_loaded != None: self.music_loaded = None pygame.mixer.music.stop() def continue_music(self): if self.settings['music']: if self.music_name is not None: if self.music_loaded != self.music_name: pygame.mixer.music.load(self.resource_find( self.music_name)) # plays once PLUS repeats if int is specified: print("playing music only once...") pygame.mixer.music.play() # general exception handler # (formerly used during imports to avoid exit without warning) # call this in any except clause def exception_handler(): import traceback import sys type, info, trace = sys.exc_info() tracetop = traceback.extract_tb(trace)[-1] tracetext = 'File %s, Line %d' % tracetop[:2] if tracetop[2] != '?': tracetext += ', Function %s' % tracetop[2] exception_message = '%s:\n%s\n\n%s\n"%s"' message = (exception_message % (str(type), str(info), tracetext, tracetop[3])) if type not in (KeyboardInterrupt, SystemExit): print(message) raise def zero_padded(self, i, min_digits): s = str(i) if len(s) < min_digits: s = '0' * (min_digits - len(s)) + s return s def get_seq_info(self, name_except_number, dot_ext=".png"): results = { 'min_digits': None, 'first_i': None, 'directory': None, 'tried_paths': [], 'found': False } try_dirs = [ '.', self.DATA_PATH, os.path.dirname(os.path.abspath(__file__)) ] never_pad_len = 5 for parent in try_dirs: for min_digits in range(never_pad_len): for first_i in range(2): name = (name_except_number + self.zero_padded(first_i, min_digits) + dot_ext) path = os.path.join(parent, name) if os.path.isfile(path): results['min_digits'] = min_digits results['first_i'] = first_i results['directory'] = parent results['found'] = True return results else: results['tried_paths'].append(path) return results def load_seq(self, name_except_number, dot_ext=".png", min_digits=0): results = None info = self.get_seq_info(name_except_number) if info['found']: results = [] i = info['first_i'] while True: name = (name_except_number + self.zero_padded(i, info['min_digits']) + dot_ext) path = os.path.join(info['directory'], name) if os.path.exists(path): surf = self.load_file(name, try_dirs=[info['directory']]) if surf is not None: results.append(surf) i += 1 else: print("ERROR in load_seq: image unreadable: " + path) break else: break # no errors, just no more images left in seq else: print("No png sequence found named " + name_except_number + ". Tried:") for try_path in results['tried_paths']: print(" " + try_path) return results def resource_find(self, name, repress_error_enable=False, try_dirs=None, file_type='image'): ret = None if try_dirs is None: try_dirs = [ '.', self.DATA_PATH, os.path.dirname(os.path.abspath(__file__)) ] for parent in try_dirs: path = os.path.join(parent, name) if os.path.isfile(path): ret = path if ret is None: if not repress_error_enable: print("ERROR in main.py: failed to find resource '" + name + "'") return ret def load_file(self, name, repress_error_enable=False, try_dirs=None, file_type='image'): try: if try_dirs is None: try_dirs = [ '.', self.DATA_PATH, os.path.dirname(os.path.abspath(__file__)) ] for parent in try_dirs: path = os.path.join(parent, name) if os.path.isfile(path): if file_type == 'image': return pygame.image.load(path).convert_alpha() else: return pygame.mixer.Sound(path) except: if not repress_error_enable: print("Failed to load file " + str(name)) return None
def setUp(self): self.new_menu = Menus()
def main(): """ Main Program """ pygame.init() # Set the height and width of the screen size = [SCREEN_WIDTH, SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Platformer Fighting Game") # Manage how fast the screen updates fps_clock = pygame.time.Clock() fps = 30 # Create and setup player 1 and player 2 player = Player(SCREEN_HEIGHT, SCREEN_WIDTH, screen, 0) player2 = Player(SCREEN_HEIGHT, SCREEN_WIDTH, screen, 1) player.enemy = player2 player2.enemy = player player.create_sword() player2.create_sword() #Load menu music #pygame.mixer.music.load('resources\music\Dark Ambience.ogg') pygame.mixer.music.load('resources\music\Last_Man_Standing.ogg') pygame.mixer.music.play() menu = Menus(screen) # If settings is one camera will be None else a camera is created camera = None cam_option = menu.camera_choice() if cam_option: camera = camera_movment(player, player2) menu.loading() # Create all the levels level_list = [] level_list.append(Level_01(player, player2)) level_list.append(Level_02(player, player2)) # Set the current Level current_level_no = menu.level_choice() current_level = level_list[current_level_no] player.level = current_level player2.level = current_level # Create list active_sprite_list = pygame.sprite.Group() projectile_sprite_list = pygame.sprite.Group() # set players position reset_players(player, player2, camera) # Add players and if need the camera to list active_sprite_list.add(player) active_sprite_list.add(player2) if camera is not None: active_sprite_list.add(camera) #Load sounds sword_sound = pygame.mixer.Sound('resources/sounds/sword_sound.wav') laser_sound = pygame.mixer.Sound('resources/sounds/laser_sound.ogg') set_music(current_level_no) # Loop until the user clicks the close button done = False while(True): # ------ Main Program Loop ------ while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True sys.exit() # Player 1 controls if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: player.go_left() if event.key == pygame.K_d: player.go_right() if event.key == pygame.K_w: player.jump() if event.key == pygame.K_s: player.drop() if event.key == pygame.K_f: if player.sufficient_stamina(1): laser_sound.play() laser = player.range_attack() active_sprite_list.add(laser) projectile_sprite_list.add(laser) current_level.projectile_list.append(laser) if event.key == pygame.K_t: player.attacking = True sword_sound.play() if event.type == pygame.KEYUP: if event.key == pygame.K_a and player.change_x < 0: player.stop() if event.key == pygame.K_d and player.change_x > 0: player.stop() # Player 2 controls if event.type == pygame.KEYDOWN: if event.key == pygame.K_h: player2.go_left() if event.key == pygame.K_k: player2.go_right() if event.key == pygame.K_u: player2.jump() if event.key == pygame.K_j: player2.drop() if event.key == pygame.K_l: if player2.sufficient_stamina(1): laser_sound.play() laser = player2.range_attack() active_sprite_list.add(laser) projectile_sprite_list.add(laser) current_level.projectile_list.append(laser) if event.key == pygame.K_p: player2.attacking = True sword_sound.play() if event.type == pygame.KEYUP: if event.key == pygame.K_h and player2.change_x < 0: player2.stop() if event.key == pygame.K_k and player2.change_x > 0: player2.stop() for laser in projectile_sprite_list: if (laser.rect.x > laser.starting_x + laser.range or laser.rect.x < laser.starting_x - laser.range): projectile_sprite_list.remove(laser) active_sprite_list.remove(laser) hit = pygame.sprite.collide_rect(laser, laser.enemy) if hit: laser.enemy.damage(laser.player.laser_damage * laser.player.stamina_penalty + laser.dmg) projectile_sprite_list.remove(laser) active_sprite_list.remove(laser) # If the player gets near the right side, shift the world left (-x) shift_left(player, current_level, camera) # If the player gets near the left side, shift the world right (+x) shift_right(player, current_level, camera) player.left_screen_boundary = player2.rect.x - 850 player.right_screen_boundary = player2.rect.x + 850 player2.left_screen_boundary = player.rect.x - 850 player2.right_screen_boundary = player.rect.x + 850 # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw(screen) active_sprite_list.draw(screen) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT # Update the player active_sprite_list.update() # Update items in the level current_level.update() # Limit to 60 frames per second fps_clock.tick(fps) # Go ahead and update the screen with what we've drawn. pygame.display.flip() if not player.alive: done = True menu.display_winner('Player 2 wins') elif not player2.alive: menu.display_winner('Player 1 wins') done = True projectile_sprite_list.empty() # Game Over screen # prompt user for rematch or quit done = menu.game_over() # If rematch show level select then reset everything if not done: current_level_no = menu.level_choice() current_level = level_list[current_level_no] player.level = current_level player2.level = current_level set_music(current_level_no) reset_players(player, player2, camera)
class AWhereAPI(object): def __init__(self, api_key, api_secret): """ Initializes the AWhereAPI class, which is used to perform HTTP requests to the aWhere V2 API. Docs: http://developer.awhere.com/api/reference """ self._fields_url = 'https://api.awhere.com/v2/fields' self._weather_url = 'https://api.awhere.com/v2/weather/fields' self.api_key = api_key self.api_secret = api_secret self.base_64_encoded_secret_key = self.encode_secret_and_key( self.api_key, self.api_secret) self.auth_token = self.get_oauth_token(self.base_64_encoded_secret_key) self._menu = Menus() def create_test_field(self): """ Performs a HTTP POST request to create and add a Field to your aWhere App.AWhereAPI Docs: http://developer.awhere.com/api/reference/fields/create-field """ # Each Field requires a unique ID testField = 'TestField-' testField += str(random.randint(1, 999)) # Next, we build the request body. Please refer to the docs above for # more info. fieldBody = {'id': testField, 'name': testField, 'farmId': 'Farm1Test', 'centerPoint': {'latitude': 39.82, 'longitude': -98.56}, 'acres': 100} # Setup the HTTP request headers auth_headers = { "Authorization": "Bearer %s" % self.auth_token, "Content-Type": 'application/json' } # Perform the POST request to create your Field print('Attempting to create new field....\n') response = rq.post(self._fields_url, headers=auth_headers, json=fieldBody) # A successful request will return a 201 status code print('The server responded with a status code of %d \n' % response.status_code) pprint.pprint(response.json()) print('\n\n\n') if response.status_code == 201: print( 'Your field "{0}" was successfully created!'.format(testField)) else: print('An error occurred. Please review the above resonse and try again.') def delete_field_by_id(self, field_id): """ Performs a HTTP DELETE request to delete a Field from your aWhere App. Docs: http://developer.awhere.com/api/reference/fields/delete-field Args: field_id: The field to be deleted """ # Setup the HTTP request headers auth_headers = { "Authorization": "Bearer %s" % self.auth_token, "Content-Type": 'application/json' } # Perform the POST request to Delete your Field response = rq.delete(self._fields_url + '/{0}'.format(field_id), headers=auth_headers) print('The server responded with a status code of %d' % response.status_code) def encode_secret_and_key(self, key, secret): """ Docs: http://developer.awhere.com/api/authentication Returns: Returns the base64-encoded {key}:{secret} combination, seperated by a colon. """ # Base64 Encode the Secret and Key key_secret = '%s:%s' % (key, secret) #print('\nKey and Secret before Base64 Encoding: %s' % key_secret) encoded_key_secret = base64.b64encode( bytes(key_secret, 'utf-8')).decode('ascii') #print('Key and Secret after Base64 Encoding: %s' % encoded_key_secret) return encoded_key_secret def get_fields(self): """ Performs a HTTP GET request to obtain all Fields you've created on your aWhere App. Docs: http://developer.awhere.com/api/reference/fields/get-fields """ # Setup the HTTP request headers auth_headers = { "Authorization": "Bearer %s" % self.auth_token, } # Perform the HTTP request to obtain a list of all Fields fields_response = rq.get(self._fields_url, headers=auth_headers) responseJSON = fields_response.json() # Display the count of Fields the user has on their account print('You have %s fields registered on your account' % len(responseJSON["fields"])) # Iterate over the fields and display their name and ID print('{0} {1} \t\t {2}'.format('#', 'Field Name', 'Field ID')) print('-------------------------------------------') count = 0 for field in responseJSON["fields"]: count += 1 print('{0}. {1} \t {2}\r'.format( count, field["name"], field["id"])) def get_weather_by_id(self, field_id): """ Performs a HTTP GET request to obtain Forecast, Historical Norms and Forecasts Docs: 1. Forecast: http://developer.awhere.com/api/forecast-weather-api 2. Historical Norms: http://developer.awhere.com/api/reference/weather/norms 3. Observations: http://developer.awhere.com/api/reference/weather/observations """ # Setup the HTTP request headers auth_headers = { "Authorization": "Bearer %s" % self.auth_token, } # Perform the HTTP request to obtain the Forecast for the Field response = rq.get(self._weather_url + '/{0}/forecasts?blockSize=24'.format(field_id), headers=auth_headers) pprint.pprint(response.json()) print('\nThe above response from the Forecast API endpoint shows the forecast for your field location ({0}).'.format(field_id)) self._menu.os_pause() # Next, let's obtain the historic norms for a Field response = rq.get(self._weather_url + '/{0}/norms/04-04'.format(field_id), headers=auth_headers) pprint.pprint(response.json()) print('\nThe above response from the Norms API endpoint shows the averages of the last 10 for an arbitrary date, April 4th.') self._menu.os_pause() # Finally, display the observed weather. Returns the last 7 days of data for the provided Field. response = rq.get(self._weather_url + '/{0}/observations'.format(field_id), headers=auth_headers) pprint.pprint(response.json()) print('\nThe above response from the Observed Weather API endpoint shows the last 7 days of data for the provided field ({0})'.format(field_id)) def get_oauth_token(self, encoded_key_secret): """ Demonstrates how to make a HTTP POST request to obtain an OAuth Token Docs: http://developer.awhere.com/api/authentication Returns: The access token provided by the aWhere API """ auth_url = 'https://api.awhere.com/oauth/token' auth_headers = { "Authorization": "Basic %s" % encoded_key_secret, 'Content-Type': 'application/x-www-form-urlencoded' } body = "grant_type=client_credentials" response = rq.post(auth_url, headers=auth_headers, data=body) # .json method is a requests lib method that decodes the response return response.json()['access_token']
class UnitTestMenus(unittest.TestCase): def setUp(self): self.new_menu = Menus() def test_menu_has_a_title(self): pass """ Main Menu """ def test_main_menu_should_be_Game_while_main_menu_has_bee_set_g(self): self.new_menu.set_main_menu("g") self.assertEqual("Game", self.new_menu.get_main_menu()) def test_main_menu_should_be_Option_while_main_menu_has_bee_set_o(self): self.new_menu.set_main_menu("o") self.assertEqual("Option", self.new_menu.get_main_menu()) def test_main_menu_should_be_Exit_while_main_menu_has_bee_set_x(self): self.new_menu.set_main_menu("x") self.assertEqual("Exit", self.new_menu.get_main_menu()) def test_main_menu_should_not_continue_to_different_option(self): self.new_menu.set_main_menu("a") self.assertEqual("choose another option", self.new_menu.get_main_menu()) """ Sub Menu Game """ def test_sub_menu_Game_should_be_Play_while_it_has_been_set_p(self): self.new_menu.set_sub_menu_game("p") self.assertEqual("Play", self.new_menu.get_sub_menu_game()) def test_sub_menu_Game_should_be_Generate_while_it_has_been_set_g(self): self.new_menu.set_sub_menu_game("g") self.assertEqual("Generate", self.new_menu.get_sub_menu_game()) def test_sub_menu_Game_should_be_Resolve_while_it_has_been_set_l(self): self.new_menu.set_sub_menu_game("l") self.assertEqual("Resolve", self.new_menu.get_sub_menu_game()) def test_sub_menu_Game_should_be_Read_while_it_has_been_set_r(self): self.new_menu.set_sub_menu_game("r") self.assertEqual("Read", self.new_menu.get_sub_menu_game()) def test_sub_menu_Game_should_be_Save_while_it_has_been_set_s(self): self.new_menu.set_sub_menu_game("s") self.assertEqual("Save", self.new_menu.get_sub_menu_game()) def test_sub_menu_Game_should_be_Reset_while_it_has_been_set_t(self): self.new_menu.set_sub_menu_game("t") self.assertEqual("Reset", self.new_menu.get_sub_menu_game()) def test_sub_menu_Game_should_be_Back_while_it_has_been_set_b(self): self.new_menu.set_sub_menu_game("b") self.assertEqual("Back", self.new_menu.get_sub_menu_game()) def test_sub_menu_Game_should_not_continue_to_some_one_else_selection_higher_than_6(self): self.new_menu.set_sub_menu_game(7) self.assertEqual("choose another option", self.new_menu.get_sub_menu_game()) def test_sub_menu_Game_should_not_continue_to_some_one_else_selection_lower_than_1(self): self.new_menu.set_sub_menu_game(-3) self.assertEqual("choose another option", self.new_menu.get_sub_menu_game()) def test_sub_menu_Game_should_not_continue_to_different_option(self): self.new_menu.set_sub_menu_game("f") self.assertEqual("choose another option", self.new_menu.get_sub_menu_game()) """ Sub Menu Read """ def test_sub_menu_Read_should_be_Txt_while_it_has_been_set_t(self): self.new_menu.set_sub_menu_read("t") self.assertEqual("txt", self.new_menu.get_sub_menu_read()) def test_sub_menu_Read_should_be_Csv_while_it_has_been_set_c(self): self.new_menu.set_sub_menu_read("c") self.assertEqual("csv", self.new_menu.get_sub_menu_read()) def test_sub_menu_Read_should_be_Read_while_it_has_been_set_b(self): self.new_menu.set_sub_menu_read("b") self.assertEqual("Back", self.new_menu.get_sub_menu_read()) def test_sub_menu_Read_should_not_continue_to_alphabetic_option(self): self.new_menu.set_sub_menu_read("f") self.assertEqual("choose another option", self.new_menu.get_sub_menu_read()) """ Sub Menu Save """ def test_sub_menu_Save_should_be_Txt_while_it_has_been_set_t(self): self.new_menu.set_sub_menu_save("t") self.assertEqual("txt", self.new_menu.get_sub_menu_save()) def test_sub_menu_Save_should_be_Csv_while_it_has_been_set_c(self): self.new_menu.set_sub_menu_save("c") self.assertEqual("csv", self.new_menu.get_sub_menu_save()) def test_sub_menu_Save_should_be_Html_while_it_has_been_set_h(self): self.new_menu.set_sub_menu_save("h") self.assertEqual("html", self.new_menu.get_sub_menu_save()) def test_sub_menu_Save_should_be_Back_while_it_has_been_set_4(self): self.new_menu.set_sub_menu_save("b") self.assertEqual("Back", self.new_menu.get_sub_menu_save()) def test_sub_menu_Save_should_not_continue_to_different_option(self): self.new_menu.set_sub_menu_save("a") self.assertEqual("choose another option", self.new_menu.get_sub_menu_save()) """ Sub Menu Option """ def test_sub_menu_Options_should_be_Algorithm_while_it_has_been_set_a(self): self.new_menu.set_sub_menu_options("a") self.assertEqual("Algorithm", self.new_menu.get_sub_menu_options()) def test_sub_menu_Options_should_be_Difficulty_while_it_has_been_set_d(self): self.new_menu.set_sub_menu_options("d") self.assertEqual("Difficulty", self.new_menu.get_sub_menu_options()) def test_sub_menu_Options_should_be_Solver_out_put_while_it_has_been_set_v(self): self.new_menu.set_sub_menu_options("v") self.assertEqual("Solver_out_put", self.new_menu.get_sub_menu_options()) def test_sub_menu_Options_should_be_Back_while_it_has_been_set_b(self): self.new_menu.set_sub_menu_options("b") self.assertEqual("Back", self.new_menu.get_sub_menu_options()) def test_sub_menu_Options_should_not_continue_to_alphabetic_option(self): self.new_menu.set_sub_menu_options("f") self.assertEqual("choose another option", self.new_menu.get_sub_menu_options()) """ Sub Menu Algorithm""" def test_sub_menu_Algorithm_should_be_Backtrack_while_it_has_been_set_k(self): self.new_menu.set_sub_menu_algorithm("k") self.assertEqual("Backtrack", self.new_menu.get_sub_menu_algorithm()) def test_sub_menu_Algorithm_should_be_Peter_while_it_has_been_set_n(self): self.new_menu.set_sub_menu_algorithm("n") self.assertEqual("Peter Norwick", self.new_menu.get_sub_menu_algorithm()) def test_sub_menu_Algorithm_should_be_Recursive_out_put_while_it_has_been_set_i(self): self.new_menu.set_sub_menu_algorithm("i") self.assertEqual("Recursive", self.new_menu.get_sub_menu_algorithm()) def test_sub_menu_Algorithm_should_be_Back_while_it_has_been_set_b(self): self.new_menu.set_sub_menu_algorithm("b") self.assertEqual("Back", self.new_menu.get_sub_menu_algorithm()) def test_sub_menu_Algorithm_should_not_continue_to_different_option(self): self.new_menu.set_sub_menu_algorithm("f") self.assertEqual("choose another option", self.new_menu.get_sub_menu_algorithm()) """ Sub Menu Difficulty """ def test_sub_menu_difficulty_should_be_Easy_while_it_has_been_set_e(self): self.new_menu.set_sub_menu_difficulty("e") self.assertEqual("Easy", self.new_menu.get_sub_menu_difficulty()) def test_sub_menu_difficulty_should_be_Medium_while_it_has_been_set_m(self): self.new_menu.set_sub_menu_difficulty("m") self.assertEqual("Medium", self.new_menu.get_sub_menu_difficulty()) def test_sub_menu_difficulty_should_be_Hard_while_it_has_been_set_a(self): self.new_menu.set_sub_menu_difficulty("a") self.assertEqual("Hard", self.new_menu.get_sub_menu_difficulty()) def test_sub_menu_difficulty_should_be_Back_while_it_has_been_set_b(self): self.new_menu.set_sub_menu_difficulty("b") self.assertEqual("Back", self.new_menu.get_sub_menu_difficulty()) def test_sub_menu_difficulty_should_not_continue_to_alphabetic_option(self): self.new_menu.set_sub_menu_difficulty("f") self.assertEqual("choose another option", self.new_menu.get_sub_menu_difficulty()) """ Sub Menu Difficulty Edith """ def test_sub_menu_difficulty_edith_should_be_Easy_while_it_has_been_set_nw(self): self.new_menu.set_sub_menu_difficulty_edith("nw") self.assertEqual("New", self.new_menu.get_sub_menu_difficulty_edith()) def test_sub_menu_difficulty_edith_should_be_Medium_while_it_has_been_set_ch(self): self.new_menu.set_sub_menu_difficulty_edith("ch") self.assertEqual("Change Values", self.new_menu.get_sub_menu_difficulty_edith()) def test_sub_menu_difficulty_edith_should_be_Back_while_it_has_been_set_b(self): self.new_menu.set_sub_menu_difficulty_edith("b") self.assertEqual("Back", self.new_menu.get_sub_menu_difficulty_edith()) def test_sub_menu_difficulty_edith_should_not_continue_to_alphabetic_option(self): self.new_menu.set_sub_menu_difficulty_edith("f") self.assertEqual("choose another option", self.new_menu.get_sub_menu_difficulty_edith())
def __init__(self): self.menus = Menus()
from player import Player from menus import Menus from game import Game from utils import log if __name__ in '__main__': log('[[INFO] main] Welcome to "The Luckiest Penny", version 0.1.1', 1) #run main menu levelOver = False menu = Menus() game = Game() log('[[INFO] main] Init main menu', 1) menu.main_menu() #start by creating our character. class_choice = menu.class_menu() #If we're here, we'll create an instance of our player class character_class = Player() character_class.create_character(class_choice[1], class_choice[0]) print(character_class.get_current_player()) #some story intro of some kind will go here. #We gotta introduce what we're doing and why. #Now we're past the intro. #"You enter the valley, not sure what will come next, etc. etc."
def __init__(self, resolution): pygame.init() self.settings = {} self.settings['sound_system'] = True self.settings['stage_music'] = True # TODO: implement this self.settings['music'] = True self.settings['music_vol'] = .4 self.settings['sounds'] = True # TODO: implement this # pygame.mixer.init(frequency=44100, size=-16, channels=2, # buffer=4096) if self.settings['sound_system']: print("initializing sound with volume " + str(self.settings['music_vol'])) pygame.mixer.init(frequency=44100, channels=2) pygame.mixer.music.set_volume(self.settings['music_vol']) else: self.settings['sounds'] = False self.settings['music'] = False if self.settings['music']: pygame.mixer.music.set_endevent(pygame.USEREVENT) else: self.settings['stage_music'] = False print("effective settings: " + str(self.settings)) self.music_name = None self.queued_music_name = None self.prev_offset = 0.0 self.prev_song_len = 0.0 self.music_loaded = None self.clock = pygame.time.Clock() self.music_count = -1 data_sub_dir = "data" ced = os.path.dirname(__file__) # current executable directory self.DATA_PATH = os.path.join(ced, data_sub_dir) self.screen = pygame.display.set_mode(resolution) pygame.display.set_caption("Pylaga " + __version__) self.world = World(self, self.screen) logo_image = self.load_file("screen-intro.png") cursor_image = self.load_file('pship0.png') about_string = ''' PYLAGA Code License: GPL 3.0 Media License: CC-BY-SA 4.0 International Original Creator: Derek Mcdonald FreeSansBold.ttf: Copyleft 2002, 2003, 2005, 2008, 2009, 2010 Free Software Foundation ([GPL License] (https://www.gnu.org/licenses/gpl-3.0.en.html)) PYLAGA fork [python 2] RJ Marsan (gmail RJMarsan) PYLAGA [Python 3] new graphics new enemies removed globalvars sound fx [own work] particles poikilos CRYSTAL-Regular.ttf: Felipe Munoz (CC-BY SA 4.0 International) Music MixMystery ''' help_string = ''' MOVE: move mouse FIRE: click/tap MENU: Escape ("Esc") key MENU controls: click/tap choice, or use arrows & enter key (Esc or q key to resume/retry) EXIT: In the menu, click EXIT (or select EXIT with arrows then press Enter key) ''' pages_dict = { 'ABOUT': { 'scroll_text': about_string }, 'HELP': { 'scroll_text': help_string } } # pages_dict['ABOUT']['scroll_text'] = about_string # pages_dict['HELP'] = {} # pages_dict['HELP']['scroll_text'] = help_string self.menus = Menus(self.world.statcounter, self, logo_image, cursor_image, pages_dict) init_menu_strings = ["PLAY", "ABOUT", "HELP", "EXIT"] self.menus.show_dialog(init_menu_strings) print("starting world...") self.world.start(self.menus) tries = 1 open_page = None caption = None retry_menu_strings = [ "RETRY", "ABOUT", "HELP", "EXIT", "Score: %s" % self.world.statcounter.get_val() ] if self.world.won: open_page = 'ABOUT' caption = self.world.won_msg # retry_menu_strings.insert(0, self.world.won_msg) else: caption = 'GAME OVER' # retry_menu_strings.insert(0, 'GAME OVER') while ((not self.menus.get_bool('exit')) and (self.menus.show_dialog(retry_menu_strings, cursor_spin=-1.0, open_page=open_page, caption=caption))): print("starting world (tries: " + str(tries) + ")...") self.world.start(self.menus) open_page = None retry_menu_strings = [ "RETRY", "ABOUT", "HELP", "EXIT", "Score: %s" % self.world.statcounter.get_val() ] if self.world.won: open_page = 'ABOUT' caption = self.world.won_msg # retry_menu_strings.insert(0, self.world.won_msg) else: caption = 'GAME OVER' # retry_menu_strings.insert(0, 'GAME OVER') tries += 1 self.world.on_exit()
class SudokuPlay: def __init__(self): self.new_tool = Tools() self.matrix_play = [] self.row = 0 self.column = 0 self.value = 0 self.new_menu = Menus() self.return_game = "" self.boards = integrator.integrator() def print_sub_menu_play(self): self.new_menu.print_sub_menu_play() def start_end_menus(self, matrix_play, menu): os.system("cls") self.new_tool.display_board(matrix_play) if menu == "play": self.print_sub_menu_play() return raw_input("Make your play:") elif menu == "read": self.new_menu.print_sub_menu_read() return raw_input("Choose your option:") elif menu == "save": self.new_menu.print_sub_menu_save() return raw_input("Choose your option:") def verify_read_key_str(self, read_key, pos): ABC = self.new_tool.get_ABC(9, 9) list_tmp = list(read_key) try: if ABC[0].index(list_tmp[pos]) >= 0: return True else: return False except: return False def get_parse_str(self, read_key, pos): list_tmp = list(read_key) return list_tmp[pos] def verify_read_key_int(self, read_key, pos): list_tmp = list(read_key) try: if len(list_tmp) >= 4: return False else: if int(list_tmp[2]) in range(0, 10): self.value = int(list_tmp[2]) return True else: return False except: return False def set_possiton(self, read_key): list_tmp = list(read_key) self.row = ord(list_tmp[0]) - 65 self.column = ord(list_tmp[1]) - 65 def verify_busy(self, matrix, rows, columns): if matrix[rows][columns] == 0: return False else: return True def change_value_in_matrix(self, matrix, row, column, value): matrix[row][column] = str(value) return matrix def play_the_game(self, puzzle): self.boards.load_sudoku() puzzle = self.boards.get_original_sudoku() self.matrix_play = self.new_tool.convert_str_to_matrix(puzzle, 9, 9) read_key = self.start_end_menus(self.matrix_play, "play") while read_key != "Q": parse_row = self.verify_read_key_str(read_key, 0) parse_column = self.verify_read_key_str(read_key, 1) parse_value = self.verify_read_key_int(read_key, 2) if parse_row and parse_column and parse_value: self.set_possiton(read_key) if not self.verify_busy(self.matrix_play, self.row, self.column): self.matrix_play = self.change_value_in_matrix(self.matrix_play, self.row, self.column, self.value) self.return_game = self.new_tool.convert_matrix_to_str(self.matrix_play) else: raw_input("That point is busy, make another play") elif read_key == "g": self.boards.load_sudoku() puzzle = self.boards.get_original_sudoku() self.matrix_play = self.new_tool.convert_str_to_matrix(puzzle, 9, 9) elif read_key == "r": self.print_sub_menu_read() elif read_key == "h": currently_game = self.new_tool.convert_matrix_to_str(self.matrix_play) currently_game = self.boards.get_hint(currently_game) self.matrix_play = self.new_tool.convert_str_to_matrix(currently_game, 9, 9) elif read_key == "v": puzzle = self.boards.get_solved_puzzle() print puzzle self.matrix_play = self.new_tool.convert_str_to_matrix(puzzle, 9, 9) elif read_key == "t": puzzle = self.boards.get_original_sudoku() self.matrix_play = self.new_tool.convert_str_to_matrix(puzzle, 9, 9) elif read_key == "s": self.print_sub_menu_save() elif read_key == "q": if raw_input("do you really want to quit(y/n)? ") == "y": break else: raw_input("Make another play. Review the upper case and value") read_key = self.start_end_menus(self.matrix_play, "play") def print_sub_menu_read(self): read_key = self.start_end_menus(self.matrix_play, "read") while read_key != "B": if read_key == "t": path_file = self.get_path_from_console("txt") puzzle = self.boards.read_txt_file(path_file) self.matrix_play = self.new_tool.convert_str_to_matrix(puzzle, 9, 9) elif read_key == "v": path_file = self.get_path_from_console("cvs") puzzle = self.boards.read_cvs_file(path_file) self.matrix_play = self.new_tool.convert_str_to_matrix(puzzle, 9, 9) elif read_key == "c": # print "you press key %s" %(read_key) self.load_from_console() elif read_key == "b": break else: read_key = raw_input("choose another option.") read_key = self.start_end_menus(self.matrix_play, "read") def print_sub_menu_save(self): read_key = self.start_end_menus(self.matrix_play, "save") currently_game = self.boards.get_original_sudoku() while read_key != "B": if read_key == "t": self.boards.save_txt(currently_game) elif read_key == "c": self.boards.save_cvs(currently_game) elif read_key == "h": self.boards.save_html(currently_game) elif read_key == "d": self.boards.save_default() elif read_key == "b": break else: read_key = raw_input("choose another option.") read_key = self.start_end_menus(self.matrix_play, "save") def verify_numbers(self, numbers_string): pass def load_from_console(self): puzzle = raw_input("Introduce the game in a single string:") if len(puzzle) == 81: self.matrix_play = self.new_tool.convert_str_to_matrix(puzzle, 9, 9) else: raw_input("wrong input, try it again") def get_path_from_console(self, type_input): path_file = raw_input("Introduce the path of the game(" + type_input + "):") return path_file
from menus import Menus from carro import MyCar car = MyCar() menu = Menus() menu.mostrar_menu() if menu.opcao == 1: gas = int(input('Informe o valor que deseja abastecer: ')) if (car.abastecer(gas)): print(''' Veiculo abastecido! ============================ █ Gasolina atual: %sL █ ============================''' % car.infoGasolina()) menu.mostrar_menu() else: print( 'Não foi possivel abastecer, quantidade de gasolina superior a capacidade do tanque.' ) menu.validar_opcao(1) elif menu.opcao == 2: gas = int(input('Informe a distancia a ser percorrida em KM: ')) if (car.abastecer()): print('Você chegou ao seu destino!') menu.mostrar_menu() else: print('Você não conseguiu chegar ao seu destino e ficou sem carro!') else:
def setUpClass(cls): cls.driver = Chrome(config.CHROMEDRIVER) # chromedriver的文件地址 url = config.HOMEPAGE_URL cls.session = Homepage(driver=cls.driver, url=url) cls.session.fullscreen() cls.m = Menus()
from menus import Menus from funcoes import Funcoes menu = Menus() funcao = Funcoes() def verificaMenus(): if menu.opcao == 1: funcao.calcular() if funcao.aplcicacao() == True: getMenu() elif menu.opcao == 2: funcao.par_impar() if funcao.aplcicacao() == True: getMenu() else: print('Bye!') exit(0) def getMenu(): menu.mostrar_menu() verificaMenus() if menu.opcao == 0: getMenu()