client.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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(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. data = json.loads(message)
  64. if 'username' in data:
  65. player_data = data
  66. def on_error(ws, error):
  67. print(error)
  68. def on_close(ws):
  69. print("### closed ###")
  70. def on_open(username, password, register=False):
  71. def run(ws):
  72. send_json(ws, {
  73. 'type': "register" if register else "login",
  74. 'username': username,
  75. 'password': password,
  76. })
  77. return run
  78. def main():
  79. ws = websocket.WebSocketApp("ws://localhost:6060",
  80. on_message = on_message,
  81. on_error = on_error,
  82. on_close = on_close)
  83. option = 0
  84. while option not in (1, 2):
  85. print("1. Login")
  86. print("2. Register")
  87. print("> ", end="", flush=True)
  88. option = int(input())
  89. print("Username: ", end="", flush=True)
  90. username = input()
  91. password = getpass()
  92. ws.on_open = on_open(username, password, option == 2)
  93. def run(*args):
  94. ws.run_forever()
  95. _thread.start_new_thread(run, ())
  96. prompt = MyPrompt(ws)
  97. prompt.prompt = '> '
  98. prompt.cmdloop('Starting prompt...')
  99. if __name__ == "__main__":
  100. main()