Ejemplo n.º 1
0
def is_valid_shot(shot, shot_list):
    """Define logic to ensure the player doesn't shoot the same spot twice."""
    if shot not in shot_list:
        return True
    else:
        functions.clear_screen()
        return False
Ejemplo n.º 2
0
 def endgame(self, winner):
     input("\n%sPress Enter to continue..." % sets["space"])
     clear_screen()
     best_player = {
         "hits": {
             "score": 0,
             "player": None
         },
         "accuracy": {
             "score": 0,
             "player": None
         },
         "sinks": {
             "score": 0,
             "player": None
         },
         "eliminations": {
             "score": 0,
             "player": None
         }
     }
     for player in self.players:
         player.score.evaluate_percentages()
         for key, value in best_player.items():
             if player.score.score[key] > best_player[key]["score"]:
                 best_player[key]["score"] = player.score.score[key]
                 best_player[key]["player"] = player
     self.game_statistics(best_player, winner)
     input("%sPress Enter to continue..." % sets["space"])
     if sets["scores"]:
         for player in self.players:
             print(player.score)
         input("%sPress Enter to continue..." % sets["space"])
     menu.menu()
Ejemplo n.º 3
0
def fight():
    option = False
    while not option:
        clear_screen()
        print("Options:")
        print("  1: Easy AI")
        print("  2: Medium AI")
        print("  3: Hard AI")
        print("  4: Extreme AI")
        print("  5: Custom AI")
        print("  6: Back")
        option = option_selector(6)
        if option != 6:
            if option == 5:
                check = False
                while not check:
                    try:
                        level = input("Enemy Level: ")
                        if level.isdigit():
                            level = int(level)
                            check = True
                        else:
                            level = None
                            check = False
                    except Exception as e:
                        pass
                return f'menu_request:battle {level}'
            else:
                return f'menu_request:battle {option}'
        else:
            return "menu_request:main_menu"
Ejemplo n.º 4
0
	def info(self):

		while True:
			functions.clear_screen()
			functions.pyramid_logo()
			functions.greeting()
			selection_menu = functions.list_items(self.description,self.menu)
			
			answer = functions.prompt()
			
			if answer in selection_menu:
				selection_menu.get(answer).info()
			#check answer against the exit tuple and runs a shutdown sequence if true.
			if answer in functions.exit_tuple:
				functions.countdown("\nSHUTTING DOWN APPLICATION.\n","",4)
				sys.exit("\nUSER TERMINATED APPLICATION.\n")
			#checks answer for reboot sequence. 
			if answer == "reboot":
				functions.countdown("USER INITIALIZED REBOOT","REBOOTING",4)
				functions.greeting(.09)
			if answer == "return":
				break
			
			else:
				print("response invalid.")
				continue
Ejemplo n.º 5
0
    def __init__(self):
        """Class initialization method.

        Set up Battleship players and game boards.
        """
        # Clear screen on game initialization
        functions.clear_screen()

        # Instatiate players
        self.player_one = Player()
        self.player_two = Player("Player Two")

        # Prompt players to take turns setting up their boards
        self.player_one.set_up_board(self.player_two.name)
        self.player_two.set_up_board(self.player_one.name)

        # Clear the screen and prepare the first player  \
        # to make targeting choices
        functions.clear_screen()
        play_game = input('\nWould you like to start Battleship? Y/n').lower()

        input('Please pass the board to {}, and look away.\n'
              'Press Enter to continue.'.format(self.player_one.name))

        if play_game != 'n':
            # Initiate the game loop
            self.play_battleship()
