-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
1478 lines (1275 loc) · 49.1 KB
/
server.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
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
import ast
import difflib
import hashlib
import json
import math
import os
import py_compile
import random
import re
import string
import subprocess
import sys
import time
import urllib
import urlparse
import web
import web.form
import pygments
import pygments.lexers
import pygments.lexers.text
import pygments.formatters
import dbcon
import matchstate as ms
import shorten
import tools
import tplib
from rgkit.settings import settings
web.config.debug = False
CHALLENGES_LIMITS = 25
ROBOTS_LIMITS = 3
MAX_NAME_LENGTH = 25
BOT_LIMIT_REACHED_MSG = '''
Currently you can have at most {0} active robots. Disabling old bots will
allow you to create new ones. Otherwise, please create a post in the Requests
board of our community to increase your limit. It's
very easy, please don't abuse the simple registration system and
create multiple users.'''
urls = (
'/viewrobot/(\d*)', 'PageRedirectViewRobot',
'/viewuser/(\d*)', 'PageRedirectViewUser',
'/robotsource/(\d*)', 'PageRedirectRobotSource',
'/', 'PageHome',
'/directory', 'PageDirectory',
'/home', 'PageHome',
'/login', 'PageLogin',
'/logout', 'PageLogout',
'/matchlist', 'PageMatchList',
'/match/(\d*)', 'PageMatch',
'/moderate', 'PageModerate',
'/moderate/(\d*)', 'PageModerate',
'/profile/edit', 'PageProfile',
'/reg', 'PageRegister',
'/robots', 'PageRobots',
'/robot/(\d*)', 'PageViewRobot',
'/robot/(\d*)/against/(\d*)', 'PageRobotHistory',
'/robot/(\d*)/challenge', 'PageChallengeRobot',
'/robot/(\d*)/challenge/(\d*)', 'PageChallengeRobot',
'/robot/(\d*)/challenge/(\d*)/(\d*)', 'PageChallengeRobot',
'/robot/(\d*)/charts', 'PageRobotCharts',
'/robot/(\d*)/delete', 'PageDeleteRobot',
'/robot/(\d*)/disable', 'PageDisableRobot',
'/robot/(\d*)/history', 'PageRobotHistory',
'/robot/(\d*)/(edit)', 'PageEditRobot',
'/robot/(\d*)/edit/mode/(normal)', 'PageSwitchEditMode',
'/robot/(\d*)/edit/mode/(vim)', 'PageSwitchEditMode',
'/robot/(\d*)/edit/(vim)', 'PageEditRobot',
'/robot/(\d*)/enable', 'PageEnableRobot',
'/robot/(\d*)/source', 'PageRobotSource',
'/robot/(\d*)/test', 'PageRobotTest',
'/robot/new', 'PageNewRobot',
'/robot/new(acc)', 'PageNewRobot',
'/robot/stats', 'PageRobotStats',
'/stats', 'PageStats',
'/update/prefs', 'PageUpdatePrefs',
'/user/(\d*)', 'PageViewUser',
# static pages
'/(api)', 'PageStatic',
'/(compdir)', 'PageStatic',
'/(credits)', 'PageStatic',
'/(email)', 'PageStatic',
'/(faq)', 'PageStatic',
'/(gettingstarted)', 'PageStatic',
'/(kit)', 'PageStatic',
'/(moreexamples)', 'PageStatic',
'/(namerules)', 'PageStatic',
'/(rgdocs)', 'PageStatic',
'/(rules)', 'PageStatic',
'/(security)', 'PageStatic',
)
app = web.application(urls, globals())
def debuggable_session(app):
if web.config.get('_sess') is None:
sess = web.session.Session(app, web.session.DiskStore('sessions'))
web.config._sess = sess
return sess
return web.config._sess
sess = debuggable_session(app)
def hash(data):
return hashlib.sha1(data).hexdigest()
def generate_salt(length=10):
random.seed()
pool = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(pool) for i in range(length))
def logged_in(sess):
if 'logged_in' in sess:
if sess.logged_in:
if sess.user_id:
db.update('users', where='id=$id', vars={'id': sess.user_id},
last_active=int(time.time()))
# Change this to manual swap when added
db.update('robots', where='user_id=$id',
vars={'id': sess.user_id}, automatch=True)
return sess.user_id
return False
def force_login(sess, page='/reg', check_logged_in=False):
user_id = logged_in(sess)
if check_logged_in:
# Redirect if logged in
if user_id:
raise web.seeother(page)
else:
# Redirect if not logged in
if not user_id:
raise web.seeother(page)
return user_id
def username_exists(username):
result = db.select('users',
what='1',
where='username=$username',
vars={'username': username},
limit=1)
return bool(result)
def create_user(username, password, **params):
pw_hash = hash(password)
pw_salt = generate_salt()
pw_hash = hash(pw_hash+pw_salt)
return db.insert('users', username=username, pw_hash=pw_hash, pw_salt=pw_salt, **params)
def authenticate_user(username, password):
users = db.select('users', where='username = $username', vars={'username': username},
what='id, pw_hash, pw_salt')
if not users:
return False
user = users[0]
if hash(hash(password) + user['pw_salt']) == user['pw_hash']:
return user['id']
return False
def login_user(sess, user_id):
if logged_in(sess):
return False
sess.logged_in = True
sess.user_id = user_id
return True
def logout_user(sess):
sess.kill()
def template_closure(directory):
global settings
templates = web.template.render(directory,
globals={
'sess': sess,
'settings': settings,
'tplib': tplib})
def render(name, *params, **kwargs):
return getattr(templates, name)(*params, **kwargs)
return render
tpl = template_closure('t/')
def ltpl(*params, **kwargs):
return tpl('layout', tpl(*params, **kwargs))
def lmsg(msg):
return tpl('layout', '<div class="prose">{0}</div>'.format(msg))
db = dbcon.connect_db()
######################
def encode_history_json(hist):
hist = json.dumps(hist)
hist = 'replay_callback({0});'.format(hist)
return hist.encode('base64')
def get_match_data(mid):
history_data = db.select('history', what='data', where='match_id=$id',
vars={'id': mid})
if history_data:
data = history_data[0]['data']
if data:
data = shorten.loads(data)
data['history'] = encode_history_json(data['history'])
return data
return None
def get_last_matches(num, min_rating=None):
mr = ''
if min_rating:
mr = ' and r1.rating >= $r and r2.rating >= $r'
query = '''
select
matches.*,
r1.compiled_code as r1_code, r2.compiled_code as r2_code,
r1.name as r1_name, r2.name as r2_name
from matches
join robots r1 on r1.id = matches.r1_id
join robots r2 on r2.id = matches.r2_id
where state = {0} {1}
order by timestamp desc
limit $num'''.format(ms.DONE, mr)
matches = db.query(query, vars={'num': num, 'r': min_rating})
return matches if matches else None
def get_latest_match(min_rating=None):
matches = get_last_matches(1, min_rating)
if matches:
return matches[0]
return None
class PageHome:
def GET(self):
if logged_in(sess):
return ltpl('home')
rating = 3000.0
match = get_latest_match(rating)
if match:
match.data = get_match_data(match['id'])
recent = get_last_matches(5, rating)
return ltpl('home', match, recent)
class PageLogin:
_form = web.form.Form(
web.form.Textbox('username', description='Username'),
web.form.Password('password', description='Password'),
web.form.Button('Login')
)
def GET(self):
force_login(sess, '/robots', True)
form = self._form()
return ltpl('login', form)
def POST(self):
form = self._form()
if not form.validates():
return 'bad input'
if not form.d.username or not form.d.password:
return 'you have to enter a username and password'
user_id = authenticate_user(form.d.username, form.d.password)
if not user_id:
return 'couldn\'t authenticate user'
login_user(sess, user_id)
raise web.seeother('/robots')
class PageRegister:
_form = web.form.Form(
web.form.Textbox('username', description='Username'),
web.form.Password('password', description='Password'),
web.form.Button('Register')
)
def GET(self):
force_login(sess, '/robots', True)
form = self._form()
return ltpl('reg', form)
def POST(self):
form = self._form()
if not form.validates():
return 'bad input'
if not form.d.username or not form.d.password:
return 'you have to enter a username and password'
if username_exists(form.d.username):
return 'username already exists'
user_id = create_user(form.d.username, form.d.password)
if not user_id:
return 'couldn\'t create user'
login_user(sess, user_id)
raise web.seeother('/robot/new')
class PageLogout:
def GET(self):
logout_user(sess)
raise web.seeother('/')
class PageRobots:
def GET(self):
force_login(sess)
query = '''
select *,
(select count(*) from robots r where compiled and passed and
not disabled and r.rating > robots.rating + 1e-5) as ranking
from robots
where user_id = $user_id and not deleted and
disabled = $disabled
order by rating desc nulls last'''
robots = db.query(
query, vars={'user_id': sess.user_id, 'disabled': False})
disabled_robots = db.query(
query, vars={'user_id': sess.user_id, 'disabled': True})
return ltpl('robots', robots, disabled_robots)
def check_name(s):
for ch in s:
if ch in string.printable and ch not in string.whitespace:
return True
return False
def count_robots(user_id):
result = db.select(
'robots', what='count(*)',
where='user_id=$user_id and not disabled',
vars={'user_id': user_id})
return result[0]['count'] if result else None
class PageNewRobot:
_form = web.form.Form(
web.form.Textbox('name'))
def GET(self, new_acc=None):
force_login(sess)
robot_count = count_robots(sess.user_id)
user = db.select('users', what='extra_bots', where='id=$id',
vars={'id': sess.user_id})
robot_limit = ROBOTS_LIMITS
if user:
robot_limit += user[0]['extra_bots']
if robot_count >= robot_limit:
return lmsg(BOT_LIMIT_REACHED_MSG.format(robot_limit))
top_robots = list(db.select('robots',
what='id, name, rating, open_source',
where='compiled and passed and not disabled and rating is not NULL',
order='rating desc',
limit=6))
return ltpl('newrobot', bool(new_acc), top_robots)
def POST(self, new_acc=None):
force_login(sess)
robot_count = count_robots(sess.user_id)
user = db.select('users', what='extra_bots', where='id=$id',
vars={'id': sess.user_id})
robot_limit = ROBOTS_LIMITS
if user:
robot_limit += user[0]['extra_bots']
if robot_count >= robot_limit:
return lmsg(BOT_LIMIT_REACHED_MSG.format(robot_limit))
form = self._form()
if not form.validates():
return 'bad input'
form.d.name = form.d.name.strip()
if not form.d.name:
return lmsg('You have to enter a name.')
if not check_name(form.d.name):
return lmsg('Please have at least one printable, non-whitespace ASCII character in your name.')
if len(form.d.name) > MAX_NAME_LENGTH:
return lmsg(
'Please limit your name to {0} characters.'.format(
MAX_NAME_LENGTH))
code = '''import rg
class Robot:
def act(self, game):
# return something
pass'''
rid = db.insert('robots',
user_id=sess.user_id,
name=form.d.name,
code=code)
raise web.seeother('/robot/{0}/edit'.format(rid))
def get_robot(rid, check_user_id=True):
where = 'id=$id'
vars = {'id': rid}
if check_user_id and not tplib.is_admin(sess):
where += ' and user_id=$user_id'
vars['user_id'] = sess.user_id
result = db.select('robots', where=where, vars=vars)
return result[0] if result else None
class PageSwitchEditMode:
def GET(self, rid, edit_mode):
if edit_mode == 'vim':
web.setcookie('vim', 'yes', 480984220)
raise web.seeother('/robot/' + rid + '/edit/vim')
web.setcookie('vim', 'no', -1)
raise web.seeother('/robot/' + rid + '/edit')
class PageEditRobot:
_form = web.form.Form(
web.form.Textbox('name'),
web.form.Textarea('code'),
web.form.Checkbox('open_source'),
web.form.Button('save'))
def first_time(self):
result = db.select('robots',
what='count(*)',
where='compiled and user_id = $user_id',
vars={'user_id': sess.user_id})
if result and result[0]['count'] == 0:
return True
user = db.select('users',
what='registered_on',
where='id = $id',
vars={'id': sess.user_id})
if user and time.time() - user[0]['registered_on'] < tools.DAY:
return True
return False
def GET(self, rid, edit_mode):
force_login(sess)
vim_cookie = web.cookies().get('vim')
if vim_cookie == 'yes' and edit_mode != 'vim':
raise web.seeother('/robot/' + rid + '/edit/vim')
if vim_cookie == 'no' and edit_mode == 'vim':
raise web.seeother('/robot/' + rid + '/edit')
rid = int(rid)
robot = get_robot(rid)
if not robot:
return lmsg('That robot does not exist.')
first = self.first_time()
db.update('robots',
where='id=$id',
vars={'id': rid},
saved=False)
return ltpl('editrobot', robot, edit_mode == 'vim', first)
def POST(self, rid, edit_mode):
force_login(sess)
rid = int(rid)
robot = get_robot(rid)
if not robot:
return lmsg('Robot does not exist.')
form = self._form(robot)
if not form.validates():
return lmsg('Bad input.')
form.d.name = form.d.name.strip()
if not form.d.name:
return lmsg('You have to enter a name.')
if not check_name(form.d.name):
return lmsg('Please have at least one printable and ' +
'non-whitespace ASCII character in your name.')
if len(form.d.name) > MAX_NAME_LENGTH:
return lmsg(
'Please limit your name to {0} characters.'.format(
MAX_NAME_LENGTH))
if len(form.d.code) > 250000:
return lmsg('Please limit your code to 250,000 characters.')
robot_code = form.d.code
db.update('robots',
where='id=$id',
vars={'id': rid},
name=form.d.name,
code=robot_code,
open_source=form.d.open_source)
robot = get_robot(rid)
if not robot:
return lmsg('Robot does not exist.')
compiled_code = robot_code
if robot.rating is not None:
rating = robot.rating
else:
rating = settings.default_rating
db.update('robots',
where='id=$id',
vars={'id': rid},
last_updated=int(time.time()),
last_rating=rating,
compiled_code=compiled_code,
changed_since_sbtest=True,
saved=True,
passed=True,
compiled=True)
raise web.seeother('/robot/{0}/edit'.format(robot.id))
MATCHES_PER_PAGE = 20
class PageRedirectViewRobot:
def GET(self, rid):
raise web.redirect('/robot/{0}'.format(rid))
class PageRedirectViewUser:
def GET(self, uid):
raise web.redirect('/user/{0}'.format(uid))
class PageRedirectRobotSource:
def GET(self, rid):
raise web.redirect('/robot/{0}/source'.format(rid))
class PageViewRobot:
def get_robot(self, rid):
query = '''
select
robots.id, user_id, name, disabled, last_updated, deleted,
rating, users.about, open_source, priority, time,
length(compiled_code) as len, fast, short, winrate, automatch,
(select count(*) from robots r where compiled and passed and
not disabled and r.rating > robots.rating + 1e-5) as ranking
from robots
join users on users.id = robots.user_id
where robots.id = $id'''
robot = db.query(query, vars={'id': rid})
return robot[0] if robot else None
def GET(self, rid, against=None):
robot = self.get_robot(int(rid))
if not robot:
return lmsg('Robot not found.')
query = '''
select
matches.*,
r1.name as r1_name,
r2.name as r2_name
from matches
join robots r1 on r1.id = matches.r1_id
join robots r2 on r2.id = matches.r2_id
where (r1.id = $id or r2.id = $id)
and (state = {0} or state = {1})
order by matches.id desc
'''.format(ms.WAITING, ms.RUNNING)
next_matches = db.query(query, vars={'id': rid})
latest_match = get_latest_match()
query = '''
select
matches.*,
r1.name as r1_name,
r2.name as r2_name
from matches
join robots r1 on r1.id = matches.r1_id
join robots r2 on r2.id = matches.r2_id
where (r1_id = $id or r2_id = $id)
and (state = {0} or state = {1})
order by timestamp desc
LIMIT {2}
'''.format(ms.ERROR, ms.DONE, 5)
matches = db.query(
query, vars={'id': rid})
challenges = 0
if logged_in(sess):
result = db.select('users',
what='challenges',
where='id=$id',
vars={'id': sess.user_id})
if result:
challenges = CHALLENGES_LIMITS - result[0]['challenges']
return ltpl('viewrobot', robot, matches, next_matches,
latest_match.id if latest_match else None, challenges)
class PageRobotHistory:
def get_robot(self, rid):
query = '''
select
robots.id, user_id, name, disabled, last_updated, deleted,
rating, users.about, open_source, priority, time,
length(compiled_code) as len, fast, short, winrate, automatch,
(select count(*) from robots r where compiled and passed and
not disabled and r.rating > robots.rating + 1e-5) as ranking
from robots
join users on users.id = robots.user_id
where robots.id = $id'''
robot = db.query(query, vars={'id': rid})
return robot[0] if robot else None
def GET(self, rid, against=None):
robot = self.get_robot(int(rid))
if not robot:
return lmsg('Robot not found.')
opponent = None
if against is not None:
opponent = self.get_robot(int(against))
if not opponent:
return lmsg('Robot against not found.')
#robot.about = self.convert_links(robot.about)
params = web.input(page=None, ranked=None, per=None)
page = int(params.page or 0)
ranked = int(params.ranked or 0)
per = int(params.per or MATCHES_PER_PAGE)
if per > 200 and not tplib.is_admin(sess):
per = 200
ranked = 'and ranked' if ranked > 0 else 'and not ranked' if ranked < 0 else ''
if against is None:
query = '''
select
matches.*,
r1.name as r1_name,
r2.name as r2_name
from matches
join robots r1 on r1.id = matches.r1_id
join robots r2 on r2.id = matches.r2_id
where (r1_id = $id or r2_id = $id)
and (state = {0} or state = {1})
{3}
order by timestamp desc
limit {2}
offset $page'''.format(ms.ERROR, ms.DONE, per,
ranked)
matches = db.query(
query, vars={'id': rid, 'page': page * per})
else:
query = '''
select
matches.*,
r1.name as r1_name,
r2.name as r2_name
from matches
join robots r1 on r1.id = matches.r1_id
join robots r2 on r2.id = matches.r2_id
where ((r1_id = $id1 and r2_id = $id2) or
(r1_id = $id2 and r2_id = $id1))
and (state = {0} or state = {1})
{3}
order by timestamp desc
limit {2}
offset $page'''.format(ms.ERROR, ms.DONE, per,
ranked)
matches = db.query(
query,
vars={
'id1': rid,
'id2': against,
'page': page * per
})
return ltpl('robot_history', robot, matches, page, per, against,
params.ranked)
class PageViewUser:
def get_user_detailed(self, uid):
query = '''
select
*, coalesce(r.count, 0) as robot_count
from users
left join (
select
user_id as uid, count(*) as count
from robots
where not robots.disabled
group by user_id
) as r
on r.uid = users.id
where users.id = $id'''
user = db.query(query, vars={'id': uid})
return user[0] if user else None
def get_robots(self, uid, disabled=False):
query = '''
select
*,
(select count(*) from robots r where compiled and passed and
not disabled and r.rating > robots.rating + 1e-5) as ranking
from robots
where robots.user_id = $id and disabled = $disabled and not deleted
order by robots.rating desc nulls last
'''
robots = db.query(query, vars={'id': uid, 'disabled': disabled})
return robots if robots else []
def get_user(self, uid):
query = '''
select id, about, last_active, registered_on
from users
where id = $id'''
user = db.query(query, vars={'id': uid})
return user[0] if user else None
def GET(self, uid=None):
if uid is None or ('user_id' in sess and int(uid) == sess.user_id):
uid = force_login(sess)
user = self.get_user_detailed(int(uid))
user.robots_limit = ROBOTS_LIMITS + user.extra_bots
user.challenges_limit = CHALLENGES_LIMITS
else:
user = self.get_user(int(uid))
if not user:
return lmsg('User not found.')
robots = self.get_robots(int(uid))
disabled_robots = self.get_robots(int(uid), True)
return ltpl('viewuser', user, robots, disabled_robots)
def get_match(mid):
query = '''
select
matches.*,
r1.compiled_code as r1_code, r2.compiled_code as r2_code,
r1.name as r1_name, r2.name as r2_name
from matches
join robots r1 on r1.id = matches.r1_id
join robots r2 on r2.id = matches.r2_id
where matches.id = $id'''
match = db.query(query, vars={'id': mid})
return match[0] if match else None
def get_pending_matches():
query = '''
select
matches.*,
r1.compiled_code as r1_code, r2.compiled_code as r2_code,
r1.name as r1_name, r2.name as r2_name
from matches
join robots r1 on r1.id = matches.r1_id
join robots r2 on r2.id = matches.r2_id
where state = {0} and not ranked'''.format(ms.WAITING)
return db.query(query)
class PageChallengeRobot:
def match_running(self, rid, challenger):
result = db.select('matches',
what='id',
where='''
(r1_id = $id1 and r2_id = $id2 or
r1_id = $id2 and r2_id = $id1)
and (state = {0} or state = {1})
'''.format(ms.WAITING, ms.RUNNING),
vars={'id1': rid, 'id2': challenger})
return result[0].id if result else None
def eligible(self, rid):
result = db.select(
'robots', what='count(*)',
where='passed and compiled and not deleted and id=$id',
vars={'id': rid})
return result and result[0]['count'] > 0
def is_self(self, rid):
result = db.select('robots', what='user_id', where='id=$id', vars={'id': rid})
return (result and result[0]['user_id'] == sess.user_id)
def get_rating(self, rid):
result = db.select('robots', what='rating', where='id=$id', vars={'id': rid})
return result[0]['rating']
def limit_ok(self, user_id, num_matches):
result = db.select('users',
what='challenges',
where='id=$id',
vars={'id': user_id})
if result:
result = result[0]
return result['challenges'] + num_matches <= CHALLENGES_LIMITS
return False
def GET(self, rid, challenger=None, num_matches=None):
force_login(sess)
rid = int(rid)
if self.is_self(rid):
return lmsg('You can\'t challenge one of your own robots.')
if num_matches is None:
num_matches = 1
else:
num_matches = int(num_matches)
if not self.limit_ok(sess.user_id, num_matches):
return lmsg('''
You <a href="/profile"><b>don't have enough challenges</b></a>
left today! The counts are reset everyday at midnight EST.
<br/><br/>''')
if challenger is None:
robots = db.select(
'robots',
where='user_id=$id and compiled and passed and not deleted',
vars={'id':sess.user_id})
return ltpl('choosechallenge', rid, robots)
challenger = int(challenger)
if not self.is_self(challenger):
return lmsg('You can only challenge others with your robots.')
if not self.eligible(rid):
return lmsg('The enemy is not eligible to fight.')
if not self.eligible(challenger):
return lmsg('Your robot is not eligible to fight.')
# create match
for l in range(num_matches):
if random.random() < 0.5:
match_id = db.insert(
'matches', r1_id=rid, r2_id=challenger,
ranked=False, r1_rating=self.get_rating(rid),
r2_rating=self.get_rating(challenger),
seed=random.randint(1, settings.max_seed))
else:
match_id = db.insert(
'matches', r2_id=rid, r1_id=challenger,
ranked=False, r2_rating=self.get_rating(rid),
r1_rating=self.get_rating(challenger),
seed=random.randint(1, settings.max_seed))
# add to user's challenges count
db.query('UPDATE users SET challenges=challenges+$c WHERE id=$id',
vars={'id': sess.user_id, 'c': num_matches})
if num_matches == 1:
raise web.seeother('/match/{0}'.format(match_id))
else:
raise web.seeother('/robot/{0}'.format(rid))
class PageMatchList:
def GET(self):
recent = get_last_matches(100)
query = '''
select
matches.*,
r1.name as r1_name,
r2.name as r2_name
from matches
join robots r1 on r1.id = matches.r1_id
join robots r2 on r2.id = matches.r2_id
where (state = {0} or state = {1})
order by matches.id desc
'''.format(ms.WAITING, ms.RUNNING)
next_matches = db.query(query)
return ltpl('matchlist', recent, next_matches)
class PageMatch:
def GET(self, mid):
match = get_match(int(mid))
if not match:
return 'match not found'
match.data = get_match_data(match['id'])
has_match_log = time.time() - match.timestamp < tools.WEEK
return ltpl('match', match, has_match_log)
class PageStatic:
def GET(self, page):
return ltpl(page)
PER_PAGE = 20
class PageDirectory:
def get_ranking(self, rating, where=''):
if rating is None:
count = db.select('robots',
what='count(*)',
where='''compiled and passed and not disabled
and rating is not NULL {0}'''.format(where))
else:
count = db.select('robots',
what='count(*)',
where='''compiled and passed and not disabled
and rating > $rating + 1e-5 {0}'''.format(where),
vars={'rating': rating})
return count[0]['count'] if count else None
def GET(self):
params = web.input(upper=None, page=None, latest=None, os=None,
diff=None, pri=None, viewactive=None, fast=None,
time=None, short=None, disabled=None, tlimit=None,
win=None, per=None)
params.diff = int(params.diff or 0)
if params.latest:
order = 'last_updated desc'
elif params.diff > 0:
order = 'rating-last_rating desc nulls last'
elif params.diff < 0:
order = 'rating-last_rating asc nulls first'
elif params.pri:
order = 'priority desc'
elif params.time:
order = 'time desc'
elif params.win:
order = 'winrate ' + ('desc' if int(params.win) > 0 else 'asc')
else:
order = 'rating desc nulls last'
per = int(params.per or PER_PAGE)
if per > 200 and not tplib.is_admin(sess):
per = 200
os_where = ' and not disabled' if not params.disabled else ''
os_where += ' and open_source' if params.os else ''
os_where += ' and automatch' if params.viewactive else ''
t = 2 if not params.tlimit else float(params.tlimit)
os_where += ' and time < {0}'.format(t) if params.fast else ''
os_where += ' and length(compiled_code) < 1000' if params.short else ''
page = int(params.page or 0)
os_what = '''id, user_id, name, rating, open_source, automatch,
last_updated, last_rating, fast, short, winrate'''
if params.upper == '':
upper = None
robots = list(db.select('robots',
what=os_what,
where='''compiled and rating is NULL and passed
and not deleted {0}'''.format(os_where),
order=order,
limit=per,
offset=page*per,
vars=locals()))
else:
if params.upper is None and 'logged_in' in sess and sess.user_id:
my_robots = list(db.select('robots',
what='rating',
where='''compiled and rating is not NULL and passed
and not deleted and user_id=$user_id
{0}'''.format(os_where),
order=order,
vars={'user_id': sess.user_id}))
if not my_robots:
top_rating = settings.default_rating
else:
top_rating = my_robots[0].rating
my_rank = self.get_ranking(top_rating, os_where)
goal_rank = max(0, my_rank - (per - 1) / 2)
#print top_rating, my_rank, goal_rank
left, right = int(top_rating), 10000
while left < right:
#print left, right
mid = (left + right + 1) / 2
cur_rank = self.get_ranking(mid, os_where)
if cur_rank > goal_rank:
left = mid
elif cur_rank < goal_rank:
right = mid - 1
else:
left = mid
break
upper = left