Created
          February 11, 2019 12:47 
        
      - 
      
- 
        Save rdeioris/78da7d6828f74fe6348b351429fa0a4b to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import socket | |
| import struct | |
| import time | |
| JOIN = 0 | |
| PLAY = 1 | |
| class EvensAndOddsServer: | |
| def __init__(self, address, port): | |
| self.address = address | |
| self.port = port | |
| self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
| self.socket.bind((self.address, self.port)) | |
| self.in_game = False | |
| self.players = {} | |
| def tick(self): | |
| self.packet, self.sender = self.socket.recvfrom(64) | |
| if len(self.packet) <= 0: | |
| return | |
| command, value = struct.unpack('=BB', self.packet) | |
| if command == JOIN: | |
| self.join(value) | |
| elif command == PLAY: | |
| self.play(value) | |
| if not self.in_game: | |
| if len(self.players) == 2: | |
| self.in_game = True | |
| total = 0 | |
| if self.in_game: | |
| for move in self.players.values(): | |
| if move is None: | |
| return | |
| total += move | |
| else: | |
| return | |
| # if i am here, check victory | |
| if total % 2 == 0: | |
| print('EVEN WINS') | |
| else: | |
| print('ODD WINS') | |
| self.players = {} | |
| self.in_game = False | |
| def join(self, value): | |
| if self.in_game: | |
| return | |
| if len(self.players) == 2: | |
| return | |
| print('player {} joined'.format(self.sender)) | |
| self.players[self.sender] = None | |
| def play(self, value): | |
| if not self.in_game: | |
| return | |
| if not self.sender in self.players: | |
| return | |
| print('player {} moved: {}'.format(self.sender, value)) | |
| self.players[self.sender] = value | |
| def run(self): | |
| print('server is running') | |
| while True: | |
| self.tick() | |
| game = EvensAndOddsServer('192.168.10.1', 9999) | |
| game.run() | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment