-
Notifications
You must be signed in to change notification settings - Fork 0
/
controllers.py
254 lines (219 loc) · 11.6 KB
/
controllers.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
from argparse import ArgumentError
from linebot import LineBotApi
from linebot.models import *
from google.cloud.firestore import Client
from card.cardServices import ChanceService, DestinyService
from models import *
from services import GameService, UserService
from views import ConsoleArgument, View, ViewFactory
class BaseController:
def __init__(self, lineBotApi: LineBotApi, db: Client, gameService=None, userService=None):
self._db = db
self.lineBotApi = lineBotApi
self.gameService = GameService(db) if gameService == None else gameService
self.userService = UserService(db) if userService == None else userService
def recordAndReply(self, view: View):
self.lineBotApi.reply_message(self.event.reply_token, view.message)
self.userService.setLastMessageId(self.userId, view.messageId)
def handleEvent(self, event):
self.event = event
self.userId = event.source.user_id
def removeUserData(self):
self.gameService.leaveGame(self.userId)
self.userService.delete(self.userId)
def getUserName(self, userId):
return self.lineBotApi.get_profile(userId).display_name
class FollowController(BaseController):
def __init__(self, lineBotApi: LineBotApi, db: Client, gameService=None, userService=None):
super().__init__(lineBotApi, db, gameService, userService)
def handleEvent(self, event):
super().handleEvent(event)
if isinstance(event, UnfollowEvent):
self.removeUserData()
elif isinstance(event, FollowEvent):
self.recordAndReply(ViewFactory.greeting())
class DefaultController(BaseController):
def __init__(self, lineBotApi: LineBotApi, db: Client, gameService=None, userService=None):
super().__init__(lineBotApi, db, gameService, userService)
def handleEvent(self, event):
super().handleEvent(event)
if isinstance(event, PostbackEvent):
data = PostbackData.parse(event.postback.data)
if data.type == PostbackType.CreateGame:
gameId = self.gameService.createGame(self.userId)
self.userService.initGameData(self.userId)
self.recordAndReply(
ViewFactory.gameCreated(
ConsoleArgument(
gameId,
self.getUserName(self.userId),
UserService.initBalance)))
return
elif isinstance(event, MessageEvent) and isinstance(event.message, TextMessage):
if GameService.isGameId(event.message.text):
if self.gameService.joinGame(event.message.text, self.userId):
self.userService.initGameData(self.userId)
self.recordAndReply(
ViewFactory.joinGameSuccess(
ConsoleArgument(
event.message.text,
self.getUserName(self.userId),
UserService.initBalance)))
else:
self.recordAndReply(ViewFactory.joinGameFail())
return
self.recordAndReply(ViewFactory.greeting())
class GameController(BaseController):
def __init__(self, lineBotApi: LineBotApi, db: Client, gameId: str, gameService=None, userService=None):
super().__init__(lineBotApi, db, gameService, userService)
self.gameId = gameId
def handleEvent(self, event):
super().handleEvent(event)
self.responseContext = None
self.userName = self.getUserName(self.userId)
try:
if isinstance(event, PostbackEvent):
self.data = PostbackData.parse(event.postback.data)
excution = {
PostbackType.Console: self.replyConsole,
PostbackType.LeaveConfirm: self.replyLeaveConfirm,
PostbackType.Leave:self.leaveGame,
PostbackType.Earn: self.askEarnAmount,
PostbackType.Pay: self.askPayAmount,
PostbackType.Transfer: self.askTransferTarget,
PostbackType.SelectTransferTarget: self.askTransferAmount,
PostbackType.Chance: self.drawChanceCard,
PostbackType.Destiny: self.drawDestinyCard,
PostbackType.Rollback: self.rollback,
}
if self.data.type in excution: excution[self.data.type]()
return
self.userContext = self.userService.getContext(self.userId)
if self.userContext != None:
excution = {
UserContextType.Earn: self.earn,
UserContextType.Pay: self.pay,
UserContextType.TransferAmount: self.transfer,
}
if self.userContext.type in excution:
excution[self.userContext.type]()
return
self.recordAndReply(ViewFactory.Console(self.getConsoleArgument()))
finally:
self.userService.setContext(self.userId, self.responseContext)
def getConsoleArgument(self):
return ConsoleArgument(
self.gameId,
self.userName,
self.userService.getBalance(self.userId),
self.gameService.getGameLogs(self.gameId))
def replyConsole(self):
if self.userService.isLastMessage(self.userId, self.data.messageId):
self.recordAndReply(ViewFactory.Console(self.getConsoleArgument()))
def replyLeaveConfirm(self):
self.recordAndReply(ViewFactory.leaveConfirm(self.getConsoleArgument()))
def leaveGame(self):
if self.userService.isLastMessage(self.userId, self.data.messageId):
self.recordAndReply(ViewFactory.leavedGame())
self.removeUserData()
def askEarnAmount(self):
self.recordAndReply(ViewFactory.askAmount(self.getConsoleArgument(), "領取"))
self.responseContext = UserContext(UserContextType.Earn)
def askPayAmount(self):
self.recordAndReply(ViewFactory.askAmount(self.getConsoleArgument(), "繳交"))
self.responseContext = UserContext(UserContextType.Pay)
def askTransferTarget(self):
players = {}
for memberId in self.gameService.getOtherMembers(self.gameId, self.userId):
players[memberId] = self.getUserName(memberId)
if len(players) < 1:
self.recordAndReply(ViewFactory.Console(
self.getConsoleArgument(), text="這場遊戲還沒有其他玩家喔~\n快邀請朋友加入吧!"))
else:
self.recordAndReply(ViewFactory.askTransferTarget(self.getConsoleArgument(), players))
def askTransferAmount(self):
if self.userService.isLastMessage(self.userId, self.data.messageId):
self.recordAndReply(ViewFactory.askAmount(self.getConsoleArgument(), f"匯給 {self.getUserName(self.data.params)} "))
self.responseContext = UserContext(UserContextType.TransferAmount, self.data.params)
def drawChanceCard(self):
cardService = ChanceService(self._db)
if self.data.params == None:
cardViewFunc = cardService.draw(self.gameId)
self.recordAndReply(cardViewFunc(self.getConsoleArgument()))
elif self.userService.isLastMessage(self.userId, self.data.messageId):
cardService.excuteCard(self)
def drawDestinyCard(self):
cardService = DestinyService(self._db)
if self.data.params == None:
cardViewFunc = cardService.draw(self.gameId)
self.recordAndReply(cardViewFunc(self.getConsoleArgument()))
else:
if self.userService.isLastMessage(self.userId, self.data.messageId):
cardService.excuteCard(self)
def rollback(self):
if self.userService.isLastMessage(self.userId, self.data.messageId):
gameLog = self.gameService.getGameLog(self.gameId, self.data.params["gameLogId"])
if not gameLog.canceled:
if gameLog.action == GameLogAction.Transfer:
params = json.loads(gameLog.value)
self.userService.addBalance(params["from"], params["amount"])
self.userService.addBalance(params["to"], params["amount"] * -1)
else:
self.userService.addBalance(self.userId,
gameLog.value * (-1 if gameLog.action == GameLogAction.Earn else 1))
self.gameService.rollbackGameLog(self.gameId, gameLog.id)
self.recordAndReply(ViewFactory.Console(self.getConsoleArgument(), text="撤銷成功~"))
def earn(self):
try:
if not isinstance(self.event, MessageEvent) or not isinstance(self.event.message, TextMessage):
raise ArgumentError(None, "")
amount = int(self.event.message.text)
if amount <= 0:
raise ArgumentError(None, "")
self.userService.addBalance(self.userId, amount)
gameLog = GameLog(self.userName, f"領取了 ${amount}", GameLogAction.Earn, amount)
self.gameService.AddGameLog(self.gameId, gameLog)
self.recordAndReply(ViewFactory.OperateSuccess(
self.getConsoleArgument(), f"操作成功~\n您領取了 ${amount}", gameLog.id))
except (ArgumentError, ValueError):
self.recordAndReply(ViewFactory.inputError(self.getConsoleArgument()))
self.responseContext = self.userContext
def pay(self):
try:
if not isinstance(self.event, MessageEvent) or not isinstance(self.event.message, TextMessage):
raise ArgumentError(None, "")
amount = int(self.event.message.text)
if amount < 1 or amount > self.userService.getBalance(self.userId):
raise ArgumentError(None, "")
self.userService.addBalance(self.userId, amount * -1)
gameLog = GameLog(self.userName, f"繳納了 ${amount}", GameLogAction.Pay, amount)
self.gameService.AddGameLog(self.gameId, gameLog)
self.recordAndReply(ViewFactory.OperateSuccess(
self.getConsoleArgument(), f"操作成功~\n您繳納了 ${amount}", gameLog.id))
except (ArgumentError, ValueError):
self.recordAndReply(ViewFactory.inputError(self.getConsoleArgument()))
self.responseContext = self.userContext
def transfer(self):
try:
if not isinstance(self.event, MessageEvent) or not isinstance(self.event.message, TextMessage):
raise ArgumentError(None, "")
amount = int(self.event.message.text)
balance = self.userService.getBalance(self.userId)
if amount <= 0 or amount > balance:
raise ArgumentError(None, "")
self.userService.addBalance(self.userContext.params, amount)
self.userService.addBalance(self.userId, amount * -1)
toPlayerName = self.getUserName(self.userContext.params)
gameLog = GameLog(self.userName,
f"匯款給 {toPlayerName} ${amount}",
GameLogAction.Transfer,
json.dumps(
{"from": self.userId, "to": self.userContext.params,
"amount": amount},
separators=(',', ':')))
self.gameService.AddGameLog(self.gameId, gameLog)
self.recordAndReply(ViewFactory.OperateSuccess(
self.getConsoleArgument(), f"操作成功~\n您匯了 ${amount} 給 {toPlayerName}", gameLog.id))
except (ArgumentError, ValueError) as ex:
self.recordAndReply(ViewFactory.inputError(self.getConsoleArgument()))
self.responseContext = self.userContext