-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrg.cgi
executable file
·2287 lines (1946 loc) · 70.7 KB
/
rg.cgi
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/env python3
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
#
# Copyright 2020 by Sony Corporation
#
# Author: Tim Bird <[email protected]> or <[email protected]>
#
# This is an implementation of the "red-green" trivia game, often
# used for the closing game session of the Embedded Linux Conference.
# This can be used as either a CGI script or a WSGI script.
#
# See "GAME DATA and state machine" below for a description of
# game data.
#
# Implementation notes:
# j in front of variable means "junk_" - something that is discarded
# and not used in the function
#
import sys
import os
import cgi
import re
import copy
import time
VERSION=(2, 1, 0)
# turn this on to show the game data in the admin view
# (for debugging)
show_data = False
user_show_data = False
data_dir = "/home/tbird/work/games/red-green/rgdata/"
user_dir = data_dir + "users/"
still_in_dir = data_dir + "still_in/"
still_in_backup = data_dir + "still_in_backup/"
# keep pages from automatically refreshing, while I'm debugging
rfile = data_dir + "suppress_refresh"
default_suppress_refresh = os.path.exists(rfile)
#default_suppress_refresh = True
def log_this(msg):
t = time.time()
tfrac = int((t - int(t))*100)
timestamp = time.strftime("%Y-%m-%d_%H:%M:%S.") + "%02d" % tfrac
with open(data_dir+"rg.log", "a", encoding="utf-8") as f:
f.write("[%s] %s\n" % (timestamp, msg))
# mode indicates whether we're doing a group play (with an admin game
# moderator) or just letting a single user run through the questions
# to get their own score.
# this has a significant effect on the game mechanics
SINGLE="single"
#default_mode = SINGLE
default_mode = "group"
# in single-player mode:
# question forms have a timeout
# each user has their own game data file to control game state
# each page must automatically drive to the next status
# start_trivia, and done are automatic
# declare_winners is not supported
# users are allowed to make state changes
# in multi-player
# administrator makes all game state changes
# STATUS consts
STILL_IN = "still-in"
OUT = "out"
# import the trivia data
if data_dir not in sys.path:
sys.path.append(data_dir)
from trivia import tdata
from rps import rps_data
game_file_pattern = "rgdata-([0-9][0-9][0-9]).txt"
game_file_fmt = "rgdata-%03d.txt"
winner_file_fmt = "winners-%02d.txt"
CGI_URL = "/cgi-bin/rg.cgi"
WSGI_URL = "/rg"
if os.path.isdir("/var/www/owncloud/red-green/images"):
IMAGE_URL = "/red-green/images"
else:
IMAGE_URL = "/images"
REFRESH_SECONDS = 2
# To login as administrator, use the url:
# http://localhost:8000/rg.cgi?user_id=admin-game-admin
# or enter: admin-game-admin, Real Name=Tim in the registration form
ADMIN_USER_ID = "admin-game-admin"
ADMIN_NAME = "Tim"
OBSERVER_USER_ID = "observer"
NOBODY_USER_ID = "nobody-not-logged-in"
# trivia.py provides the trivia data in the form of the 'tdata' dictionary
# Each entry is a list, with question_num as the key:
# This list has the following items:
# 0) question text
# 1) red answer text
# 2) green answer text
# 3) both answer text
# 4) answer code
# 5) answer text (explanation)
#
# The answer code can be "red", "green", or "both".
# The answer can consist of multiple answers (for fake-out or lenient questions)
# Multiple correct answers are separated by a vertical bar ('|')
# example: "red|green"
#
# {1: ["question #1", "true", "false", "" "red", "answer #1 because..."],
# 2: ["question #2", "less than 10", "10 or more", "", "green", "answer #2"],
# ...
# }
# rps.py provides the this will provide the 'rps_data' dictionary
# Each entry is a string with, round_num as the key:
# The host_throw can be "rock", "paper", or "scissors".
#
# {1: "rock",
# 2: "scissors",
# ...
# }
# GAME DATA and state machine
# The game has 4 phases:
# - registration (phase="registration")
# - red-green trivia (phase="trivia")
# - rock-paper-scissors (phase="rps")
# - done (phase="done")
#
# each question goes through a state machine:
# ask_question, wait_for_answer, show_answer
# for a player, the ask_question page has the question and a form
# when the player responds, they go to the "wait_for_answer" state
# the admin has a screen showing the number of players who have voted
# as well as the number of players "still-in"
# the state "wait_for_answer" is entered per-user
# everyone stays in the "wait_for_answer" state until the administrator
# changes the global state to "show_answer"
# In the show_answer state, user answers are checked, and their status is updated
# this writes a new status to their user file
#
# The game progresses as a series of rounds.
# within the trivia each round consists of several questions:
# for each question:
# players are presented with a question and a form to answer
# when players have answered, they sit on a "waiting" page
# when the administrator reveals the answer, each player sees their outcome
# when the administrator moves to the next question, each player sees the question page
# - a user is in one of 3 states: "question", "waiting", "answer"
# - the admin goes from "question" to "waiting"
# - the user goes from "question" to "waiting"
# - the admin goes from "waiting" to "answer"
# - the admin goes from "waiting" to "answer"
#
# there are two views of the game, the player view. If player_view=1,
# the the player_view is shown, an no actions are processed.
# if answer_to_show is not zero, then an answer is shown in player_view
#
# The player view automatically refreshes for certain pages,
# so as the game state changes, it should change without manual intervention.
#
# The admin screen allows changing the game state.
#
class data_class(object):
def __init__(self):
self.data = {}
self.html = []
self.err_msg_list = []
self.admin_view = False
self.is_observer = False
self.notice_list = []
self.suppress_refresh = default_suppress_refresh
self.refresh_count = REFRESH_SECONDS
self.is_form_page = False
self.header_shown = False
self.cookie = ""
self.resp_status = "200 OK"
self.resp_headers = [('Content-type', 'text/html')]
self.is_wsgi = False
self.url = CGI_URL
self.image_url = IMAGE_URL
self.rps_image_size = 80
self.mode = default_mode
self.user = None
# here is the game data
self.game_attr_list = ['sequence', 'winner_group', 'phase',
'state', 'question_num', 'round_num']
self.game_attr_ints = ['sequence', 'winner_group',
'question_num', 'round_num']
self.sequence = 0
self.winner_group = 0
self.phase = "registration" # registration, trivia, rps, done
self.state = "question" # question, wiating, answer, winners
# or, for rps: query, waiting, result, winners
self.question_num = 1
self.round_num = 1
self.game_file_mtime = 0
def set_data(self, new_data):
for key in list(new_data.__dict__.keys()):
if key in self.game_attr_list:
self.__dict__[key] = new_data.__dict__[key]
def __getitem__(self, key):
if key in self.data:
item = self.data[key]
elif hasattr(self, key):
item = getattr(self, key)
else:
raise KeyError
if callable(item):
return item(self)
else:
return item
def __setitem__(self, key, value):
self.data[key] = value
def has_key(self, key):
return key in self.data
def keys(self):
# FIXTHIS - are the __dict__ keys needed?
keys = list(self.__dict__.keys())
keys.extend(list(self.data.keys()))
return keys
######################################################
def html_append(self, html):
if isinstance(html, str):
self.html.append(html.encode("utf-8"))
else:
self.html.append(html)
def emit_html(self):
# trick to change encoding of sys.stdout to utf8
#import io
#sys.stdout = io.open(sys.stdout.fileno(), 'w', encoding='utf8')
for hline in self.html:
# uncomment this to enable debugging, via a custom log file
#log_this(hline)
# output each line as bytes
sys.stdout.buffer.write(hline)
self.html = []
def add_error_message(self, msg):
self.err_msg_list.append('<font color="red">ERROR: %s<br></font>' % msg)
# give time for user to see error
self.refresh_count = 10
def get_errors_as_html(self):
html = ""
if self.err_msg_list:
html += '<table bgcolor="pink"><tr><td>\n'
last_msg = self.err_msg_list[-1]
for msg in self.err_msg_list:
html += msg+"\n"
if msg != last_msg:
html += "<BR>\n"
html += '</td></tr></table>\n'
self.err_msg_list = []
return html
def add_notice(self, msg):
self.notice_list.append('<font color="green">NOTE: %s<br></font>' % msg)
def get_notices_as_html(self):
html = ""
if self.notice_list:
html += '<table bgcolor="lime"><tr><td>\n'
last_msg = self.notice_list[-1]
for msg in self.notice_list:
html += msg+"\n"
if msg != last_msg:
html += "<BR>\n"
html += '</td></tr></table>\n'
self.notice_list = []
return html
def debug_data(self):
d = self.__dict__.copy()
for attr in ["html", "err_msg_list", "notice_list", "game_attr_ints", "game_attr_list"]:
del d[attr]
return str(d)
######################################################
stub_data = data_class()
######################################################
class user_class(object):
def __init__(self, user_id, alias, name, email, status=STILL_IN):
self.user_id = user_id
self.alias = alias
self.name = name
self.email = email
# status can be STILL_IN or OUT
self.status = status
self.last_answer = ""
self.logged_in = False
def write_file(self):
line = "%s,%s,%s,%s,%s,%s\n" % (self.user_id, self.alias, self.name,
self.email, self.status,
self.last_answer)
user_filepath = user_dir + self.user_id
fd = open(user_filepath, "w", encoding="utf-8")
fd.write(line)
fd.close()
def save_answer(self, data, form, answer):
# make sure answer is for current question
if data.phase == "trivia":
try:
qnum = form["qnum"].value
except:
data.add_error_message("Question form missing 'qnum'")
qnum = 0
if int(qnum) != data.question_num:
data.add_error_message(
"Incorrect question num %s in form<br>" % qnum + \
"Discarding answer for this question. " + \
"Maybe you got behind in the game??")
return
if data.state != "question":
data.add_error_message(
"I'm sorry - you missed your opportunity to respond<br>" + \
"Discarding answer for this question. " + \
"Maybe you got behind in the game??")
return
elif data.phase == "rps":
try:
rnum = form["rnum"].value
except:
data.add_error_message("Question form missing 'rnum'")
rnum = 0
if int(rnum) != data.round_num:
data.add_error_message(
"Incorrect round num %s in form<br>" % rnum + \
"Discarding throw for this round. " + \
"Maybe you got behind in the game??")
return
if data.state != "query":
data.add_error_message(
"I'm sorry - you missed your opportunity to respond<br>" + \
"Discarding answer for this question. " + \
"Maybe you got behind in the game??")
return
else:
data.add_error_message(
"I'm sorry - you missed your opportunity to respond<br>" + \
"Discarding answer for this question. " + \
"Maybe the game is over or restarted??")
return
# put answer in user file (old method)
self.last_answer = answer
self.write_file()
# put answer in separate file (new method)
answer_dir = get_current_answer_dir(data)
if not os.path.isdir(answer_dir):
os.mkdir(answer_dir)
answer_filepath = answer_dir + "/" + self.user_id
try:
fd = open(answer_filepath, "w", encoding="utf-8")
fd.write(answer)
fd.close()
except:
data.add_error_message("could not write to answer file %s" % answer_filepath)
# FIXTHIS - user.save_status is unused
def save_status(self, data, status):
# put status in user file (old method)
user.status = status
self.write_file()
# still-in status is kept in a different directory (new method)
# remove still_in status if we're eliminated
status_filepath = still_in_dir + self.user_id
if status != STILL_IN and os.path.exists(status_filepath):
os.remove(status_filepath)
######################################################
def read_game_data_from_last_file(data):
# read from the last-numbered game-data file
file_list = os.listdir(data_dir)
max_sequence = -1
max_filename = "no-game-data-file"
for filename in file_list:
m = re.match(game_file_pattern, filename)
if m:
sequence = int(m.groups()[0])
if sequence > max_sequence:
max_sequence = sequence
max_filename = filename
if max_filename == "no-game-data-file":
return copy.deepcopy(stub_data)
last_game_filename = data_dir + max_filename
return read_game_data(data, last_game_filename)
######################################################
# FIXTHIS - may need to save off err_msg_list and html, in case
# they already have data
def read_game_data(data, game_filename):
try:
game_lines = open(game_filename, "r", encoding="utf-8").readlines()
except:
data.add_error_message("Warning: failed to open game data file: %s\n<p>\n" % game_filename)
game_lines = []
for line in game_lines:
line = line.strip()
if line and line[0] != '#':
(name, value) = line.split('=', 1)
if name in data.game_attr_list:
if name in data.game_attr_ints:
value = int(value)
setattr(data, name, value)
data.game_filename = game_filename
try:
data.game_file_mtime = os.path.getmtime(game_filename)
except:
data.game_file_mtime = time.time()
return data
######################################################
def write_game_data(data):
# write out file to next filename in sequence
# increment sequence number
data.sequence += 1
game_filename = data_dir + game_file_fmt % data.sequence
data.game_filename = game_filename
fd = open(game_filename, "w", encoding="utf-8")
klist = list(data.keys())
klist.sort()
for name in klist:
if name in data.game_attr_list:
fd.write("%s=%s\n" % (name, str(getattr(data, name))))
fd.close()
######################################################
def remove_undo_data_files():
# scan for game-data files
file_list = os.listdir(data_dir)
for filename in file_list:
m = re.match(game_file_pattern, filename)
if m:
target = data_dir + filename
os.unlink(target)
def reset_answers_and_users(data):
num_questions = len(tdata)
data.phase = "trivia"
for qnum in range(num_questions):
data.question_num = qnum
clear_current_answers(data)
num_rounds = len(rps_data)
data.phase = "rps"
for rnum in range(num_rounds):
data.round_num = rnum
clear_current_answers(data)
# erase all old still_in files
file_list = os.listdir(still_in_dir)
for f in file_list:
os.remove(still_in_dir + f)
make_all_users_still_in(data)
def get_registered_user_count():
return len(os.listdir(user_dir))
######################################################
# returns answer dir, or None if we're in the wrong phase
def get_current_answer_dir(data):
if data.phase == "trivia":
return data_dir + "trivia-q%d/" % (data.question_num)
elif data.phase == "rps":
return data_dir + "rps-r%d/" % (data.round_num)
else:
return None
######################################################
# returns (user_count, answer_count, still_in_count)
def get_status_counts(data):
file_list = os.listdir(user_dir)
user_count = len(file_list)
answer_dir = get_current_answer_dir(data)
if answer_dir and os.path.exists(answer_dir):
answer_count = len(os.listdir(answer_dir))
else:
answer_count = 0
still_in_count = len(os.listdir(still_in_dir))
return (user_count, answer_count, still_in_count)
def show_status_counts(data):
(user_count, answers, still_in) = get_status_counts(data)
last_question = len(list(tdata.keys()))
last_round = len(list(rps_data.keys()))
last_update_time = time.time() - data.game_file_mtime
data.html_append('Game status:<br><table border="1"><tr>')
data.html_append('<td>registered users</td>')
data.html_append('<td>answers</td><td>still-in count</td>')
data.html_append('<td width="10px"> </td>')
data.html_append('<td>sequence</td><td>phase</td><td>state</td>')
data.html_append('<td>question</td><td>round</td>')
data.html_append('<td>last update time</td>')
data.html_append('</tr><tr>')
data.html_append('<td align="center">%d</td>' % user_count)
data.html_append('<td align="center">%d</td>' % answers)
data.html_append('<td align="center">%d</td>' % still_in)
data.html_append('<td align="center"> </td>')
data.html_append('<td align="center">%d</td>' % data.sequence)
data.html_append('<td align="center">"%s"</td>' % data.phase)
data.html_append('<td align="center">"%s"</td>' % data.state)
data.html_append('<td align="center">%d of %d</td>' % (data.question_num, last_question))
data.html_append('<td align="center">%d of %d</td>' % (data.round_num, last_round))
data.html_append('<td align="center">%3.1f</td>' % (last_update_time))
data.html_append('</tr></table>')
######################################################
# returns list of winner tuples (id, alias, name, email)
def get_winners(data):
# scan still_in_dir, and find data for each winner
file_list = os.listdir(still_in_dir)
winners = []
for still_in_user_id in file_list:
if still_in_user_id in [ADMIN_USER_ID, OBSERVER_USER_ID]:
continue
user_filepath = user_dir + still_in_user_id
try:
fd = open(user_filepath, "r", encoding="utf-8")
line = fd.readline().strip()
user_id, alias, name, email, status, jlast_answer = \
line.split(',', 5)
winners.append((user_id, alias, name, email))
except:
data.add_error_message("Problem reading data from '%s'" % (user_filepath))
winners.sort()
return winners
######################################################
def save_winners(data):
# write out file to next filename in sequence
# increment sequence number
data.winner_group += 1
winner_filepath = data_dir + winner_file_fmt % data.winner_group
winners = get_winners(data)
try:
fd = open(winner_filepath, "w", encoding="utf-8")
for w in winners:
line = "%s,%s,%s,%s\n" % w
fd.write(line)
fd.close()
except:
data.add_error_message("Problem writing winner file %s" % winner_filepath)
######################################################
def show_registration(data, user):
if not user.logged_in:
# show player registration form
html_start(data, user)
data.html_append("This is the registration page.\n<p>\n")
show_register_form(data, "", "", "", "")
data.is_form_page = True
else:
html_start(data, user, True)
show_waiting_to_begin_page(data)
######################################################
def show_question_form(data):
qnum = data.question_num
try:
question = tdata[qnum][0]
green_text = tdata[qnum][1]
red_text = tdata[qnum][2]
both_text = tdata[qnum][3]
except (KeyError, IndexError):
question = "What is wrong with the game engine?"
green_text = "Aliens have taken over the server"
red_text = "Tim doesn't know what he's doing"
both_text = ""
data.add_error_message("Corrupt trivia data for question %d" % qnum)
d = {}
d["qnum"] = data.question_num
d["image_url"] = data.image_url
d["question"] = question % d
data.html_append("""
<h1>Question # %(qnum)s</h1>
%(question)s
<p>
<HR>
""" % d)
data.html_append("""
Please choose an answer:
<FORM method=post action="%s" name="question_form">
<input type="hidden" name="action" value="submit_answer">
<input type="hidden" name="qnum" value="%s">
<ul>
<table>
<tr>
<td><font color="green">Green</font> : </td>
<td><INPUT type="radio" name="answer" value="green">%s</td>
</tr><tr>
<td><font color="red">Red</font> : </td>
<td><INPUT type="radio" name="answer" value="red">%s</td>
""" % (data.url, data.question_num, green_text, red_text))
if both_text:
data.html_append("""
</tr><tr>
<td><font color="red">B</font><font color="green">o</font><font color="red">t</font><font color="green">h</font> : </td>
<td><INPUT type="radio" name="answer" value="both">%s</td>
""" % both_text)
# now finish the form
data.html_append("""
</tr><tr>
<td><input type="submit" name="give_answer" value="Submit"></td>
<td></td>
</tr>
</table>
</ul>
<FORM>
<p>
""")
if data.mode == SINGLE:
seconds = 20
timer_html = get_timer_html(data, seconds, "submit")
data.html_append(timer_html + """
<div>You have <span id="time">%s</span> seconds to answer the question</div>
<p>
""" % seconds)
data.is_form_page = True
######################################################
def show_qwaiting_page(data, answer):
qnum = data.question_num
try:
question = tdata[qnum][0]
green_text = tdata[qnum][1]
red_text = tdata[qnum][2]
both_text = tdata[qnum][3]
except (KeyError, IndexError):
question = "What is wrong with the game engine?"
green_text = "Aliens have taken over the server"
red_text = "Tim doesn't know what he's doing"
both_text = ""
data.add_error_message("Corrupt trivia data for question %d" % qnum)
d = {}
d["qnum"] = data.question_num
d["image_url"] = data.image_url
d["question"] = question % d
d["green_text"] = green_text
d["red_text"] = red_text
d["both_text"] = both_text
data.html_append("""
<h1>Question # %(qnum)s</h1>
%(question)s
<p>
<HR>
""" % d)
d["green_indicator"] = ""
d["red_indicator"] = ""
d["both_indicator"] = ""
d["you_chose"] = "You chose an answer:"
if answer == "green":
d["green_indicator"] = "<--- Your answer"
elif answer == "red":
d["red_indicator"] = "<--- Your answer"
elif answer == "both":
d["both_indicator"] = "<--- Your answer"
elif answer == "no-answer":
d["you_chose"] = ""
else:
data.add_error_message("Invalid answer '%s' provided" % answer)
data.html_append("""
%(you_chose)s
<ul>
<table>
<tr>
<td><font color="green">Green</font> : </td>
<td>%(green_text)s</td>
<td>%(green_indicator)s</td>
</tr><tr>
<td><font color="red">Red</font> : </td>
<td>%(red_text)s</td>
<td>%(red_indicator)s</td>
""" % d)
if both_text:
data.html_append("""
</tr><tr>
<td><font color="red">B</font><font color="green">o</font><font color="red">t</font><font color="green">h</font> : </td>
<td>%(both_text)s</td>
<td>%(both_indicator)s</td>
""" % d)
# finish the page
data.html_append("""
</tr>
</table>
</ul>
<p>
<hr>
<h1 align="center">Waiting for answer</h1>
<HR>\n<p>\n
""")
if data.mode == SINGLE:
seconds = 5
timer_html = get_timer_html(data, seconds, "show_answer")
data.html_append(timer_html + """
<div>Answer will show in in <span id="time">%s</span> seconds</div>
<p>
""" % seconds)
######################################################
def show_answer_page(data, answer):
qnum = data.question_num
try:
question = tdata[qnum][0]
green_text = tdata[qnum][1]
red_text = tdata[qnum][2]
both_text = tdata[qnum][3]
answer_code = tdata[qnum][4]
answer_text = tdata[qnum][5]
except (KeyError, IndexError):
question = "What is wrong with the game engine?"
red_text = "Tim doesn't know what he's doing"
green_text = "Aliens have taken over the server"
both_text = ""
answer_code = "red"
answer_text = "obviously"
data.add_error_message("Corrupt trivia data for question %d" % qnum)
#data.add_error_message("answer=%s" % answer)
d = {}
d["qnum"] = data.question_num
d["image_url"] = data.image_url
d["question"] = question % d
d["green_text"] = green_text
d["red_text"] = red_text
d["both_text"] = both_text
data.html_append("""
<h1>Question # %(qnum)s</h1>
%(question)s
<p>
<HR>
""" % d)
d["red_indicator"] = ""
d["green_indicator"] = ""
d["both_indicator"] = ""
d["you_chose"] = "You chose an answer:"
if answer == "green":
d["green_indicator"] = "<--- Your answer"
elif answer == "red":
d["red_indicator"] = "<--- Your answer"
elif answer == "both":
d["both_indicator"] = "<--- Your answer"
elif answer == "no-answer":
d["you_chose"] = ""
else:
data.add_error_message("Invalid answer '%s' provided" % answer)
d["green_right"] = ""
d["red_right"] = ""
d["both_right"] = ""
answer_list = answer_code.split("|")
found_right_answer = False
if "green" in answer_list:
d["green_right"] = "<--- The right answer"
found_right_answer = True
if "red" in answer_list:
d["red_right"] = "<--- The right answer"
found_right_answer = True
if "both" in answer_list:
d["both_right"] = "<--- The right answer"
found_right_answer = True
if not found_right_answer:
data.add_error_message("Invalid answer_code '%s'!!" % answer_code)
data.html_append("""
%(you_chose)s
<ul>
<table>
<tr>
<td><font color="green">Green</font> : </td>
<td>%(green_text)s</td>
<td>%(green_indicator)s</td>
<td>%(green_right)s</td>
</tr><tr>
<td><font color="red">Red</font> : </td>
<td>%(red_text)s</td>
<td>%(red_indicator)s</td>
<td>%(red_right)s</td>
""" % d)
if both_text:
data.html_append("""
</tr><tr>
<td><font color="red">B</font><font color="green">o</font><font color="red">t</font><font color="green">h</font> : </td>
<td>%(both_text)s</td>
<td>%(both_indicator)s</td>
<td>%(both_right)s</td>
""" % d)
# finish the page
if data.is_observer:
msg = ""
else:
if answer in answer_code.split("|"):
msg = "<h2>You got it right!!</h2>"
else:
msg = "Sorry - you didn't get it right!!"
data.html_append("""
</tr>
</table>
</ul>
<p>\n<HR>\n<p>\n
%s
<p>\n<HR>\n<p>\n
%s
<HR>\n<p>\n
""" % (answer_text % d, msg))
if data.mode == SINGLE:
seconds = 20
timer_html = get_timer_html(data, seconds, "next_question")
data.html_append(timer_html + """
<div>Next question will show in in <span id="time">%s</span> seconds</div>
<p>
""" % seconds)
######################################################
def show_winners_page(data, user):
winners = get_winners(data)
data.html_append("""<h1>We have winners!!</h1>
Here is the list of winners:
<hr>
<ul>
""")
is_winner = False
for winner in winners:
user_id = winner[0]
alias = winner[1]
if user_id == user.user_id:
data.html_append("""<li><b>%s</b>
<-- This is you!! - You are a winner!!""" % alias)
is_winner = True
else:
data.html_append("<li>%s" % alias)
data.html_append("</li>")
data.html_append("</ul>\n<hr>\n<p>\n")
if not data.admin_view:
if not is_winner:
data.html_append("Sorry - you did not win this time.\n<p>\n")
######################################################
def show_trivia(data, form, user):
# if player:
# if state==question, show question and answer form (not refreshin)
# user can submit form, action=answer_question
# if state==waiting, show waiting_for_answer page (refreshing)
# put answer in user file
# if state==answer, show answer page (refreshing)
# on first answer page, update status:
# if answer!='recorded'
# get answer from file
# check answer against correct answer
# write status to user file
# if state==winners, show winners page (refreshing)
# if admin:
# if state==question, show question (with user answer counts)
# if state==waiting, show question page (with user answer counts)
# admin can select "action=show_answer"
# if state==answer, show answer page
# admin can select "action=next_question"
# admin can select "action=declare_winners"
# if state==winners, show winners page (refreshing)
# admin can do: "action=reset_status"
# admin can do: "action=start_rps"
#
state = data.state
if data.is_observer:
answer = "no-answer"
else:
try:
answer = form["answer"].value
except LookupError:
answer = user.last_answer
if state == "question" and answer:
state = "waiting"
# data.add_notice("answer='%s'" % answer)
# data.add_notice("state='%s'" % state)
if not data.admin_view:
if state == "question":
if data.is_observer:
html_start(data, user, True)
show_qwaiting_page(data, "no-answer")
else:
html_start(data, user)
show_question_form(data)
elif state == "waiting":
html_start(data, user, True)
show_qwaiting_page(data, answer)
elif state == "answer":
html_start(data, user, True)
show_answer_page(data, answer)
elif state == "winners":
html_start(data, user, True)
show_winners_page(data, user)
else:
data.add_error_message("unknown trivia state: %s" % state)