develop
huangjielun 3 years ago
commit 2e4d5c1bab

@ -6,13 +6,14 @@ import uuid
import time import time
from threading import Thread, Lock from threading import Thread, Lock
if(sys.version[:1] == "3"): if (sys.version[:1] == "3"):
import queue as Queue import queue as Queue
from _thread import * from _thread import *
else: else:
import Queue import Queue
from thread import * from thread import *
class Config: class Config:
SOCKET_HOST = '127.0.0.1' # Symbolic name meaning all available interfaces SOCKET_HOST = '127.0.0.1' # Symbolic name meaning all available interfaces
SOCKET_PORT = 50005 # Arbitrary non-privileged port SOCKET_PORT = 50005 # Arbitrary non-privileged port
@ -20,6 +21,7 @@ class Config:
MAX_THNIKING_TIME = 60 MAX_THNIKING_TIME = 60
MAX_TOTAL_TIME = 600 MAX_TOTAL_TIME = 600
class Client: class Client:
def __init__(self, conn, addr, name, side, time, total): def __init__(self, conn, addr, name, side, time, total):
self.conn = conn self.conn = conn
@ -29,13 +31,16 @@ class Client:
self.time = time self.time = time
self.total = total self.total = total
mutex = Lock() mutex = Lock()
mutex_playing = Lock() mutex_playing = Lock()
playing_ones = {} playing_ones = {}
waiting_players = Queue.Queue() waiting_players = Queue.Queue()
#init queues
#for games in range(1, 10):
# init queues
# for games in range(1, 10):
# waiting_players[games] = Queue.Queue() # waiting_players[games] = Queue.Queue()
def load_config(): def load_config():
@ -43,18 +48,19 @@ def load_config():
for line in f.readlines(): for line in f.readlines():
line = line.strip() line = line.strip()
if line.find('SOCKET_HOST=') >= 0: if line.find('SOCKET_HOST=') >= 0:
Config.SOCKET_HOST = line[line.index('=') + 1 : ] Config.SOCKET_HOST = line[line.index('=') + 1:]
elif line.find('SOCKET_PORT=') >= 0: elif line.find('SOCKET_PORT=') >= 0:
Config.SOCKET_PORT = int(line[line.index('=') + 1 : ]) Config.SOCKET_PORT = int(line[line.index('=') + 1:])
elif line.find('MAX_WAITING_TIME=') >= 0: elif line.find('MAX_WAITING_TIME=') >= 0:
Config.MAX_WAITING_TIME = int(line[line.index('=') + 1 : ]) Config.MAX_WAITING_TIME = int(line[line.index('=') + 1:])
elif line.find('MAX_THNIKING_TIME=') >= 0: elif line.find('MAX_THNIKING_TIME=') >= 0:
Config.MAX_THNIKING_TIME = int(line[line.index('=') + 1 : ]) Config.MAX_THNIKING_TIME = int(line[line.index('=') + 1:])
elif line.find('MAX_TOTAL_TIME=') >= 0: elif line.find('MAX_TOTAL_TIME=') >= 0:
Config.MAX_TOTAL_TIME = int(line[line.index('=') + 1 : ]) Config.MAX_TOTAL_TIME = int(line[line.index('=') + 1:])
else: else:
pass pass
def get_counterpart_from(waiting_ones): def get_counterpart_from(waiting_ones):
counterpart = None counterpart = None
mutex.acquire() mutex.acquire()
@ -63,24 +69,28 @@ def get_counterpart_from(waiting_ones):
mutex.release() mutex.release()
return counterpart return counterpart
def to_wait_in_queue(client, the_queue): def to_wait_in_queue(client, the_queue):
mutex.acquire() mutex.acquire()
the_queue.put(client) the_queue.put(client)
mutex.release() mutex.release()
def remove_one_from_queue(the_queue): def remove_one_from_queue(the_queue):
mutex.acquire() mutex.acquire()
if (the_queue.qsize() == 1): if (the_queue.qsize() == 1):
the_queue.get() the_queue.get()
mutex.release() mutex.release()
def send_msg_to(client, msg): def send_msg_to(client, msg):
packet = json.dumps(msg) packet = json.dumps(msg)
if (sys.version[:1] == "3"): if (sys.version[:1] == "3"):
packet = packet.encode('utf-8') packet = packet.encode('utf-8')
#print(client.addr[0] + ":" + str(client.addr[1]) + "\t" + str(msg)) # print(client.addr[0] + ":" + str(client.addr[1]) + "\t" + str(msg))
client.conn.send(packet) client.conn.send(packet)
def __start_match_between(client0, client1): def __start_match_between(client0, client1):
match_uuid = str(uuid.uuid4()) match_uuid = str(uuid.uuid4())
mutex_playing.acquire() mutex_playing.acquire()
@ -113,18 +123,20 @@ def __start_match_between(client0, client1):
} }
send_msg_to(client1, msg1) send_msg_to(client1, msg1)
def join_game_handler(msg, addr, conn): def join_game_handler(msg, addr, conn):
new_client = Client(conn, addr, msg['name'], -1, -1, -1) new_client = Client(conn, addr, msg['name'], -1, -1, -1)
#game_type = msg["id"] # game_type = msg["id"]
#the_queue = waiting_players[game_type] # the_queue = waiting_players[game_type]
counterpart = get_counterpart_from(waiting_players) counterpart = get_counterpart_from(waiting_players)
if not counterpart: #wait if not counterpart: # wait
to_wait_in_queue(new_client, waiting_players) to_wait_in_queue(new_client, waiting_players)
return return
else: else:
#counterpart=get_counterpart_from(waiting_players[game_type]) # counterpart=get_counterpart_from(waiting_players[game_type])
__start_match_between(new_client, counterpart) __start_match_between(new_client, counterpart)
def quit_game_handler(msg): def quit_game_handler(msg):
match_uuid = msg['game_id'] match_uuid = msg['game_id']
if match_uuid is None: if match_uuid is None:
@ -138,25 +150,26 @@ def quit_game_handler(msg):
mutex_playing.release() mutex_playing.release()
if pairs is not None: if pairs is not None:
if(pairs[0].side == msg['side']): if (pairs[0].side == msg['side']):
to_notify = pairs[1] to_notify = pairs[1]
else: else:
to_notify = pairs[0] to_notify = pairs[0]
msg = { msg = {
"status": 2, #exit "status": 2, # exit
"game_id": match_uuid, "game_id": match_uuid,
"side": msg['side'], "side": msg['side'],
"request": msg['request'], "request": msg['request'],
} }
send_msg_to(to_notify, msg) send_msg_to(to_notify, msg)
def timer_thread(): def timer_thread():
while True: while True:
time.sleep(1) time.sleep(1)
mutex_playing.acquire() mutex_playing.acquire()
for game_id in list(playing_ones.keys()): for game_id in list(playing_ones.keys()):
(client0, client1) = playing_ones[game_id] (client0, client1) = playing_ones[game_id]
#print("%d - %d" % (client0.time, client1.time)) # print("%d - %d" % (client0.time, client1.time))
if (client0.time < 0): if (client0.time < 0):
client = client1 client = client1
else: else:
@ -164,7 +177,7 @@ def timer_thread():
if (client.time == 0 or client.total == 0): if (client.time == 0 or client.total == 0):
msg = { msg = {
"status": 3, #timeout exit "status": 3, # timeout exit
"game_id": game_id, "game_id": game_id,
"side": client.side, "side": client.side,
} }
@ -176,10 +189,11 @@ def timer_thread():
client.total -= 1 client.total -= 1
mutex_playing.release() mutex_playing.release()
def transfer_message(msg): def transfer_message(msg):
match_uuid = msg['game_id'] match_uuid = msg['game_id']
pairs = playing_ones[match_uuid] pairs = playing_ones[match_uuid]
if(pairs[0].side == msg['side']): if (pairs[0].side == msg['side']):
to_notify = pairs[1] to_notify = pairs[1]
pairs[0].time = -1 pairs[0].time = -1
else: else:
@ -188,6 +202,7 @@ def transfer_message(msg):
to_notify.time = Config.MAX_THNIKING_TIME to_notify.time = Config.MAX_THNIKING_TIME
send_msg_to(to_notify, msg) send_msg_to(to_notify, msg)
def client_thread(conn, addr): def client_thread(conn, addr):
while True: while True:
try: try:
@ -212,22 +227,24 @@ def client_thread(conn, addr):
elif data['type'] == 3: elif data['type'] == 3:
break break
else: else:
#delivering message between the two clients # delivering message between the two clients
transfer_message(data['msg']) transfer_message(data['msg'])
continue continue
except: except:
break break
#came out of loop # came out of loop
conn.close() conn.close()
#print("conneection exit!")
# print("conneection exit!")
def main(): def main():
load_config() load_config()
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket server created') print('Socket server created')
#try: # try:
server.bind((Config.SOCKET_HOST, Config.SOCKET_PORT)) server.bind((Config.SOCKET_HOST, Config.SOCKET_PORT))
#except (socket.error, msg): # except (socket.error, msg):
# print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) # print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
# sys.exit() # sys.exit()
@ -235,17 +252,17 @@ def main():
server.listen(10) server.listen(10)
print('Socket now listening') print('Socket now listening')
#now keep talking with the client # now keep talking with the client
start_new_thread(timer_thread, ()) start_new_thread(timer_thread, ())
while True: while True:
#wait to accept a connection - blocking call # wait to accept a connection - blocking call
conn, addr = server.accept() conn, addr = server.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1])) print('Connected with ' + addr[0] + ':' + str(addr[1]))
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function. # start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(client_thread, (conn, addr)) start_new_thread(client_thread, (conn, addr))
server.close() server.close()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

