client.py 4.4 KB

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