client.py 2.9 KB

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