client.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. def do_resources(self, args):
  35. """List available resources."""
  36. global player_data
  37. for resource, amount in player_data['resources'].items():
  38. print(resource.title() + ": " + str(amount))
  39. def do_buildings(self, args):
  40. """List the buildings of the city and their levels."""
  41. global player_data
  42. for name, level in player_data['buildings'].items():
  43. if level > 0:
  44. print("{}, level {}".format(name.title(), level))
  45. def do_exit(self, args):
  46. """Exits the program."""
  47. print("Exiting.")
  48. raise SystemExit
  49. def default(self, line):
  50. print("Unknown command: " + line)
  51. def emptyline(self):
  52. pass
  53. def send_json(ws, message):
  54. ws.send(json.dumps(message))
  55. def on_message(ws, message):
  56. global player_data
  57. data = json.loads(message)
  58. if 'username' in data:
  59. player_data = data
  60. def on_error(ws, error):
  61. print(error)
  62. def on_close(ws):
  63. print("### closed ###")
  64. def on_open(username, password, register=False):
  65. def run(ws):
  66. send_json(ws, {
  67. 'type': "register" if register else "login",
  68. 'username': username,
  69. 'password': password,
  70. })
  71. return run
  72. def main():
  73. ws = websocket.WebSocketApp("ws://localhost:6060",
  74. on_message = on_message,
  75. on_error = on_error,
  76. on_close = on_close)
  77. option = 0
  78. while option not in (1, 2):
  79. print("1. Login")
  80. print("2. Register")
  81. print("> ", end="", flush=True)
  82. option = int(input())
  83. print("Username: ", end="", flush=True)
  84. username = input()
  85. password = getpass()
  86. ws.on_open = on_open(username, password, option == 2)
  87. def run(*args):
  88. ws.run_forever()
  89. _thread.start_new_thread(run, ())
  90. prompt = MyPrompt(ws)
  91. prompt.prompt = '> '
  92. prompt.cmdloop('Starting prompt...')
  93. if __name__ == "__main__":
  94. main()