Ejemplo n.º 6
0
def are_valid_coordinates(coords, player_board, shots_board):
    """Check if ship coordinates are valid."""
    if len(coords) > 3:
        functions.clear_screen()
        if shots_board:
            shots_board.display()
        player_board.display()
        print('\n{} is not a valid entry. '
              'Please enter a column ({}-{}) and a row (1-{}), ex. "h4"'
              .format(coords,
                      constants.BOARD_HEADING[0],
                      constants.BOARD_HEADING[(constants.BOARD_SIZE - 1)],
                      constants.BOARD_SIZE))
        return False

    if len(coords) < 2 or coords == '':
        functions.clear_screen()
        if shots_board:
            shots_board.display()
        player_board.display()
        print('\nYou must enter at least one column (letter) '
              'and one row (number), ex. "b8"')
        return False
    else:
        column = coords[0]
        try:
            row = int(coords[1:])
        except ValueError:
            functions.clear_screen()
            row = coords[1:]
            if shots_board:
                shots_board.display()
            player_board.display()
            print('\n{} is not a valid row, valid rows are numbered 1-{}'
                  .format(row, constants.BOARD_SIZE))
            return False

    if column not in constants.VALID_LETTERS:
        functions.clear_screen()
        if shots_board:
            shots_board.display()
        player_board.display()
        print("\n{} is not a valid column valid lettered columns are {}"
              .format(column, constants.VALID_LETTERS))
        return False

    if row > constants.BOARD_SIZE:
        functions.clear_screen()
        if shots_board:
            shots_board.display()
        player_board.display()
        print('\n{} is not a valid row, valid rows are numbered 1-{}'
              .format(row, constants.BOARD_SIZE))
        return False

    return True
Ejemplo n.º 7
0
def is_valid_orientation(orientation, player_board):
    """Check for valid orientation input."""
    if orientation not in 'hv' or orientation == '':
        functions.clear_screen()
        player_board.display()
        print('\n{} is not a valid orientation,'
              ' please enter either "h" or "v"'.format(orientation))
        return False
    else:
        return True
Ejemplo n.º 8
0
def main():
    """ Main function """
    module = None
    try:

        # Clear
        clear_screen()

        # Logging debug | DEBUG INFO
        create_log(logging.DEBUG)

        # Start
        now = datetime.now()
        logging.info("Program start @ %s on %s",
                     now.strftime("%Y-%m-%d %H:%M:%S"), platform.system())

        # path
        data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 'data')
        if not os.path.exists(data_path):
            os.mkdir(data_path)
        config.main['data_path'] = data_path

        ftp_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                'ftp')
        if not os.path.exists(ftp_path):
            os.mkdir(ftp_path)
        config.main['ftp_path'] = ftp_path

        # create main module object
        logging.info("Creating main iono object...")
        module = IonoW1(config.main)

        # start main loop
        logging.info("Starting main thread")
        main_thread = threading.Thread(target=polling,
                                       daemon=True,
                                       args=[module, config.main])
        main_thread.start()

        # loop forever waiting for user ctrl+c to exit
        while True:
            time.sleep(0.1)

    except KeyboardInterrupt:
        pass
    except Exception as ex:
        logging.critical("An exception was encountered in main(): %s", str(ex))
    finally:
        if module:
            module.cleanup()
        logging.info("End")
Ejemplo n.º 9
0
def hit_or_miss(coordinates, board):
    """Check whether player shot is a hit or miss."""
    coordinates = coordinates.strip()

    column = constants.VALID_LETTERS.index(coordinates[0])
    row = int(coordinates[1:]) - 1

    if board[row][column] == '-' or board[row][column] == '|':
        functions.clear_screen()
        print('***********\n*** HIT ***\n***********')
        return True
    else:
        functions.clear_screen()
        print('************\n*** MISS ***\n************')
        return False
Ejemplo n.º 10
0
def program_loop():
    while True:
        menu_choice = functions.menu("Main Menu:", "Record a new task entry.",
                                     "Lookup previous task entries.",
                                     "Exit the program.")

        if int(menu_choice) == 1:
            new_task = task.Task()

        if int(menu_choice) == 2:
            reports_menu()

        if int(menu_choice) == 3:
            functions.clear_screen()
            break
Ejemplo n.º 11
0
	def print_overview(self,line_cap = 82):
		functions.clear_screen()
		functions.pyramid_logo()
		'''method to print dictionary containing overview information'''
		while True:
			functions.clear_screen()
			functions.pyramid_logo()
			print("=" * 82)
			print(self.name.title() + " Overview: ")
			print("=" * 82)			
			for k, v in self.overview.items():
				print(k + v)
			
			answer = input("\npress enter to return\n")
			return answer 
