import pickle, sys
from jobs import *
from urllib import urlencode
from os import getcwd
from random import sample
GAME_DIR = 'games'
FULL_GAME_DIR = getcwd() + "/" + GAME_DIR
DEFAULT_INTERNAL_ERROR_MESSAGE = """
This is an internal error which you should never see
unless I screwed up or you are hand-typing URLs. In the former
case, just send me an email and let me know about it. In
latter case, you are a bad person for messing with my poor
innocent little cgi scripts.
"""
HTML_BASE = 'http://www.cs.hmc.edu/~cpierog/qmafia/'
COL_SPACER = ' '
LIST_SPACER = ' '
NUM_OF_LAST_PLAYERS = 1 # 0 for no 'last one' emails
# 1 for only last person to move get email
# 2 for last two people get email, etc.
AI_PASSWORD = 'a' # password for all ais
def game_link(game_name, extraText = ''):
return '%s%s' \
% (HTML_BASE, urlencode({'game_name': game_name}), extraText, game_name)
# FIX: go directly to separate sections
def help_link(str):
return '%s'\
% (HTML_BASE, str)
def home_link(str = "Return to the Main Page"):
return '%s' \
% (HTML_BASE, str)
def return_links(game_name = False, main = True):
print '
'
if main:
print '
%s
' % home_link()
if game_name:
print '
%s
' % game_link(game_name, 'Return to ')
print '
\n\n'
# Standard way to report errors
# error_point = what you were doing when the error occured
# error_str = specifics on the error
# correction_str = what the user should do to fix it
#
# (Currently must be called before anything is printed)
# FIX: would be more robust if it erased everything else
# in the buffer before it started printing stuff
def my_error(error_point, error_str, \
correction_str = DEFAULT_INTERNAL_ERROR_MESSAGE):
html_title('Error while ' + error_point)
print """
There has been an error while %s
Error: %s
%s
""" % (error_point, error_str, correction_str)
html_end()
sys.exit(0)
def html_title(title_str):
print '\n%s\n\n\n' % title_str
def html_end():
print '\n\n\n'
# excludedPlayers = list of names of players to exclude from listing
def html_player_selector(selector_name, selected_player, addSleep = False):
print ''
# Functions to begin and end a table which if offset by COL_SPACER
# This is accomplished with nested tables
def indented_table_begin(width_100 = False, spacer = COL_SPACER):
width_100_str = ''
if width_100:
width_100_str = 'width="100%"'
print """
"""
# Make sure the form provided has the requested field
def assert_fields(form, fields):
for field in fields:
if not form.has_key(field): # Couldn't find the game field
my_error('attempting to access the "%s" field' % field, \
'Form did not recieve a "%s" field' % field)
# Append an index unto a word and return the resulting string
def add_index(word, index):
return word + '__' + str(index)
# Strip off the index that we added ealier
def rem_index(word):
return word[:(word.rfind('__'))]
# Insert an item into a dictionary
# If there is already something for that key, add it to the list
# If it is the first, make a new list
def dict_add(dict, key, elem):
if dict.has_key(key):
dict[key].append(elem)
else:
dict[key] = [elem]
# Increment a dictionary entry by the given value.
# If that value is not yet present, create a key with the given values
def dict_incr(dict, key, value = 1):
if dict.has_key(key):
dict[key] += value
else:
dict[key] = value
# Takes a list
# Returns true if it contains duplicates, and false otherwise
def contains_duplicates(list):
for (i,a) in enumerate(list):
for (j,b) in enumerate(list):
if i != j and a == b:
return True
return False
# Return a random element from a list
def rand_elem(list):
return sample(list,1)[0]
def unique_combinations(items):
for n in xrange(1,len(items)):
for comb in unique_combinations_helper(items, n):
yield comb
def unique_combinations_helper(items, n):
if n==0: yield []
else:
for i in xrange(len(items)-n+1):
for cc in unique_combinations_helper(items[i+1:],n-1):
yield [items[i]]+cc
# Takes:
# Choice dict: voting_player_name -> player_name they voted for
# (ala game.get_player_choices())
# Returns:
# If 1) (percent)% or more of the players vote for one player,
# and 2) there are no ties for the most votes,
# return that player_name
# Otherwise, return None
def general_vote(player_choices, percent = 50):
if len(player_choices) <= 0:
return None
# Tally votes
vote_qty_dict = {} # player_name -> num of votes for that player
for target_of_vote in player_choices.values():
dict_incr(vote_qty_dict, target_of_vote)
# Find player(s) with most votes
most_votes = max(vote_qty_dict.values())
winners = [candidate for candidate, votes in vote_qty_dict.items() \
if votes == most_votes]
# No winner if there is no 50% majority or it there is a tie
if most_votes < len(player_choices) * (percent/100.0) or len(winners) != 1:
return None
return winners[0]