#!/usr/bin/python3 # ==================================================================== # my game # Note: json object contains the game data # ==================================================================== import json import time import platform import os import sys game_path = 'my_simple_game.json' # ------------------------------------------------------------------- # ---- clear the terminal screen (window) # ------------------------------------------------------------------- def clear_screen(): if platform.system() == 'Linux': os.system('clear') elif platform.system() == 'Windows': os.system('clear') else: os.system('cls') # -------------------------------------------------------------------- # ---- ask the user to select a direction # -------------------------------------------------------------------- def select_direction(d_lst): d_len = len(d_lst) print() print('You can go in the following directions: ',end='') for idx in range(d_len): if idx == 0: print(d_lst[idx],end='') else: print(', ' + d_lst[idx],end='') print() idx = -1 while True: print() direction = input('Select a direction: ').strip().lower() if not direction: # empty string return -1 for idx in range(d_len): if direction == d_lst[idx]: return idx print() print('bad direction - try again') # -------------------------------------------------------------------- # ---- move around the maze # -------------------------------------------------------------------- def traverse(game): # ---- set the starting node node_name = game['start'] node = game['nodes'][game['start']] while True: # ---- display a description of the node print() print(node['description']) # ---- get a list of directions and the associated node connections = node['connections'] c_len = len(connections) d_lst = [] # node direction list n_lst = [] # next node list for idx in range(c_len): d_lst.append(connections[idx][0]) n_lst.append(connections[idx][1]) # ---- ask the user to select a direction d_idx = select_direction(d_lst) if d_idx < 0: return False # ---- test for game end node if n_lst[d_idx] == game['end']: return True # ---- go to the next node next_node_name = n_lst[d_idx] clear_screen() node = game['nodes'][next_node_name] ##print() ##print(f'moving to {next_node_name}') # ==================================================================== # ---- main # ==================================================================== clear_screen() start_game = time.strftime('%Y-%m-%d %H:%M:%S') game = {} with open(game_path,"r") as gp: game = json.load(gp) gp.close() print() print(f'Game title : {game["title"]}') print(f'game author : {game["author"]}') print(f'Game created: {game["date"]}') print(game['start_message']) if traverse(game): print() print(game['end_message']) else: print() print('Early exit from the game') print()