Ejemplo n.º 12
0
	def info(self):
		while True:
			"""method to print info about the region."""
			functions.clear_screen()
			functions.pyramid_logo()
			#prints information from object. 
			print(
				"=" * 80
				+"\nGalactic power: \n"
				+ self.title
				+ "\n" + "=" * 80
				+"\n\n SYNOPSIS: \n\n"
				+ self.synopsis 
				+ "\n\n HISTORY: \n\n"
				+ self.history 
				+"\n\n"
				)
			if self.sectors:
				selection_menu = functions.list_items(str(self.name + " sectors"),self.sectors.items())
				answer = input("Select Index number for more information: ")
				if answer in selection_menu:
					selection_menu.get(answer).info()
					
				elif answer in functions.exit_tuple:
					functions.countdown("\nSHUTTING DOWN APPLICATION.\n","",4)
					sys.exit("\nUSER TERMINATED APPLICATION.\n")
				#checks answer for reboot sequence. 
				
				elif answer == "reboot":
					functions.countdown("USER INITIALIZED REBOOT","REBOOTING",4)
					functions.greeting(.09)
				else:
					return answer
			else:
				print("=" * 80 + "\n" + "This OBJECT contain \"NULL VALUE\"" + "\n" + "=" * 80 + "\n")
				answer = input("enter RETURN to go back: ")
								
				if answer in functions.exit_tuple:
					functions.countdown("\nSHUTTING DOWN APPLICATION.\n","",4)
					sys.exit("\nUSER TERMINATED APPLICATION.\n")
				#checks answer for reboot sequence. 
				
				elif answer == "reboot":
					functions.countdown("USER INITIALIZED REBOOT","REBOOTING",4)
					functions.greeting(.09)
				else:
					return answer
Ejemplo n.º 13
0
def collision(player_board, ship_name, board, ship_length,
              coordinates, orientation):
    """Check if ship collides with another ship.

    Check for existence of a ship on board at passed in coordinates.
    If there is return an error message and a False value.
    """
    if ship_exists(ship_name, board, ship_length,
                   coordinates, orientation):
        functions.clear_screen()
        player_board.display()
        print('\nSorry, {} cannot be placed, '
              'you already have a ship there.'
              .format(ship_name))
        return True
    else:
        return False
Ejemplo n.º 14
0
	def print_more(self,line_cap = 82):

		'''method to print dictionary containing more information'''
		while True:
			index = 0
			functions.clear_screen()
			functions.pyramid_logo()
			print("=" * 82)
			print(self.name.title() + " resources")
			print("=" * 82)
			print("*" * 82)			
			for k, v in self.more.items():
				
				print(k + v)
				input("\nENTER>>\n")
					
			answer = input("\npress enter to return\n")
			return answer
Ejemplo n.º 15
0
def menu():
    clear_screen()
    print("\n\n%s" % ((offset() + 5) * '=' * 2))
    print("%s %sBattleship%s %s" % ((offset() - 1) * '=',
                                    Back.BLUE,
                                    Style.RESET_ALL,
                                    (offset() - 1) * '='))
    print("%s\n" % ((offset() + 5) * '=' * 2))

    print("New Game (g)")
    print("Options (o)")
    print("Exit/Quit (e/q)\n")

    answer = input("What's your choice? ").lower()
    print()

    if answer in ("g",
                  "game",
                  "new game",
                  "new_game",
                  "newgame"):

        global game
        game = NewGame()
        game.start()
        return
    elif answer in ("a",
                    "o",
                    "ao",
                    "advanced",
                    "options",
                    "advanced options"):
        options()
    elif answer in ("e",
                    "exit",
                    "q",
                    "quit"):
        print("Exit game\n")
        exit()
    else:
        print("Enter a valid answer!")
        menu()
        return
