Source

namethatanime / game / game.py

Full commit
  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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
from itertools import cycle
from player import Player
from song import Song
import traceback
from time import gmtime, strftime, sleep
import time
import threading
import random
import sys
from tornado.escape import json_decode
from database import db
from exce import ntae
import amonpy

TIMEOUT = 120
# Change method if you ever delete anime or somehow fix order
ANIME_TITLES = 239

class GameException(Exception): pass
class GameProcedureError(GameException): pass
class OutOfTurn(GameException): pass

class Anime(object):
    def __init__(self, title, id):
        self.title = title
        self.id = id
        
    def __repr__(self):
        return str(self.id) + ": " + self.title

# Thread dla pytania, czeka na wczytanie mp4 i odlicza do konca utworu
class TimeThread(threading.Thread):
    def __init__(self, game, delay, name):
        self.game = game
        self.delay = delay
        self._stop = threading.Event()
        super(TimeThread,self).__init__(name=name)

    def run(self):
        try:
            if (self.delay > 0 ):
                #Wysyla sygnal ze bedzie czekac
                self.game.broadcast("!de")
            sleep(self.delay)
            if self.game.ended:
                self.stop()
                return
            self.game.next_question()
            rdy = False
            while not rdy:
                if self.game.ended:
                    self.stop()
                    return
                rdy = True
                #self.game.broadcast("!rldebug")
                to_counter = 0
                for pl in self.game.players:
                    if not pl.songready and not pl.left:
                        print 'czekamy...'
                        rdy = False
                        to_counter = to_counter + 1
                        if (to_counter > TIMEOUT):
                            self.game.timeout = True
                            self.game.end_game()
                        if pl.socket:
                            if not pl.loading:
                                pl.socket.write_message("!l" + self.game.song)
                                pl.loading = True
                                #print 'zaczynamy wczytywanie'
                sleep(1)
            self.game.waiting = False
            self.game.starttime = int(strftime("%S", gmtime()))  
            self.game.broadcast("!gs")
            i = 0  
            while i < 30 and not self._stop.isSet():
                sleep(1)
                i+=1
                self.game.currtime -= 1
                if (i % 3) == 0:
                    self.game.currpts -= 1
                if not self.game:
                    self.stop()
            for pl in self.game.players:
                if pl.answer == -1:
                    pl.answer = -2 # -2 means no answer
                    pl.anstime = 0
                    pl.anspts = 0
            self.game.check_q_end()
        except Exception, e:
            print e
            ntae.process_exception(e, {'test':'1'})

    def stop (self):
        self._stop.set()

    def stopped (self):
        return self._stop.isSet()

class GameStartThread(threading.Thread):
    def __init__(self, game, delay, name):
        self.game = game
        self.delay = delay
        self._stop = threading.Event()
        super(GameStartThread,self).__init__(name=name)
        
    def run(self):
        sleep(self.delay)
        rdy = False
        to_counter = 0
        while not rdy:
            if self.game.ended:
                self.stop()
                return
            rdy = True
            if self.game.players:
                for pl in self.game.players:
                    if not pl.ready:
                        to_counter = to_counter + 1
                        if (to_counter > TIMEOUT):
                            self.game.timeout = True
                            self.game.end_game()
                        rdy = False
                        #print 'player not ready...'
                        #self.game.broadcast("Player %s is not ready" % pl.name)
            else:
                #print "nie ma graczy"
                self.stop()
                return
            sleep(1)
        #print 'game start'
        self.game.start_game()
        
    def stop (self):
        self._stop.set()

    def stopped (self):
        return self._stop.isSet()
    
class EndGameThread(threading.Thread):
    def __init__(self, game, delay, name):
        self.game = game
        self.delay = delay
        self._stop = threading.Event()
        super(EndGameThread,self).__init__(name=name)
        
    def run(self):
        sleep(self.delay)
        self.game.end_game()
    
class NextRoundThread(threading.Thread):
    def __init__(self, game, delay, name):
        self.game = game
        self.delay = delay
        self._stop = threading.Event()
        super(NextRoundThread,self).__init__(name=name)
        
    def run(self):
        sleep(self.delay)
        rdy = False
        to_counter = 0
        while not rdy:
            if self.game.ended:
                self.stop()
                return
            rdy = True
            if self.game.players:
                for pl in self.game.players:
                    if not pl.ready:
                        to_counter = to_counter + 1
                        if (to_counter > TIMEOUT):
                            self.game.end_game()
                            self.game.timeout = True
                        rdy = False
                        #self.game.broadcast("Player %s is not ready" % pl.name)
            else:
                #print "nie ma graczy"
                self.stop()
                return
            sleep(1)
        self.game.next_round()
        
    def stop (self):
        self._stop.set()

    def stopped (self):
        return self._stop.isSet()

