-
Notifications
You must be signed in to change notification settings - Fork 2
/
room.py
94 lines (74 loc) · 2.63 KB
/
room.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import board
import amazons
import timer
import asyncio
import json
from Surakarta import Surakarta
get_mesg = lambda x: bytes(str(json.dumps(x)), 'utf-8')
class Room():
def __init__(self, boardtype, boardargs, totaltime, roomId):
# 初始化棋盘,计时器, 玩家列表, 比赛状态
self.__board = board.Board()
self.__timer = timer.Timer(totaltime)
self.__status = 0
self.roomId = roomId
self.type = boardtype
self.player = []
self.history = []
# 根据棋种覆盖原棋盘
if boardtype == None:
pass
elif boardtype == 'amazons':
self.__board = amazons.Amazons(boardargs[0], boardargs[1])
else:
self.__board = Surakarta()
# 加入玩家
def addPlayer(self, player, order):
if self.type == 'amazons':
playerId = 'B' if order == '1' else 'A'
elif self.type == 'surakarta':
playerId = 1 if order == '1' else -1
self.player.append({'id': playerId, 'player': player, 'order': order})
return playerId
# 删除玩家
def removePlayer(self, id):
playerNum = len(self.player)
for i in range(playerNum):
if self.player[i]['id'] == id:
self.player.pop(i)
return 1
# 开始游戏,并开始计时
async def start(self, playerId):
self.__status += 1
if self.__status >= 2:
mesg = {'mesg': 'start'}
await self.notifyToAll(mesg)
else:
mesg = {'mesg': 'ready'}
await self.notifyToOther(playerId, mesg)
async def rollback(self):
board = self.__board.rollback()
await self.notifyToAll({'mesg': 'rollback', 'board': board})
# 获取比赛状态
def status(self):
return {'status': self.__status, 'message': None}
# 移动棋子
async def move(self, player, location, *kw):
board, result = self.__board.fire(player, location, *kw)
self.history.append(board)
await self.notifyToOther(player, {'mesg': 'move', 'move': location, 'player': player, 'result': result, 'kw': kw[0]})
# 通知另一方玩家
async def notifyToOther(self, playerId, mesg):
for i in self.player:
if i['id'] != playerId:
await i['player'].send(get_mesg(mesg))
# 通知所有玩家
async def notifyToAll(self, mesg):
for i in self.player:
await i['player'].send(get_mesg(mesg))
# 先后手次序
def getOrder(self):
if self.player[0]['order'] == '1':
return '2'
else:
return '1'