0

멀티 플레이어로 퀴즈 게임을 프로그래밍하고 싶습니다. 서버 부분에서 질문을 선택하고 클라이언트에게 보냅니다. 클라이언트는이 대답에 응답하여 서버에 보냅니다. 그런 다음 서버가 맞는지 여부를 확인합니다. 나는 이것을 반복하고 싶다. 하지만 문제는 타이밍의 문제입니다. 때로는 고객이 대답하기 전에 질문을받지 못하는 경우가 있습니다. 또 다른 문제는 클라이언트가 응답을 보낼 때 서버가 응답을받지 못하고 실제로 이유를 모르겠다는 것입니다.퀴즈 멀티 플레이어 게임, 서버가 클라이언트로부터 정보를받지 못함

처음으로 네트워크 프로그래밍을하는 것이므로 스레딩 및 모든 것을 이해하는 것이 어렵습니다.

다음

제이다), 또 다른 질문이 관련, 나는 간단한 그래픽 인터페이스와 함께 작동이 코드를 싶습니다 ...하지만 그 다음 단계입니다 : ) = 당신의 도움을

PS 감사합니다 클라이언트 코드 :

import numpy as np 
from numpy.random import shuffle 
from random import randint 
import socket 
import time 

#LIST OF QUESTIONS AND ANSWERS 
question2 = ["What is the capital of France?","In which continent is Argentina?","Where is Big Ben?","What is the most densely populated country?","What language do they speak in Brazil?"] 
answer2 = [["Paris","London","Berlin","Madrid"], 
     ["South America","Africa","Europe","Asia"], 
     ["London","New York","Mexico","Jakarta"], 
     ["China","India","USA","Indonesia"], 
     ["Portuguese","Spanish","French","English"]] 
question_done=[0]*(len(question2)) 


#SCORE, stored as a list score[0]--> score of the player 1 
score=[0] 


#SHOW THE POSSIBLE ANSWERS 
def displayA(question,answer,i): 
    a = answer[i] 
    order = np.arange(4) 
    shuffle(order) #create list from 1 to 4 in different order --> to print the answers in random order 
    a_display = [[a[order[0]],a[order[1]]],[a[order[2]],a[order[3]]]] 
    print(a_display) 


#CHOOSE RANDOMLY A QUESTION IN THE LIST 
def chooseQuestion(question,answer): 
    k = randint(0,len(question)-1) 
    if (question_done[k]!=0): 
     while(question_done[k]!=0): 
      k = randint(0,len(question)-1) 
     question_done[k]=1 
    else : 
     question_done[k]=1 
    print(question[k]) 
    #displayA(question,answer,k) 
    return k 


#CHECK IF GOOD ANSWER OR NOT 
def checkAnswer(answer,agiven,qnb): 
    print("CHECK") 
    test = False 
    if(answer[qnb][0] in agiven): 
     test = True 
     score[0]=score[0]+1 
    print("ANSWER") 
    return test 



#END OF GAME, DISPLAY OF SCORES 
def final_score(score): 
    print("The scores are {}".format(score)) 

    maxi = max(score) 
    if(score.count(maxi)==1): 
     print("The winner is Player {}".format(score.index(max(score))+1)) 
    else : 
     winners = [] 
     for i in range(len(score)): 
      if(score[i]==maxi): 
       winners.append(i+1) 
     print("The winners are players {}".format(winners)) 


""" 

#Number of choosen questions, random order : GIVE THE QUESTION TO THE PLAYER 
nb = 3 

for k in range(nb): 
    nbq = chooseQuestion(question2,answer2) 
    agiven = raw_input("What is your answer? ") 
    result = checkAnswer(answer2,agiven,nbq) 
    print("Your answer is {}".format(result)) 



#Say who the winner is 
final_score(score) 



""" 
#START THE NETWORK CODE 
#host = '192.168.26.86' 
host = '127.0.0.1' 

port = 5000 

#list for all the players 
players = [] 

#creation of socket object UDP and bind 
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
s.bind((host, port)) 
#socket non blocking --> will always try to grab datas from the stream 
#not block it 
s.setblocking(0) 


quitting = False 
print "Server Started." 

#NUMBER OF QUESTIONS 
nb = 3 