Ejemplo n.º 16
0
def store(player):
    finished = False
    while not finished:
        clear_screen()
        print("  1: Abilities")
        print("  2: Back")
        option = option_selector(2)
        if option == 1:
            check = False
            while not check:
                clear_screen()
                print(f"Player XP: {player.xp}")
                print("-"*10)
                print(f"Max hitpoints: {player.max_hp}")
                print(f"Attack Damage: {player.attack_damage}")
                print(f"Defensive ability: {player.defense_ablilty}")
                print("-"*10)
                print("Options:")
                print("  1: Increase max hitpoints by 10 (10 XP)")
                print("  2: Increase attack damage by 4 (10 XP)")
                print("  3: Increase defensive ability by 1 (2 XP)")
                print("  4: Back")
                option = option_selector(4)
                if option == 1:
                    if player.xp >= 10:
                        player.max_hp += 10
                        player.current_hp = player.max_hp
                        player.xp -= 10
                elif option == 2:
                    if player.xp >= 10:
                        player.attack_damage += 4
                        player.xp -= 10
                elif option == 3:
                    if player.xp >= 2:
                        player.defense_ablilty += 1
                        player.xp -= 2
                elif option == 4:
                    check = True
        elif option == 2:
            return ["menu_request:main_menu", player]
Ejemplo n.º 17
0
def main_menu():
    option = False
    while not option:
        clear_screen()
        print("Options:")
        print("  1: Fight!")
        print("  2: Store")
        print("  3: Save Character")
        print("  4: Load Character")
        print("  5: Exit")
        option = option_selector(5)
        if option == 1:
            option = "menu_request:fight"
        elif option == 2:
            option = "menu_request:store"
        elif option == 3:
            option = "action_request:save_character"
        elif option == 4:
            option = "action_request:load_character"
        elif option == 5:
            option = "action_request:exit_game"
    return option
Ejemplo n.º 18
0
def out_of_bounds(player_board, ship_length, coordinates, orientation):
    """Check if ship is outside of game board."""
    if orientation == 'v':
        if (ship_length + int(coordinates[1:]) - 1) > constants.BOARD_SIZE:
            functions.clear_screen()
            player_board.display()
            print('\nThat ship exceeds the board size.'
                  ' Please choose another location or orientation')
            return True
        else:
            return False

    if orientation == 'h':
        if (ship_length + constants.VALID_LETTERS.index(coordinates[0])) > \
                constants.BOARD_SIZE:
            functions.clear_screen()
            player_board.display()
            print('\nThat ship exceeds the board size.'
                  ' Please choose another location or orientation')
            return True
        else:
            return False
Ejemplo n.º 19
0
def reports_menu():
    while True:
        menu_search = functions.menu("Lookup previous task entries:",
                                     "Find by employee.", "Find by date.",
                                     "Find by search term.",
                                     "Find by date range.",
                                     "Return to main menu.")

        if int(menu_search) == 1:
            result = lookup.employee()

        if int(menu_search) == 2:
            result = lookup.date()

        if int(menu_search) == 3:
            result = lookup.term()

        if int(menu_search) == 4:
            result = lookup.date_range()

        if int(menu_search) == 5:
            functions.clear_screen()
            break
Ejemplo n.º 20
0
def battle(player, ai_level):
    clear_screen()
    print("Prepare for battle!")
    enemy = Enemy(ai_level)
    check = False
    player_is_blocking = False
    result = None
    while not check:
        clear_screen()
        print(f'You are fighting a level {ai_level} enemy, it\'s remaining health is {enemy.hp}, your remaining health is {player.current_hp}hp!\n')
        print('-'*40)
        print("Options:")
        print("  1: Attack!")
        print("  2: Block")
        print("  3: Run!")
        option = option_selector(3)
        if option == 1:
            otpt = enemy.calculate_damage(player.attack_damage)
            print(f'You did {otpt["damage"]} damage! Your enemy is now at {otpt["hp"]}hp!')
        elif option == 2:
            player_is_blocking = True
        elif option == 3:
            print("You run away.. coward.")
            check = True
            result = "run"
        print('-'*20)

        if enemy.hp <= 0:
            check = True
            player.coins += ai_level*100
            player.xp += ai_level*10 + random.randint(1,50)
            player.current_hp = player.max_hp
            result = "won"
        else:
            otpt = player.calculate_damage(enemy.attack_damage, player_is_blocking)

        if player.current_hp <= 0:
            check=True
            player.current_hp = player.max_hp
            result = "loss"

    clear_screen()
    if result == "won":
        print("You won the battle!")
        player.wins += 1
    elif result == "loss":
        print("You lost the battle..")
        player.losses += 1
    elif result == "run":
        print("You ran away from battle!")
        player.losses += 1
    input("Press enter to continue...")

    return ["menu_request:main_menu", player]