@ -1672,6 +1672,18 @@ def server_thread(conn,addr) :
except: except:
return return
def time_ShowAndCheck(player: player):
time.sleep(1)
clock = str(player.think_time) + ''
largeText = pygame.font.SysFont('comicsansms', 25)
TextSurf, TextRect = text_objects(clock, largeText)
if player.side == 1:
TextRect = init.tran(0,3)
else:
TextRect = init.tran(8,3)
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
mutex_playing = Lock() mutex_playing = Lock()
def time_thread(): def time_thread():
@ -1684,6 +1696,7 @@ def time_thread():
break break
else: else:
player.think_time -= 1 player.think_time -= 1
time_ShowAndCheck(player)
player.total_time -= 1 player.total_time -= 1
if is_over_time: if is_over_time:
return False return False
@ -1691,7 +1704,7 @@ def time_thread():
return True return True
class Config: class Config:
SOCKET_HOST = '127.0.0.1'#Symbolic name meaning all available interfaces SOCKET_HOST = '192.168.43.201'#Symbolic name meaning all available interfaces
SOCKET_PORT = 50005#Arbitrary non-privileged port SOCKET_PORT = 50005#Arbitrary non-privileged port
MAX_WAITING_TIME = 180 MAX_WAITING_TIME = 180
MAX_THNIKING_TIME = 60 MAX_THNIKING_TIME = 60
@ -1747,6 +1760,7 @@ def main():
run = False run = False
if demo == 1: if demo == 1:
C.start_new_thread(server_thread, (client,Address)) C.start_new_thread(server_thread, (client,Address))
C.server_thread(time_thread,())
Right_win = player.Right_win Right_win = player.Right_win
Left_win = player.Left_win Left_win = player.Left_win
for event in pygame.event.get(): for event in pygame.event.get():

@ -0,0 +1,32 @@
import pygame
import time
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width, display_height))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def time_ShowAndCheck(client_time):
time.sleep(1)
gameDisplay.fill(white)
count = client_time
clock = str(count)
largeText = pygame.font.SysFont('comicsansms', 25)
TextSurf, TextRect = text_objects(clock, largeText)
TextRect.center = (750, (display_height / 10))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
flag = 300
while flag:
time_ShowAndCheck(flag)
flag -= 1
Loading…
Cancel
Save