while (not quitting and nb>0): 
    try: 
      data, addr = s.recvfrom(1024) 
      print("FIRST RECV {}".format(data)) 
      if "Quit" in str(data): 
       quitting = True 
      if addr not in players: 
       players.append(addr) 
       print("liste players {}".format(players)) 
       s.sendto("the game is starting ",players[len(players)-1]) 

      print time.ctime(time.time()) + ":" + str(data) 

      #GAME 

      #for k in range(nb): 
      print("question nb {}".format(nb)) 
      nbq = chooseQuestion(question2,answer2) 


      for i in range(len(players)): 
       print("ENTER FOR") 
       #s.sendto(question2[nbq], players[i]) 
       try: 
        s.sendto(question2[nbq], players[i]) 
        print("BEFORE GET ANSWER") 
        agiven, addr = s.recvfrom(1024) 
        print("GOT ANSWER") 

        print("agiven is : {}".format(agiven)) 
        checkAnswer(answer2,agiven,nbq) 

        if "Quit" in str(agiven): 
         quitting = True 
        if addr not in players: 
         s.sendto("You cannot enter the game now ",addr) 
        else: 
         players[i] = addr 
       except: 
        pass 

      nb=nb-1 

    except: 
      pass 



for i in range(len(players)): 
    try: 
     s.sendto("The game is finished, write q to quit",players[i]) 

    except: 
     pass 

final_score(score) 
s.close() 

답변

0

귀하의 코드는 질문과 답변에 대한 올바른 로직을 포함하지만, DAT : 여기

import socket 
import threading 
import time 

tLock = threading.Lock() 
shutdown = False 

def receving(name, sock): 
    while not shutdown: 
      try: 
       tLock.acquire() 
       while True: 
         data,addr = sock.recvfrom(1024) 
         print(str(data)) 
      except: 
        pass 
      finally: 
        tLock.release() 

#host = '192.168.26.86' 
host = '127.0.0.1' 
port = 0 #pick any free port currently on the computer 
server = (host, 5000) 

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
s.bind((host,port)) 
s.setblocking(0) 

#receiving thread 
rT = threading.Thread(target=receving, args=("RecvThread", s)) 
rT.start() 

alias = raw_input("Name: ") 

#PLAYER ENTERS DATA 
message = raw_input(alias + "First msg ->") 

while message != 'q': 
     tLock.acquire() 
     message = raw_input(alias + "What is your answer ? ->") 
     tLock.release() 


     if message != '': 
      s.sendto(alias + ": " + message, server) 

     time.sleep(0.2) 

shutdown = True 
rT.join() 
s.close() 

내 서버 코드 클라이언트와 서버 간의 전송은 허약했으며 타이밍이 완벽하다면 작동했습니다.

타이밍을 제어하고 순서가 바뀌지 않도록 코드를 수정했습니다. select() 시스템 호출을 사용하여 타임 아웃을 처리하고, 클라이언트에서 질문이 서버에서 도착하면 메인 루프에 알리기 위해 읽기 스레드를 변경했습니다.

이 코드는 완벽하지는 않지만 먼 거리에서 작동하며 원하는 방식으로 작동하는 최종 코드를 작성하는 데 도움이됩니다.

NB 원래 코드를 디버깅하는 데 도움이되는 "지금 게임에 참여할 수 없습니다."코드가 제거되었으므로 아마도 지금 다시 넣을 수 있습니다. 희망이 도움이됩니다.

클라이언트 코드 :

import socket 
import threading 
import time 

tEv = threading.Event() 
tShutdown = threading.Event() 

def receving(name, sock): 
    shutdown = False 
    while not shutdown: 
     try: 
      data,addr = sock.recvfrom(1024) 
      print(str(data)) 
      if '?' in data: 
       tEv.set() 
      if data == "The game is finished": # message from server to stop 
       tShutdown.set() 
       shutdown = True 
     except: 
      pass 
     finally: 
      pass 

#host = '192.168.26.86' 
host = '127.0.0.1' 
port = 0 #pick any free port currently on the computer 
server = (host, 5000) 

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
s.bind((host,port)) 
s.setblocking(0) 

# Start listener 
rT = threading.Thread(target=receving, args=("RecvThread", s)) 
rT.start() 

# Join the game 
alias = raw_input("Name: ") 
s.sendto(alias, server) 

running = True 
while running: 
    if tEv.wait(1.0): 
     tEv.clear() 
     message = raw_input(alias + ", what is your answer ? -> ") 
     if message != '': 
      s.sendto(alias + ": " + message, server) 
    if tShutdown.is_set(): 
     running = False 

rT.join() 
s.close() 

서버 코드 :

import numpy as np 
from numpy.random import shuffle 
from random import randint 
import socket 
import time 
import select 