Ejemplo n.º 21
0
import feedparser
import functions as fn
import classes

program = classes.Program()
program.state = 'MAIN_MENU'

command = ''

while program.running:

    if command == 'Q' or command == 'q':
        fn.clear_screen()
        program.running = False
        break
    elif command == '1' and program.state == 'MAIN_MENU':
        command = ''
        program.state = 'USER_URL'
        fn.print_menu(program.state)
        program.feed = fn.user_url()


    if program.state == 'MAIN_MENU':
        command = ''
        fn.print_menu(program.state)
    elif program.state == 'USER_URL':
        fn.list_entries(program.feed)
        program.state = 'ENTRY_LIST'
    elif program.state == 'ENTRY_LIST':
        if command == 'b' or command == 'B':
            program.state = 'MAIN_MENU'
Ejemplo n.º 22
0
def main():
    """ Main function """
    module = None
    try:

        # config
        config = {
            'polling_time': 10,  # polling (seconds)
            'store_time': 60,  # store data (seconds)
            'data_path': None,  # data path
            'ftp_path': None,  # data path for ftp export
            'file_header': 'iono',  # data file header
        }

        # iono config
        config_iono = {
            'use_ai': True,  # analog input
            'use_io': True,  # digital io
            'use_ev': True,  # digital io events
            'use_1w': True,  # one wire input (temperature)
            'use_ro': True,  # relay outputs
            'use_oc': True,  # open collectors
            'use_ld': True,  # on board led
        }

        # Clear
        clear_screen()

        # Logging debug | DEBUG INFO
        create_log(logging.DEBUG)

        # Start
        now = datetime.now()
        logging.info("Program start @ %s on %s",
                     now.strftime("%Y-%m-%d %H:%M:%S"), platform.system())

        # path
        data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 'data')
        if not os.path.exists(data_path):
            os.mkdir(data_path)
        config['data_path'] = data_path

        ftp_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                'ftp')
        if not os.path.exists(ftp_path):
            os.mkdir(ftp_path)
        config['ftp_path'] = ftp_path

        # create main module object
        logging.info("Creating main iono object...")
        module = IonoWrapper(config, config_iono)

        # start main loop
        logging.info("Starting main thread")
        main_thread = threading.Thread(target=polling,
                                       daemon=True,
                                       args=[module, config])
        main_thread.start()

        # loop forever waiting for user ctrl+c to exit
        while True:
            time.sleep(0.1)

    except KeyboardInterrupt:
        pass
    except Exception as ex:
        logging.critical("An exception was encountered in main(): %s", str(ex))
    finally:
        module.cleanup()
        logging.info("End")
Ejemplo n.º 23
0
import functions as fc
import random

fc.clear_screen()

no_of_tries = 6
guess = False
letters_guessed = []
letters_failed = []
played_letters = []
tries = 0

# Create list of available words and pick a random word.
# For now this is stored in a .txt file. but can be improved in the future
try:
    words_file = open('words.txt', 'r')
except:
    print(
        "Word file not found. Please place words.txt with words in the root of the game."
    )
    exit()

words = [line.strip() for line in words_file]

if len(words) == 0:
    raise ValueError("No words to choose from")

word = list(random.choice(words).lower())

# Keep asking user for input until guess or excedeed number of tries
while tries < no_of_tries and not guess:
Ejemplo n.º 24
0
def options():
    clear_screen()
    global sets
    # Colors for boolean settings
    colors = {}
    for key, value in sets.items():
        if str(value) in ("True", "False"):
            if value:
                colors[key] = Fore.GREEN
            else:
                colors[key] = Fore.RED
    # Calculate valid ships
    sets["ships"] = 0
    decoys = ""
    for ship_type in types:
        if ship_type["ship_type"] != "Decoy" or not sets["decoy"]:
            sets["ships"] += ship_type["quantity"]
        if ship_type["ship_type"] == "Decoy":
            if sets["decoy"]:
                if ship_type["quantity"] == 1:
                    decoys = " and a decoy"
                elif ship_type["quantity"] > 1:
                    decoys = " and %d decoys" % ship_type["quantity"]
    print("\n\n%s %sOptions%s %s" % (offset() * '=',
                                     Back.BLUE,
                                     Style.RESET_ALL,
                                     (offset() + 1) * '='))

    print("\nThere are %d ships%s:" % (sets["ships"], decoys))
    for ship_type in types:
        if ship_type["quantity"] > 1:
            plural = "s"
        else:
            plural = ""
        if ship_type["quantity"] > 0:
            print("%s%s %s%s with size of %d" % (sets["space"],
                                                 ship_type["quantity"],
                                                 ship_type["ship_type"],
                                                 plural,
                                                 ship_type["size"]))
    print("\nChange Ships (s)")
    print("Board Size (b)          Current: (%d, %d)"
          % (sets["board"][0], sets["board"][1]))
    print("Number of Players (p)   Current: %d" % (sets["players"]))
    print("AI Players (a)          Current: %d" % (sets["ai"]))
    print("Salvo shots (ss)        Current: %d" % (sets["shots"]))
    print("AI Pause Time (t)       Current: %4.2fs" % (sets["timeout"]))
    print("AI Smart Guessing (sg)  Current: %s%s%s"
          % (colors["smart"], sets["smart"], Style.RESET_ALL))
    print("Ignore Decoys (ig)      Current: %s%s%s"
          % (colors["decoy"], sets["decoy"], Style.RESET_ALL))
    print("Cheat (c)               Current: %s%s%s"
          % (colors["cheat"], sets["cheat"], Style.RESET_ALL))
    print("Randomize Ships (r)     Current: %s%s%s"
          % (colors["randomize"], sets["randomize"], Style.RESET_ALL))
    print("Players Scores (sc)     Current: %s%s%s"
          % (colors["scores"], sets["scores"], Style.RESET_ALL))
    print("Restore Default (d)")
    print("Back to menu (m)")
    print()

    answer = input("What's your choice? ").lower()
    print()

    # Player choice
    if answer in ("g",
                  "game",
                  "new game",
                  "new_game",
                  "newgame"):

        global game
        game = NewGame()
        game.start()
        return
    elif answer in ("b",
                    "size",
                    "board size",
                    "board_size",
                    "boardsize"):
        sets["board"][0] = input_num("Choose the width of the board",
                                     inr["board"][0](sets["ships"]),
                                     inr["board"][1],
                                     "int")
        sets["board"][1] = input_num("Choose the height of the board",
                                     inr["board"][0](sets["ships"]),
                                     inr["board"][1],
                                     "int")
    elif answer in ("p",
                    "players",
                    "number of players",
                    "number_of_players",
                    "numberofplayers"):
        sets["players"] = input_num("Choose the number of players",
                                    inr["players"][0],
                                    inr["players"][1],
                                    "int")
        if sets["ai"] > sets["players"] - 1:
            sets["ai"] = sets["players"] - 1
            print("AI players reduced to %d." % (sets["ai"]))
    elif answer in ("c",
                    "cheat"):
        sets["cheat"] = not sets["cheat"]
        print("Cheat: %s" % (sets["cheat"]))
    elif answer in ("sg",
                    "smart",
                    "ai smart",
                    "smart guessing",
                    "ai smart guessing"):
        sets["smart"] = not sets["smart"]
        print("Smart Guessing: %s" % (sets["smart"]))
    elif answer in ("s",
                    "cs",
                    "ships",
                    "choose ships"):
        for ship in types:
            ship["quantity"] = input_num("Choose the quantity of %s(Size: %d)"
                                         % (ship["ship_type"], ship["size"]),
                                         inr[ship["ship_type"]][0],
                                         inr[ship["ship_type"]][1], "int")
            if ship["ship_type"] != "Decoy":
                sets["ships"] += ship["quantity"]
        board = int(floor(sets["ships"] * 1.15))
        sets["board"] = [board, board]
        print("\nThe board size has been adjusted to (%d, %d)" %
              (sets["board"][0], sets["board"][1]))
    elif answer in ("ig",
                    "decoy",
                    "ignore",
                    "ignore decoy"):
        sets["decoy"] = not sets["decoy"]
        print("Ignore Decoys: %s" % (sets["decoy"]))
    elif answer in ("e",
                    "exit",
                    "q",
                    "quit"):
        print("Exit game\n")
        exit()
    elif answer in ("d",
                    "restore",
                    "default",
                    "restore default",
                    "restore_default",
                    "restoredefault"):
        sets = dv.copy()
    elif answer in ("r",
                    "randomize",
                    "randomize ships",
                    "randomize_ships",
                    "randomizeships"):
        sets["randomize"] = not sets["randomize"]
        print("Randomize Ships: %s" % (sets["randomize"]))
    elif answer in ("sc",
                    "scores"):
        sets["scores"] = not sets["scores"]
        print("Players Scores: %s" % (sets["scores"]))
    elif answer in ("a",
                    "ai",
                    "ai players",
                    "ai_players",
                    "aiplayers"):
        sets["ai"] = input_num("Choose the number of AI players",
                               inr["ai"][0],
                               inr["ai"][1](sets["players"]),
                               "int")
    elif answer in ("ss",
                    "salvo",
                    "shots",
                    "salvo shots",
                    "salvo_shots"):
        sets["shots"] = input_num("Choose the number of shots during a Salvo",
                                  inr["shots"][0],
                                  inr["shots"][1],
                                  "int")
    elif answer in ("t",
                    "pause",
                    "time",
                    "pause time",
                    "pause_time",
                    "pausetime"):
        sets["timeout"] = input_num("Choose a pause time in"
                                    + " seconds for AI action",
                                    inr["timeout"][0],
                                    inr["timeout"][1],
                                    "float")
    elif answer in ("m",
                    "menu",
                    "return"):
        menu()
    else:
        print("Enter a valid answer!")
    sleep(sets["timeout"] * 2)
    options()
    return