def message(expected_arguments):
    def wrap(method):
        def wrapper(self, player, message):
            try:
                if self.state != method.__name__:
                    raise GameProcedureError('Not currently in the state: %s!' % method.__name__)
                if not isinstance(message, expected_arguments):
                    raise GameProcedureError('Expected different %s but got %s' % (str(type(expected_arguments)), str(type(message))))
                self.response = ''
                method(self, player, message)
                self.send(self.response)
            except Exception, e:
                ntae.process_exception(e, {'test':'1'})
                if hasattr(player, 'socket'):
                    player.socket.write_message(str(e))
                else:
                    raise e
        wrapper.__name__ = method.__name__
        return wrapper
    return wrap

class Question(object):
    def __init__(self, answer, allansw):
        self.correct = answer
        self.anspos = -1
        self.allansw = allansw
        for i in range(len(allansw)):
            if allansw[i].title == self.correct:
                self.anspos = i

class Game(object):
    def __init__(self, len, diff, ranked=True):
        self.players = []
        self.number_of_players = 1
        self.diff = diff
        if len == 0:
            self.rtotal = 2
            self.qtotal = 6
            self.length = "Short"
        elif len == 1:
            self.rtotal = 3
            self.qtotal = 7
            self.length = "Medium"
        elif len == 2:
            self.rtotal = 3
            self.qtotal = 12
            self.length = "Long"
        if diff == 0:
            self.qlen = 3
        elif diff == 1:
            self.qlen = 4
        elif diff == 2:
            self.qlen = 5
        self.round = 0
        self.rresults = []
        self.qdone = -1
        self.qend = False
        self.currentq = 0
        self.currtime = 30
        self.currpts = 10
        self.song = None
        self.songid = -1
        self.waiting = True
        self.ended = False
        self.questions = None
        self.lastsong = None
        self.state = 'add_player'
        self.starttime = 0
        self.sqlid = 0
        self.sqlroundid = 0
        self.sqlquestid = 0
        self.qthread = None
        self.ranked = ranked
        self.allansw = False #If all players answered
        self.timeout = False
        self.player_factory = Player
        self.templates = {'question' : 'question.html',
                          'points': 'points.html',
                          'lastsong': 'lastsong.html'}
        self.player_template = 'player.html'
        self.score = []
    
    def qoffset(self):
        return (self.round - 1)*self.qtotal

    @message(Player)
    def add_player(self, _, player):
        self.players.append(player)
        #self.broadcast(u'%s joined'.encode('utf-8') % player)
        self.broadcast("!rlpoints")
        if len(self.players) >= self.number_of_players:
            self.qthread  = GameStartThread(self, 0, name = "GameStartThread-%d" % (id(self)))
            self.qthread.start()

    def start_game(self):
        random.seed(self)
        self.round = 1            
        self.rresults.append([0]*self.number_of_players)
        self.state = 'round'            
        if self.ranked:
            ## Log new game and new round
            try:            
                addlog = "INSERT INTO namethatanime_gamelog (start_date, gtype, rounds, questions, diff) VALUES (CURRENT_TIMESTAMP,'0','%s', '%s', '%s') RETURNING id"
                self.sqlid = db.get(addlog, (self.rtotal, self.qtotal, self.diff,)).id
                for pl in self.players:
                    addlog = "INSERT INTO namethatanime_usergames (user_id, game_id) VALUES ('%s', '%s')"
                    db.execute(addlog, (pl.id, self.sqlid,))
                addlog = "INSERT INTO namethatanime_roundlog (game_id, start_date, rtype) VALUES ('%s', CURRENT_TIMESTAMP, 'None') RETURNING id"          
                self.sqlroundid = db.get(addlog, (self.sqlid,)).id
                # Generate song list       
                if self.players[0].banned:  
                    banned = str(json_decode(self.players[0].banned)).replace('u\'', '\'').replace('[', '(').replace(']', ')').replace('\'', '')
                else:
                    banned = None
                banque = ''
                if banned and len(banned) > 2:
                    banque = 'WHERE t2.id NOT IN %s ' % banned
                questr = "SELECT t1.id, t1.sfile, t2.title AS anime, t2.id as anime_id FROM namethatanime_song AS t1 INNER JOIN namethatanime_anime AS t2 ON t1.anime_id = t2.id " + banque + "ORDER BY random() LIMIT %s"
                self.questions = db.query(questr, (self.qtotal*self.rtotal,))
            except Exception, e:
                print e
                ntae.process_exception(e, {'test':'1'})                
        else:
            # Not ranked, just random songs
            questr = "SELECT t1.id, t1.sfile, t2.title AS anime, t2.id as anime_id FROM namethatanime_song AS t1 INNER JOIN namethatanime_anime AS t2 ON t1.anime_id = t2.id ORDER BY random() LIMIT %s"
            self.questions = db.query(questr, (self.qtotal*self.rtotal,))
        self.qthread  = TimeThread(self, 0, name = "Thread-%d" % (id(self)))
        self.qthread.start()

    def check_q_end(self):
        self.allansw = True
        for pl in self.players:
            if pl.answer == -1:
                self.allansw = False
        if self.allansw and not self.qend:
            self.qend = True
            if self.qthread != None:
                self.qthread.stop()
            self.broadcast("!st")
            self.end_q()            
            self.broadcast("!rlpoints")
            if (self.ended):
                #print "nie rob pytan, koniec jest!"
                pass
            elif (self.qdone + 1 ) == self.qtotal:
                #print "koniec rundy!"
                if self.ranked:
                    db.execute("UPDATE namethatanime_roundlog SET end_date=CURRENT_TIMESTAMP WHERE id = %s", (self.sqlroundid,))
                if (self.round == self.rtotal):
                    self.broadcast("!ge")
                    ethread  = EndGameThread(self, 3, name = "Thread-%d" % (id(self)))
                    ethread.start()
                else:
                    self.broadcast("!rb")
                    for pl in self.players:
                        pl.ready = False
                    rthread  = NextRoundThread(self, 0, name = "Thread-%d" % (id(self)))
                    rthread.start()
            else:
                #print "wszyscy odpowiedzieli, robie nowy thread"
                self.qthread  = TimeThread(self, 4, name = "Thread-%d" % (id(self)))
                self.qthread.start()
            
    def end_q(self):      
        i = 0
        #print self.rresults
        querystring = '''SELECT 
        t1.id, t1.title as songtitle, t1.stype, t1.number, t1.year, t1.coverfile, t2.title AS anime, t2.mallink as an_mal 
        FROM namethatanime_song AS t1 
        INNER JOIN namethatanime_anime AS t2 ON t1.anime_id = t2.id 
        WHERE t1.id = %s'''
        que = db.get(querystring, (self.songid,))
        self.lastsong = Song(que.id, que.songtitle, que.stype, que.number, que.year, que.coverfile, que.anime, que.an_mal)
        self.lastsong.artists = db.query('SELECT name FROM namethatanime_artist WHERE id IN (SELECT artist_id FROM namethatanime_song_artist WHERE song_id = %s)', (self.songid,))
        for pl in self.players:           
            if pl.answer == self.currentq.anspos:
                pl.score += pl.anspts
                pl.total += pl.anspts
                pl.qcorrect += 1
                pl.currcorrect = True                
                self.rresults[self.round - 1][i] = pl.score
                if self.ranked:
                    try:
                        db.execute("UPDATE namethatanime_questionlog SET answer=%s, anstime=%s, points=%s, correct=TRUE WHERE id = %s", (pl.answer, pl.anstime, pl.anspts, pl.qid,))
                    except Exception, e:
                        ntae.process_exception(e, {'test':'1'})
                        print e
            else:
                if self.ranked:
                    try:    
                        db.execute("UPDATE namethatanime_questionlog SET answer=%s, anstime=%s, points=0, correct=FALSE WHERE id = %s", (pl.answer, pl.anstime, pl.qid,))
                    except Exception, e:
                        ntae.process_exception(e, {'test':'1'})
                        print e
            pl.qtotal += 1            
            i += 1

    def end_game(self):        
        ## Update game log
        if self.ranked:
            try:                              
                db.execute("UPDATE namethatanime_gamelog SET end_date=CURRENT_TIMESTAMP WHERE id = %s", (self.sqlid,))
                for pl in self.players:
                    db.execute("UPDATE namethatanime_usergames SET result=%s WHERE user_id = '%s' AND game_id = %s", (pl.total, pl.id, self.sqlid,))
            except Exception, e:
                ntae.process_exception(e, {'test':'1'})
                print e
        self.ended = True
        self.broadcast("!rlquestion")        
        #print "Ended game"
        #amonpy.log('Game ended %s' % str(id(self)), level='info')
            
    def next_round(self):
        #print "nowa runda...."
        if self.ranked:
            try:
                addlog = "INSERT INTO namethatanime_roundlog (game_id, start_date, rtype) VALUES ('%s', CURRENT_TIMESTAMP, '0') RETURNING id"
                self.sqlroundid = db.get(addlog, (self.sqlid,)).id
            except Exception, e:
                ntae.process_exception(e, {'test':'1'})
                print e
        self.qdone = -1
        self.round += 1
        self.rresults.append([0]*self.number_of_players)
        for pl in self.players:
            pl.score = 0
        self.qthread  = TimeThread(self, 0, name = "Thread-%d" % (id(self)))
        self.qthread.start()

    def next_question(self):
        self.qdone += 1
        self.qend = False
        for pl in self.players:
            pl.loading = False
            pl.songready = False
            pl.currcorrect = False
            pl.answer = -1
            pl.anstime = 0
            pl.anspts = 0       
        self.currtime = 30
        self.currpts = 10 
        # Choose random anime title different from correct answer
        #print self.questions
        #print type(self.questions[self.qdone + self.qoffset()])
        allansw = [Anime(self.questions[self.qdone + self.qoffset()].anime, self.questions[self.qdone + self.qoffset()].anime_id)]        
        used = set()
        if self.ranked and self.players[0].banned:
            for b in json_decode(self.players[0].banned):
                used.add(int(b))
        used.add(self.questions[self.qdone + self.qoffset()].anime_id)
        for i in range(self.qlen - 1):
            other = random.randint(1, ANIME_TITLES)
            while other in used:
                other = random.randint(1, ANIME_TITLES)
            used.add(other)
            try:
                title = db.get("SELECT title FROM namethatanime_anime WHERE id = %s", (other,)).title
            except Exception, e:
                ntae.process_exception(e, {'title':title, 'other': other})
            allansw.append(Anime(title, other))
        self.song = self.questions[self.qdone + self.qoffset()].sfile
        self.songid = self.questions[self.qdone + self.qoffset()].id
        allanswid = []                  
        random.shuffle(allansw)
        for a in allansw:
            allanswid.append(a.id) 
        if self.ranked:
            for pl in self.players:
                query = "INSERT INTO namethatanime_questionlog (game_id, round_id, song_id, anime_id, user_id, choices) VALUES (%s, %s, %s, %s, %s, %s) RETURNING id" 
                pl.qid = db.get(query, (self.sqlid, self.sqlroundid, self.questions[self.qdone + self.qoffset()].id, self.questions[self.qdone + self.qoffset()].anime_id, pl.id, str(allanswid),)).id
        self.currentq = Question(self.questions[self.qdone + self.qoffset()].anime, allansw)
        
    def player_quit(self, player):
        #self.broadcast(strftime("|%H:%M:%S| ", gmtime()) + "Player %s has left the game" % player)
        self.players.remove(player)

    def broadcast(self, message):
        if len(self.players) == 0:
            #print "nie ma nikogo, koncze gre z broadcasta przy msg: " + message
            if not self.ended:
                self.end_game()
            return
        try:
            for player in self.players:
                if player.socket and not player.left:
                    try:
                        player.socket.write_message(message)
                    except Exception, e:
                        self.players.remove(player)
                        if len(self.players) == 0:
                            self.end_game()
        except:
            traceback.print_exc()

            
    def send(self, message, recipient=None):
        if not recipient:
            for player in self.players:
                if hasattr(player, 'socket') and player.socket:
					try:
						player.socket.write_message(message)
					except IOError, e:
						ntae.process_exception(e, {'test':'1'})
						print "nie da sie pisac..."
        else:
            if hasattr(recipient, 'socket') and recipient.socket:
                recipient.socket.write_message(message)