Skip to content

Commit

Permalink
disconneciton handling
Browse files Browse the repository at this point in the history
  • Loading branch information
lukakralik committed Jun 7, 2023
1 parent f827b8d commit a24cb11
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/freefang/__pycache__
18 changes: 16 additions & 2 deletions freefang/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
import models
import freefang_utils as utils
import threading

def create_game(playercap):

Expand All @@ -10,7 +11,6 @@ def create_game(playercap):


print("Game created")
players = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #For testing only
game.socket = s
Expand All @@ -25,9 +25,23 @@ def create_game(playercap):

game.players.append(p)
print(f"{p.name} has joined the game")
threading.Thread(target=player_connection, args=(game, p)).start()
game.gameloop()


def player_connection(game, player):
while True:
try:
cmd = player.connection.recv(1024).decode()
if not cmd:
break # Empty message means the player disconnected

# Handle player commands as needed

except ConnectionResetError: # Unexpected disconnection
break

game.players.remove(player)
print(f"{player.name} has left the game")

def main():
print("Starting FreeFang server.")
Expand Down
25 changes: 24 additions & 1 deletion freefang/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ def __init__(self):
self.alive = True
self.name = ""
self.connection = 0
self.voted_by = 0 # Number of people who voted for this player
self.voted = False


class WWgame:
def __init__(self):
Expand All @@ -30,13 +33,33 @@ def distribute_roles(self):

noroles.pop(index)


def update_player_count(self):
num_players = len(self.players)
print(f"Number of present players: {num_players}")

def handle_disconnections(self):
disconnected_players = [] # Track multiple disconnections at a time
for player in self.players:
try:
player.connection.send(b"") # Sending empty message to check connection status
except ConnectionResetError:
disconnected_players.append(player)

for player in disconnected_players:
self.players.remove(player)
print(f"{player.name} disconnected")

self.update_player_count()


def gameloop(self):
print("Game starting")
self.distribute_roles()

inputs = [self.socket] + [i.connection for i in self.players]
outputs = [i.connection for i in self.players]
msgqueues = {}

self.handle_disconnections()


0 comments on commit a24cb11

Please sign in to comment.