Ejemplo n.º 25
0
	def info(self,line_cap = 82):
		"""method to print statistics on planet."""
		name = str(" Name: " + self.name)
		region = str(" Region: " + self.region + " ")
		s_hex = str(" System Hex: " + self.s_hex + " ")
		atmo = str(" Atmosphere: " + self.atmo + " ")
		temp = str(" Temperature: " + self.temp + " ")
		biosphere = str(" Biosphere: " + self.biosphere + " ")
		population = str(" Population: " + self.population + " ")
		tech_level = str(" Tech Level: " + self.tech_level + " ")
		title_bar = ("=" * line_cap)
		while True:
			functions.clear_screen()
			functions.pyramid_logo()
			#creates title bar
			print(title_bar)
			print(name + " " * (line_cap - (len(name) + len(region))) + region) 
			print(title_bar + "\n")
		
		
			#format information for atmo and system Hex.
		
			print(
				" " 
				+ "*" * (len(atmo) + 2) 
				+ " " * (line_cap - (len(atmo) + len(s_hex) + 3)) 
				+ "*" * (len(s_hex) + 2)
				)
			
			print(
				" *" 
				+ atmo
				+ "*" 
				+ " " * (line_cap - (len(atmo) + 3
				+ len(s_hex))) 
				+ "*" 
				+ s_hex
				+ "*"
				)
				
		
			print(
				" "
				+ "*" * (len(atmo) + 2)
				+ " " * (line_cap - (len(atmo) + len(s_hex) + 3))
				+ "*" * (len(s_hex) + 2)
				)
		
			print("\n")
		
			#formats Temperature and Biosphere information.
			
			print(" " + "*" * (len(temp) + 2)
			+ " " * (line_cap - (len(temp) + len(biosphere) + 3))
			+ "*" * (len(biosphere) + 2)
			)
		
			print(
				" *" 
				+ temp 
				+ "*" 
				+ " " * (line_cap - (len(temp) + 3 + len(biosphere))) 
				+ "*" 
				+ biosphere
				+ "*"
				)
			
			print(
				" "
				+ "*" * (len(temp) + 2)
				+ " " * (line_cap - (len(temp) + len(biosphere) + 3))
				+ "*" * (len(biosphere) + 2)
				)
					
			print("\n")	
		
			#format populaiton and Tech_level
			print(
				" " 
				+ "*" * (len(population) + 2) 
				+ " " * (line_cap - (len(population) + len(tech_level) + 3)) 
				+ "*" * (len(tech_level) + 2)
				)
		
			print(
				" *" 
				+ population
				+ "*" 
				+ " " * (line_cap - (len(population) + 3 + len(tech_level))) 
				+ "*" 
				+ tech_level
				+ "*"
				)
			
		
			print(
				" "
				+ "*" * (len(population) + 2)
				+ " " * (line_cap - (len(population) + len(tech_level) + 3))
				+ "*" * (len(tech_level) + 2)
				)
			
			print("\n") 
			
			print(
				"=" * line_cap 
				+ "\n" 
				+ "Enter Overview for more detailed information if available.\nEnter More for a list of available resources."
				+ "\n"
				+ "=" * line_cap
				)
			
			answer = functions.prompt("\n: ")
				
			#check answer against the exit tuple and runs a shutdown sequence if true.
			if answer in functions.exit_tuple:
				functions.countdown("\nSHUTTING DOWN APPLICATION.\n","",4)
				sys.exit("\nUSER TERMINATED APPLICATION.\n")
			#checks answer for reboot sequence. 
			if answer == "reboot":
				functions.countdown("USER INITIALIZED REBOOT","REBOOTING",4)
				functions.greeting(.09)
			if answer == "overview":
				self.print_overview()
			if answer == "more":
				self.print_more()
			if answer == "return":
				break
				
			else:
				print("response invalid.")
				continue
    
    

    
    
