client.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. from getpass import getpass
  2. import websocket
  3. import _thread
  4. import json
  5. import time
  6. from cmd import Cmd
  7. class MyPrompt(Cmd):
  8. def __init__(self, ws):
  9. super(MyPrompt, self).__init__()
  10. self.ws = ws
  11. def do_build(self, args):
  12. """Starts the construction of a building."""
  13. send_json(self.ws, {
  14. 'type': "build",
  15. 'name': args,
  16. })
  17. def do_jobs(self, args):
  18. """List the current running jobs."""
  19. global player_data
  20. global server_config
  21. for job in player_data['jobs']:
  22. product = job['product']
  23. if product['type'] == "building":
  24. print("Upgrading {} to level {}.".format(server_config['building'][product['name']]['name'], player_data['buildings'][product['name']] + 1))
  25. elif product['type'] == "unit":
  26. print("Training level {} {}.".format(product['level'], server_config['unit'][product['name']]['name']))
  27. else:
  28. print("Unknown job: " + job)
  29. bar_width = 20
  30. remaining = job['finish_time'] - time.time()
  31. progress = remaining / job['product']['time']
  32. num_bars = bar_width - int(progress * bar_width)
  33. print("[" + num_bars * "#" + (bar_width - num_bars) * " " + "]" + str(int(remaining)) + "s remaining")
  34. print("-" * (bar_width + 10))
  35. if not player_data['jobs']:
  36. print("No jobs are currently running.")
  37. def do_resources(self, args):
  38. """List available resources."""
  39. global player_data
  40. for resource, amount in player_data['resources'].items():
  41. print(resource.title() + ": " + str(int(amount)))
  42. def do_buildings(self, args):
  43. """List the buildings of the city and their levels."""
  44. global player_data
  45. global server_config
  46. any_building = False
  47. for name, level in player_data['buildings'].items():
  48. if level > 0:
  49. any_building = True
  50. print("{}, level {}".format(server_config['building'][name]['name'], level))
  51. if not any_building:
  52. print("There are no buildings in this city.")
  53. def do_exit(self, args):
  54. """Exits the program."""
  55. print("Exiting.")
  56. raise SystemExit
  57. def default(self, line):
  58. print("Unknown command: " + line)
  59. def emptyline(self):
  60. pass
  61. def send_json(ws, message):
  62. ws.send(json.dumps(message))
  63. def on_message(ws, message):
  64. global player_data
  65. global server_config
  66. data = json.loads(message)
  67. if 'username' in data:
  68. player_data = data
  69. elif 'server' in data:
  70. server_config = data
  71. def on_error(ws, error):
  72. print(error)
  73. def on_close(ws):
  74. print("### closed ###")
  75. def on_open(username, password, register=False):
  76. def run(ws):
  77. send_json(ws, {
  78. 'type': "register" if register else "login",
  79. 'username': username,
  80. 'password': password,
  81. })
  82. return run
  83. def main():
  84. ws = websocket.WebSocketApp("ws://localhost:6060",
  85. on_message = on_message,
  86. on_error = on_error,
  87. on_close = on_close)
  88. option = 0
  89. while option not in (1, 2):
  90. print("1. Login")
  91. print("2. Register")
  92. print("> ", end="", flush=True)
  93. option = int(input())
  94. print("Username: ", end="", flush=True)
  95. username = input()
  96. password = getpass()
  97. ws.on_open = on_open(username, password, option == 2)
  98. def run(*args):
  99. ws.run_forever()
  100. _thread.start_new_thread(run, ())
  101. prompt = MyPrompt(ws)
  102. prompt.prompt = '> '
  103. prompt.cmdloop('Starting prompt...')
  104. if __name__ == "__main__":
  105. main()