client.py 3.6 KB

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