Question: i have codes but there is so many errors ! the client cannot write the answer, the server do not wait before start the game

i have codes but there is so many errors !
the client cannot write the answer, the server do not wait before start the game , the scores doesnot showed after every question and the client should enter the ip and the port numbers of the server then their names and if you find any another errors please fixed it :import socket
import time
import threading
class TriviaClient:
def __init__(self, server_ip, server_port, username):
self.server_ip = server_ip
self.server_port = server_port
self.username = username
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.client_socket.settimeout(1)
def connect_to_server(self):
self.client_socket.sendto(self.username.encode(),(self.server_ip, self.server_port))
print(f"Connected to {self.server_ip}:{self.server_port} as {self.username}")
def receive_messages(self):
while True:
try:
data, _= self.client_socket.recvfrom(1024)
message = data.decode()
print(f"Server: {message}")
if "Question:" in message:
self.ask_question(message)
elif "Game Over" in message:
print("Game Over. Disconnecting.")
break
except socket.timeout:
continue
def ask_question(self, question_text):
print(f"Question received: {question_text}")
answer = input("Your answer (or type 'quit' to exit): ")
if answer.lower()== "quit":
print("Exiting game.")
self.close_connection()
exit()
self.client_socket.sendto(answer.encode(),(self.server_ip, self.server_port))
def close_connection(self):
self.client_socket.close()
print("Connection closed.")
def start_client():
username = input("Enter your name: ")
client = TriviaClient("localhost",5689, username)
client.connect_to_server()
client.receive_messages()
if __name__=="__main__":
start_client()
# Trivia questions database
questions_db =[
("What is the capital of France?", "Paris"),
("What is 2+2?","4"),
("Who wrote 'To Kill a Mockingbird'?", "Harper Lee"),
("What is the largest planet in our solar system?", "Jupiter"),
("What is the square root of 64?","8"),
("Who painted the Mona Lisa?", "Leonardo da Vinci"),
("What is the speed of light?", "299792458 m/s"),
("Who discovered penicillin?", "Alexander Fleming"),
("What is the chemical symbol for gold?", "Au"),
("What is the tallest mountain on Earth?", "Mount Everest")
]
class TriviaServer:
def __init__(self, host='localhost', port=5689):
self.host = host
self.port = port
self.clients ={} # Stores client addresses and their names
self.scores ={} # Stores client scores
self.current_round =0
self.max_rounds =5
self.questions_per_round =3
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.server_socket.settimeout(1) # Prevent blocking
try:
self.server_socket.bind((self.host, self.port))
print(f"Server started on {self.host}:{self.port}")
except Exception as e:
print(f"Error binding server to {self.host}:{self.port}: {e}")
exit()def start_game(self):
# Wait for players to join
print("Waiting for players to join...")
while len(self.clients)<2: # Minimum 2 players required
self.collect_new_players()
time.sleep(1) # Avoid busy waiting
print(f"Players connected: {','.join(self.clients.values())}")
print("Game is starting!")
self.broadcast_message("The game is starting!")
# Start game rounds
while self.current_round < self.max_rounds:
self.current_round +=1
print(f"
Starting round {self.current_round}...")
self.broadcast_message(f"Round {self.current_round} is starting! Get ready!")
self.ask_questions()
self.end_round()
time.sleep(5) # Pause between rounds
print("Game Over. Final scores:")
self.show_scores() def collect_new_players(self):
"""Collect new players who send their names."""
try:
data, addr = self.server_socket.recvfrom(1024)
if addr not in self.clients:
self.clients[addr]= data.decode()
self.scores[addr]=0
print(f"New player joined: {self.clients[addr]}({addr})")
self.broadcast_message(f"Welcome {self.clients[addr]}! Current players: {','.join(self.clients.values())}")
except socket.timeout:
pass
def broadcast_message(self, message):
"""Send a message to all connected clients."""
for client in self.clients:
self.server_socket.sendto(message.encode(), client)
and the rest of code can not added beacause space

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!