#LIST OF QUESTIONS AND ANSWERS 
question2 = ["What is the capital of France?","In which continent is Argentina?","Where is Big Ben?","What is the most densely populated country?","What language do they speak in Brazil?"] 
answer2 = [["Paris","London","Berlin","Madrid"], 
     ["South America","Africa","Europe","Asia"], 
     ["London","New York","Mexico","Jakarta"], 
     ["China","India","USA","Indonesia"], 
     ["Portuguese","Spanish","French","English"]] 
question_done=[0]*(len(question2)) 


#SCORE, stored as a list score[0]--> score of the player 1 
score=[0] 


#SHOW THE POSSIBLE ANSWERS 
def displayA(question,answer,i): 
    a = answer[i] 
    order = np.arange(4) 
    shuffle(order) #create list from 1 to 4 in different order --> to print the answers in random order 
    a_display = [[a[order[0]],a[order[1]]],[a[order[2]],a[order[3]]]] 
    print(a_display) 


#CHOOSE RANDOMLY A QUESTION IN THE LIST 
def chooseQuestion(question,answer): 
    k = randint(0,len(question)-1) 
    if (question_done[k]!=0): 
     while(question_done[k]!=0): 
      k = randint(0,len(question)-1) 
     question_done[k]=1 
    else : 
     question_done[k]=1 
    print(question[k]) 
    #displayA(question,answer,k) 
    return k 


#CHECK IF GOOD ANSWER OR NOT 
def checkAnswer(answer,agiven,qnb): 
    #print("CHECK") 
    test = False 
    if(answer[qnb][0] in agiven): 
     test = True 
     score[0]=score[0]+1 
    #print("ANSWER") 
    return test 



#END OF GAME, DISPLAY OF SCORES 
def final_score(score): 
    print("The scores are {}".format(score)) 

    maxi = max(score) 
    if(score.count(maxi)==1): 
     print("The winner is Player {}".format(score.index(max(score))+1)) 
    else : 
     winners = [] 
     for i in range(len(score)): 
      if(score[i]==maxi): 
       winners.append(i+1) 
     print("The winners are players {}".format(winners)) 


""" 
#Number of choosen questions, random order : GIVE THE QUESTION TO THE PLAYER 
nb = 3 

for k in range(nb): 
    nbq = chooseQuestion(question2,answer2) 
    agiven = raw_input("What is your answer? ") 
    result = checkAnswer(answer2,agiven,nbq) 
    print("Your answer is {}".format(result)) 

#Say who the winner is 
final_score(score) 
""" 
#START THE NETWORK CODE 
#host = '192.168.26.86' 
host = '127.0.0.1' 

port = 5000 

#list for all the players 
players = [] 

#creation of socket object UDP and bind 
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
s.bind((host, port)) 
#socket non blocking --> will always try to grab datas from the stream 
#not block it 
s.setblocking(0) 

print "Server Started." 

#INITIAL SETUP PERIOD 
secs = 20 
max_players = 5 

# WAIT FOR PLAYERS TO JOIN 
while ((secs > 0) and (len(players) < max_players)): 
    ready = select.select([s], [], [], 1) 
    if ready[0]: 
     data, addr = s.recvfrom(1024) 
     print("FIRST RECV {}".format(data)) 
     if addr not in players: 
      players.append(addr) 
      print("liste players {}".format(players)) 
      s.sendto("Wait for game to start... ",players[len(players)-1]) 
     print time.ctime(time.time()) + ":" + str(data) 
    secs = secs - 1 

#START GAME 
print("Game starting") 
for i in range(len(players)): 
    try: 
     s.sendto("Game starting", players[i]) 
    except: 
     pass 

#ASK QUESTIONS 
nb = 3 
for k in range(nb): 
    print("question nb {}".format(k)) 
    nbq = chooseQuestion(question2,answer2) 
    #print("ENTER FOR") 
    for i in range(len(players)): 
     try: 
      s.sendto(str(question2[nbq]), players[i]) 
      #print("BEFORE GET ANSWER") 
      agiven = "" 
      ready = select.select([s], [], [], 10) 
      if ready[0]: 
       agiven, addr = s.recvfrom(1024) 
       #print("GOT ANSWER") 
      print("agiven is : {}".format(agiven)) 
      checkAnswer(answer2,agiven,nbq) 
     except: 
      pass 

for i in range(len(players)): 
    try: 
     s.sendto("The game is finished", players[i]) 
    except: 
     pass 

final_score(score) 
s.close() 
+0

너무 감사합니다! 그게 내가 필요한 것입니다. 내가 선택에 대해 몰랐고 그것은 나를 위해 정말로 흥미 롭다. =) –

관련 문제