Я разработал викторину в python с использованием программирования сокетов. Сервер задает вопросы 3 клиентам, а клиенты отвечают на них. Чтобы ответить, клиенты должны нажать на зуммер, а затем ответить на вопрос. 1 балл присуждается за каждый правильный ответ и -0,5 за неправильный. Первый набирает 5 очков. Вот мой код:
Сервер:
import socket
import sys
import time
import select
all_connections = []
all_address = []
questions = []
for i in range(50):
questions.append("Q" + str(i+1) + " : " + "1 + " + str(i+1) + " = ? ")
answers = []
for j in range(50):
answers.append(j+2)
Marks=[0,0,0]
response=[]
def create_socket():
try:
global host
global port
global s
host = ""
print("Enter any port number to host the game : ")
port = input()
s = socket.socket()
except socket.error as msg:
print("Socket creation error : " + str(msg))
def bind_socket():
try:
global host
global port
global s
print("Binding the Port : " + str(port))
s.bind((host, int(port)))
s.listen(5)
except socket.error as msg:
print("Socket Binding error" + str(msg) + "\n" + "Retrying...")
def accepting_connections():
for c in all_connections:
c.close()
del all_connections[:]
del all_address[:]
noOfClients = 0
while True:
conn, address = s.accept()
s.setblocking(1)
noOfClients = noOfClients + 1
all_connections.append(conn)
all_address.append(address)
if noOfClients < 3:
print("Connection has been established : Client " + str(noOfClients) + " " + address[0])
conn.send(str.encode("WELCOME TO THE GAME!!!!"))
time.sleep(1)
conn.send(str.encode("The questions will be asked one by one."))
time.sleep(1)
conn.send(str.encode("If you know the correct answer, press the BUZZER within 10 seconds after the question is asked"))
time.sleep(1)
conn.send(str.encode("If you press the buzzer first, you will be given a chance to provide the answer within 10 seconds."))
time.sleep(1)
conn.send(str.encode("If the answer is correct, you will be given 1 point, otherwise -0.5. Nobody will get a chance to answer this question again"))
time.sleep(1)
conn.send(str.encode("The first player to get 5 points wins. "))
time.sleep(1)
conn.send(str.encode("You are Player number : " + str(noOfClients)))
time.sleep(1)
else:
print("Connection has been established : Client " + str(noOfClients) + " " + address[0])
print("Maximum Clients connected")
conn.send(str.encode("WELCOME TO THE GAME!!!!"))
time.sleep(1)
conn.send(str.encode("The questions will be asked one by one."))
time.sleep(1)
conn.send(str.encode("If you know the correct answer, press the BUZZER within 10 seconds after the question is asked"))
time.sleep(1)
conn.send(str.encode("If you press the buzzer first, you will be given a chance to provide the answer within 10 seconds."))
time.sleep(1)
conn.send(str.encode("If the answer is correct, you will be given 1 point, otherwise -0.5. Nobody will get a chance to answer this question again."))
time.sleep(1)
conn.send(str.encode("The first player to get 5 points wins."))
time.sleep(1)
conn.send(str.encode("You are Player number : " + str(noOfClients)))
time.sleep(1)
thread_function()
break
def thread_function():
for i in range(len(questions)):
for conn in all_connections:
time.sleep(0.1)
conn.send(str.encode(questions[i]))
conn.send(str.encode("Press the buzzer only if you know the answer"))
response1 = select.select(all_connections,[],[],10)
if(len(response1[0]) > 0):
conn_name = response1[0][0]
b = conn_name.recv(1024)
b = b.decode("utf-8")
response1 = ()
for conn in all_connections:
if conn != conn_name:
conn.send(str.encode("Sorry, player " + str(all_connections.index(conn_name) + 1) + " has pressed the buzzer."))
for j in range(len(all_connections)):
if all_connections[j] == conn_name:
responder = j
if b == 'y':
conn_name.send(str.encode("Answer the Question"))
answer = str(conn_name.recv(1024), "utf-8")
if answer == str(answers[i]):
Marks[responder] = Marks[responder] + 1
conn_name.send(str.encode("Correct Answer, You get 1 Point !!!"))
if Marks[responder] >= 5:
return
else:
conn_name.send(str.encode("Wrong Answer, You get -0.5 points"))
Marks[responder] = Marks[responder] - (0.5)
time.sleep(1)
elif b == str(answers[i]):
conn_name.send(str.encode("You didn't press the buzzer before answering. You get -1 points"))
Marks[responder] = Marks[responder] - 1
time.sleep(1)
else:
for c in all_connections:
c.send(str.encode("Nobody pressed the buzzer. Moving on..."))
def main():
create_socket()
bind_socket()
accepting_connections()
winnerMarks = 0
winner = 0
for i in range(len(all_connections)):
if Marks[i] > winnerMarks:
winner = i
winnerMarks = Marks[i]
for c in all_connections:
if all_connections.index(c) != winner:
c.send(str.encode("The winner is Player: " + str(winner + 1) + " with " + str(winnerMarks) + " points" ))
else:
c.send(str.encode("Congratulations! You are the winner with " + str(winnerMarks) + " Points" ))
main()
Клиент:
import socket
import time
import select
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Enter IP address of server")
host = input()
print("Enter port number")
port = input()
s.connect((host, int(port)))
inst1 = str(s.recv(1024), "utf-8")
print(inst1)
inst2 = str(s.recv(1024), "utf-8")
print(inst2)
inst3 = str(s.recv(1024), "utf-8")
print(inst3)
inst4 = str(s.recv(1024), "utf-8")
print(inst4)
inst5 = str(s.recv(1024), "utf-8")
print(inst5)
inst6 = str(s.recv(1024), "utf-8")
print(inst6)
inst7 = str(s.recv(1024), "utf-8")
print(inst7)
noOfQuestions = 50
index = 0
while(index < noOfQuestions):
question_1 = str(s.recv(1024), "utf-8")
print(question_1)
question_2 = str(s.recv(1024), "utf-8")
print(question_2)
c = select.select([s],[],[],10)[0]
import msvcrt
if msvcrt.kbhit():
c.append(sys.stdin)
if len(c) > 0:
if c[0] == sys.stdin:
y = input()
s.send(str.encode(y))
else:
d = str(c[0].recv(1024), "utf-8")
print(d)
index = index + 1
continue
data2 = str(s.recv(1024),"utf-8")
print(data2)
if data2 == 'Answer the Question':
ans = input()
time.sleep(1)
s.send(str.encode(ans))
index = index + 1
result = str(s.recv(1024), "utf-8")
print(result)
finalResult = str(s.recv(1024), "utf-8")
print(finalResult)
Но во время выполнения кода он не работает должным образом. Это вывод, который я получаю:
You are Player number : 2
Q1 : 1 + 1 = ?
Press the buzzer only if you know the answer
y
Nobody pressed the buzzer. Moving on...
Q2 : 1 + 2 = ?
Answer the question
, а затем программы останавливаются.
Идеальный вывод должен быть следующим:
You are Player number : 2
Q1 : 1 + 1 = ?
Press the buzzer only if you know the answer
y
Answer the question
2
Correct Answer, You get 1 Point !!!
Q2 : 1 + 2 = ?
Press the buzzer only if you know the answer
Sorry, player 3 has pressed the buzzer.
Так как я новичок Что касается программирования сокетов, я не очень понимаю, где я go ошибся.
Любые идеи или предложения о том, как исправить мою программу, будут любезно оценены.