#end of system class
Ejemplo n.º 26
0
import menus
from entities import Player
from functions import clear_screen, save_character, load_character
import json

with open('config.json', 'r') as f:
    config = json.load(f)

clear_screen()
if config["DevMode"] == True:
    player = Player(max_hp=999,
                    current_hp=999,
                    coins=9999,
                    xp=9999,
                    attack_damage=200,
                    defense_ablilty=2000)
else:
    player = Player()
del config
menus.title()

# Start main loop
while True:
    instruction = menus.main_menu()
    while instruction != "main_menu":
        if instruction.startswith("menu_request:"):
            instruction = instruction[len("menu_request:"):len(instruction)]
            if instruction == "fight":
                instruction = menus.fight()
            elif instruction.startswith("battle"):
                instruction = instruction[len("battle "):len(instruction)]
Ejemplo n.º 27
0
def main():
    functions.clear_screen()

    rank = functions.open_rank()

    print(functions.get_info())
    opc_usr = int(input("[0 a 5] >>> "))

    if opc_usr == 1:
        # NOTE: listar os times em ordem alfabetica
        print("\n--- Ordem alfabetica:")

        sorted_rank = sorted(rank)

        functions.rank(0, len(rank), sorted_rank)

        print("---\n")
    elif opc_usr == 2:
        # NOTE: todas as 20 colocacoes
        print("\n--- 20 primeiros colocados:")

        functions.rank(0, 20, rank)

        print("---\n")
    elif opc_usr == 3:
        # NOTE: pesquisar por nome
        print("\n--- Pesquisar por nome:")

        print(
            "- Digite o nome (ou parte dele) do time a ser pesquisado [sem acentuaçao]:"
        )
        search = str(input("- >>> ")).upper().strip()

        teams_found = []

        for team in rank:
            if search in team:
                teams_found.append(team)

        if len(teams_found) > 0:
            for team in teams_found:
                index = rank.index(team)
                print(f"- {index+1:>2}°\t{rank[index]}")
        else:
            print("Este time não consta entre os 20 classificados..."
                  "Verifique se o nome foi digitado corretamente.")

        print("---\n")
    elif opc_usr == 4:
        # NOTE: apenas as 4 ultimas colocacoes
        print("\n--- 4 ultimas colocacoes:")

        lenght = len(rank)

        functions.rank(lenght - 4, lenght, rank)

        print("---\n")
    elif opc_usr == 5:
        # NOTE: apenas as 5 primeiras colocacoes
        print("\n--- 5 primeiras colocacoes:")

        functions.rank(0, 5, rank)

        print("---\n")
    elif opc_usr == 0:
        print("Saindo imediatamente...")
        exit()
    else:
        print("ERRO: opcao invalida, tente novamente")

    input("Para continuar digite ENTER: ")
    main()