/server/main.py

https://github.com/nagn/PyGG2-old
Python | 97 lines | 62 code | 23 blank | 12 comment | 9 complexity | 1e6d069e110d4d4c9b7576082da9a079 MD5 | raw file
  1. #!/usr/bin/env python
  2. from __future__ import division, print_function
  3. # add our main folder as include dir
  4. import sys, uuid
  5. sys.path.append("../")
  6. import precision_timer, time
  7. import engine.game
  8. import constants
  9. import networker
  10. import lobby
  11. import json
  12. # DEBUG ONLY
  13. import cProfile
  14. import pstats
  15. import os
  16. # the main function
  17. class Server(object):
  18. def __init__(self):
  19. self.load_config()
  20. self.port = self.config.setdefault('port', 8190)
  21. self.name = str(self.config.setdefault('name', 'Development Server'))
  22. self.password = str(self.config.setdefault('password', ''))
  23. self.ID = uuid.uuid4()
  24. # create game engine object
  25. self.game = engine.game.Game()
  26. self.game.servername = self.name
  27. self.game.isserver = True
  28. # create packet handler
  29. self.networker = networker.Networker(self.port)
  30. # create lobby announcer
  31. self.lobbyannouncer = lobby.Lobby()
  32. # time tracking
  33. self.clock = precision_timer.Clock()
  34. print("Hosting " + str(self.name) + " on port " + str(self.port) + " with password " + "\"" + str(self.password) + "\"")
  35. self.save_config()
  36. def run(self):
  37. # game loop
  38. while True:
  39. try:
  40. # update the game and render
  41. frametime = self.clock.tick()
  42. frametime = min(0.25, frametime) # a limit of 0.25 seconds to prevent complete breakdown
  43. self.networker.recieve(self, self.game)
  44. self.game.update(self.networker, frametime)
  45. self.networker.update(self, self.game, frametime)
  46. self.lobbyannouncer.update(self, frametime)
  47. if frametime < constants.SERVER_MAX_FPS:
  48. time.sleep(constants.SERVER_MAX_FPS - frametime)
  49. except KeyboardInterrupt:
  50. self.destroy()
  51. sys.exit()
  52. def load_config(self):
  53. if os.path.exists('server_cfg.json'):
  54. with open('server_cfg.json', 'r') as fp:
  55. self.config = json.load(fp)
  56. else:
  57. self.config = {}
  58. def save_config(self):
  59. with open('server_cfg.json', 'w') as fp:
  60. json.dump(self.config, fp, indent=4)
  61. def destroy(self):
  62. self.lobbyannouncer.destroy(self)
  63. def profileGG2():
  64. cProfile.run("Server().run()", "game_profile")
  65. p = pstats.Stats("game_profile", stream=open("profile.txt", "w"))
  66. p.sort_stats("cumulative")
  67. p.print_stats(30)
  68. os.remove("game_profile")
  69. def GG2main():
  70. Server().run()
  71. if __name__ == "__main__":
  72. # when profiling:
  73. profileGG2()
  74. # GG2main()