class TestAssignment(unittest.TestCase): def setUp(self) -> None: self.assignment = Assignment() self.day = pd.to_timedelta("1day") def test_asset_performance(self): start = np.datetime64('2014-02-01') end = np.datetime64('2015-05-06') # We include the end date. So end + 1 day self.assertEqual( len(self.assignment.calculate_asset_performance(start, end)), len(self.assignment.prices[start:end + self.day])) def test_currency_performance(self): start = np.datetime64('2015-02-01') end = np.datetime64('2016-05-06') self.assertEqual( len(self.assignment.calculate_currency_performance(start, end)), len(self.assignment.exchanges[start:end + self.day])) def test_total_performance(self): start = np.datetime64('2014-02-01') end = np.datetime64('2016-05-06') self.assertEqual( len(self.assignment.calculate_total_performance(start, end)), len(self.assignment.prices[start:end + self.day])) def test_whole_table(self): # Take this date. # If it won't have the price for the previous period, so it can't calculate the performance. start = np.datetime64('2014-01-16') end = np.datetime64('2050-01-01') self.assertEqual( len(self.assignment.calculate_total_performance(start, end)), len(self.assignment.prices[start:end + self.day]))
def test_unset_variable_name_is_none(self): # Arrange assignment = Assignment() # Act value = assignment.get('UNSET') # Assert self.assertIsNone(value)
def test_assignment_starts_with_empty_state(self): # Arrange assignment = Assignment() # Act count = assignment.count() # Assert self.assertEqual(0, count)
def check_work( args ): students = repo.get_student_list(ssh=args.sshlist) if args.student != None and len(args.student) > 0: student_filter = set(args.student) students = filter( lambda s: s in student_filter, students ) for assignment_id in args.assignment: a = Assignment(assignment_id, pull=args.pull, verbose=args.verbose) print a.name for s in students: if args.dry_run: print "\n" + "-"*10 feedback_fname = 'feedback/{adir}/{std}.txt'.format( adir = a.dir, std = s ) if args.action == NEW_ONLY and os.path.isfile( feedback_fname ): print "{0} already exists, skipping".format( feedback_fname ) continue print s + ": ", (state, submissions) = a.check_submission( s ) if submissions == None or not args.dry_run: print Assignment.state_description( state ) if submissions != None: comments = "" if os.path.isfile( feedback_fname ) and args.action == UPDATE: old_fb = open( feedback_fname, 'r' ) comments_started = False for line in old_fb: if comments_started: comments += line elif re.match( '---COMMENTS---', line ): comments_started = True old_fb.close() if args.dry_run: feedback = StringIO() else: feedback = open( 'feedback/{adir}/{std}.txt'.format( adir = a.dir, std = s ), 'w' ) feedback.write( Assignment.state_description( state ) + "\n" ) for sub in submissions: feedback.write( str(sub) + "\n" ) score, results = sub.evaluate() feedback.write( results + "\n" ) feedback.write( "score: {0}\n".format( score ) ) break if not args.dry_run or len(comments) > 0: feedback.write( "---COMMENTS---\n" ) if len(comments) > 0: feedback.write( comments ) elif not args.dry_run: #gives an easy way to find files where comments not written feedback.write( "#NEW# -- delete this line when done\n" ) if args.dry_run: print feedback.getvalue() print "-="*25 + "-" feedback.close
def test_not_violated_if_variable_equal(self): # Arrange expected_value = 1 variable = Variable('1', Domain([expected_value])) constraint = EqualConstraint(variable, expected_value) assignment = Assignment() assignment.set(variable.name, expected_value) # Act result = constraint.is_violated(assignment) # Assert self.assertFalse(result)
def test_unsat(self: TestClause): clause = Clause([-6, 5, -4, 3, -2, 1]) a1 = Assignment(set([1, 2, 3, 4, 5, 6])) a1.add_assignment(0, 6, 1, None) clause.assign(a1) a1.add_assignment(1, 5, 0, None) a1.add_assignment(2, 3, 0, None) a1.add_assignment(2, 4, 1, None) a1.add_assignment(2, 1, 0, None) a1.add_assignment(2, 2, 1, None) clause.assign(a1) self.assertEqual(clause.get_state(a1), (Clause.UNSATISFIED, 1, 1)) self.assertEqual(clause.get_assigned_vars(a1), [6, 5, 4, 3, 2, 1])
def __init__(self): # 建立 cplex 模型 self.A = Assignment() self.M = cplex.Cplex() self.M.objective.set_sense(self.M.objective.sense.minimize) # 这儿是随机选取的指派问题结果的第一组值 self.my_obj = self.A.costs_all()[0] # print(my_obj) self.my_rhs = [1.0] * self.A.one.customer_num + [ self.A.one.truck_cap + self.A.one.trailer_cap ] * self.A.trailer_num + [self.A.one.truck_cap ] * (self.A.truck_num - self.A.trailer_num)
def getAssignments(courseURL, daSession): id_resp = daSession.get(courseURL) parsed_id_resp = BeautifulSoup(id_resp.text, 'html.parser') # find table tableOfAssignment = parsed_id_resp.find( "table", {"id": "assignments-student-table"}) # print("\nPrinting table") # print(tableOfAssignment) # find all assignemnts assignmentList = tableOfAssignment.find_all("tr", {"role": "row"}) # print("\nPrinting assignment list") # for assign in assignmentList: # print(assign) listOfAssignments = [] # for each assignment, find its title, due date, due time for assignment in assignmentList: # find title allText = assignment.text print("printing assignment") print(allText) title = "Filler" if (allText.find('Submitted') >= 0): submitIndex = allText.find('Submitted') title = allText[0:submitIndex] elif (allText.find("No Submission") >= 0): noSubmitIndex = allText.find('No Submission') title = allText[0:noSubmitIndex] else: slashIndex = allText.find('/') title = allText[0:slashIndex - 1] # find due date/time if (allText.find('Due Date') < 0): continue indexOfDueDate = allText.find('Due Date') + 10 time = allText[indexOfDueDate:indexOfDueDate + 17] listOfAssignments.append(Assignment(title, time)) hi = Assignment(title, time) # for hi in listOfAssignments: # print(hi.title + " " + hi.dueDateTime) return listOfAssignments
def test_not_violated_if_all_variables_different(self): # Arrange assignment = Assignment() variables = [] for i in range(9): variable = Variable(str(i), Domain(list(range(1, 10)))) variables.append(variable) assignment.set(variable.name, i + 1) constraint = AllDiffConstraint(variables) # Act result = constraint.is_violated(assignment) # Assert self.assertFalse(result)
def __init__(self, players, roles, include_ai=0): if len(roles) != len(players) + 3 + (include_ai): raise Exception('you done fd up. %s != %s' % (players, roles)) self.roles = [Role(r) for r in roles] self.players = [ Player(p.name, inform=p.inform, ask=p.ask) for p in players ] + [Center(i) for i in range(3)] for i in range(include_ai): self.players.append( AIPlayer('AI_' + str(i), self.roles, self.players)) self.assignment = Assignment({}, roles) self.assign() self.inform_players() print self.assignment
def generate_column_drops(root, player_mark, opposite_player_mark, board): temp_board = deepcopy(board) if root.assignment is not None: if root.assignment.is_winning_move: return for column in range(COLUMN_COUNT): # column has already been filled if temp_board.is_invalid_move(column): continue board = deepcopy(temp_board) row = board.next_free_row_for_column(column) board.drop_coin(column, player_mark) assignment_id = Helper.next_node_name_from(None) assignment = \ Assignment( assignment_id=Helper.next_node_name_from(assignment_id), board=board, row=row, col=column, player_mark=player_mark, opposite_player_mark=opposite_player_mark, is_winning_move=board.is_winning_move(row, column, player_mark) ) node = Node(assignment_id, root, assignment=assignment)
def test_not_consistent_if_assignment_violates_constraint(self): # Arrange variables = [ Variable('1', Domain([1, 2, 3])), Variable('2', Domain([1, 2])) ] constraints = [EqualConstraint(variables[0], 2)] csp = ConstraintSatisfactionProblem(variables, constraints) assignment = Assignment() assignment.set(variables[0].name, 3) # Act consistent = csp.consistent(assignment) # Assert self.assertFalse(consistent)
def test_consistent_for_partial_assignment(self): # Arrange variables = [ Variable('1', Domain([1, 2, 3])), Variable('2', Domain([1, 2])) ] constraints = [EqualConstraint(variables[0], 2)] csp = ConstraintSatisfactionProblem(variables, constraints) assignment = Assignment() assignment.set(variables[0].name, 2) # Act consistent = csp.consistent(assignment) # Assert self.assertTrue(consistent)
def test_unset_removes_assignment(self): # Arrange variable_name = 'A' assignment = Assignment() assignment.set(variable_name, 10) # Act assignment.unset(variable_name) # Assert self.assertEqual(0, assignment.count()) self.assertFalse(assignment.is_set(variable_name)) self.assertIsNone(assignment.get(variable_name))
def test_select_unassigned_variable_returns_valid_variable(self): # Arrange variables = [ Variable('1', Domain([1, 2, 3])), Variable('2', Domain([1, 2])) ] constraints = [EqualConstraint(variables[0], 2)] csp = ConstraintSatisfactionProblem(variables, constraints) assignment = Assignment() assignment.set(variables[0].name, 2) # Act variable = csp.select_unassigned_variable(assignment) # Assert self.assertIsNotNone(variable) self.assertEqual(variables[1].name, variable.name)
def test_not_violated_if_some_variables_not_set(self): # Arrange assignment = Assignment() variables = [] for i in range(9): variable = Variable(str(i), Domain(list(range(1, 10)))) variables.append(variable) if i < 4: # Only assign some of the values assignment.set(variable.name, i + 1) constraint = AllDiffConstraint(variables) # Act result = constraint.is_violated(assignment) # Assert self.assertFalse(result)
def add_assignment(self, name, expression): """Add an assigmnet statement to our program""" # add to our list of assignments self.assignments.append(Assignment(name, expression)) # add to our list of possible variables when for building an # expression tree self.variables.add(name)
def test_select_unassigned_variable_raises_exception_if_variable_not_available( self): # Arrange exception_thrown = False variables = [Variable('1', Domain([1]))] constraints = [] csp = ConstraintSatisfactionProblem(variables, constraints) assignment = Assignment() assignment.set(variables[0].name, 1) # Act try: csp.select_unassigned_variable(assignment) except: exception_thrown = True # Assert self.assertTrue(exception_thrown)
def read_repo(self): open_file = open(self.file_n, 'r') line = open_file.readline().strip() while len(line) > 0: line_items = line.split("-") file_assignment = Assignment(line_items[1], line_items[2], int(line_items[0])) self.assignments.append(file_assignment) line = open_file.readline().strip() open_file.close()
def _build_conflict_dag( d: DecisionLevel, unsat_clauses: Set[Clause], assignment: Assignment ) -> Tuple[AssignmentItem, Dict[AssignmentItem, Set[AssignmentItem]]]: succ: Dict[AssignmentItem, Set[AssignmentItem]] = {KAPPA: set()} queue: Set[AssignmentItem] = set() seen: Set[AssignmentItem] = set() root: Optional[AssignmentItem] = None for clause in unsat_clauses: for var in clause.get_assigned_vars(assignment): var_item = assignment.get(var) if not var_item: raise Exception( "variable {} should be present in assignment".format(var)) if var_item not in succ: succ[var_item] = set() succ[var_item].add(KAPPA) queue.add(var_item) while queue: var_item = queue.pop() if var_item in seen: continue seen.add(var_item) antecedent = var_item[3] if var_item[0] != d or not antecedent: if var_item[0] == d: root = var_item continue antecedent_vars = antecedent.get_assigned_vars(assignment) for v in antecedent_vars: if v == var_item[1]: continue parent_var_item = assignment.get(v) if not parent_var_item: raise Exception( "variable {} should be present in assignment".format(v)) if parent_var_item not in succ: succ[parent_var_item] = set() succ[parent_var_item].add(var_item) queue.add(parent_var_item) if not root: raise Exception("root should be found when building conflict tree") return root, succ
def test_not_violated_if_variable_not_set(self): # Arrange variable = Variable('1', Domain([1])) constraint = EqualConstraint(variable, 1) assignment = Assignment() # Act result = constraint.is_violated(assignment) # Assert self.assertFalse(result)
def __make_assignment__(self, student, ind_status, by): assignment = Assignment( student_id=student.id, school_id=self.school_id, unique_school_id=self.unique_id, order_of_preference=student.get_preference_order_for_school( self.unique_id), voorkeur=student.get_preference_for_school(self.unique_id), assigned_by=by, ind_status=ind_status) return assignment
def __init__(self, players, roles, include_ai=0): if len(roles) != len(players) + 3 + (include_ai): raise Exception('you done fd up. %s != %s' % (players, roles)) self.roles = [Role(r) for r in roles] self.players = [Player(p.name, inform=p.inform, ask=p.ask) for p in players] + [Center(i) for i in range(3)] for i in range(include_ai): self.players.append(AIPlayer('AI_' + str(i), self.roles, self.players)) self.assignment = Assignment({}, roles) self.assign() self.inform_players() print self.assignment
def test_missingFile_keepGoing(self): out = self._get_stdout_as_StringIO() try: collector = Collector(OUTFILE) Assignment(sandbox.dir('issue28.json')).accept(collector.visit) self.assertTrue(len(collector.get_lines()) == 5) output = out.getvalue().strip() self.assertRegex(output, 'Not found: .*student2/file1.txt', msg=output) finally: self._restore_stdout()
def main(): a = Assignment() a.prompt() print() a.display()
def test_not_violated_if_variables_not_set(self): # Arrange variables = [ Variable(str(i), Domain(list(range(1, 10)))) for i in range(9) ] constraint = AllDiffConstraint(variables) assignment = Assignment() # Act result = constraint.is_violated(assignment) # Assert self.assertFalse(result)
def make_assignment(self): """Creates a new Assignment object and calls Assignment.build_assignment()""" a_id = int(input("Please enter the ID of this assignment.")) a_syear = int(input("Please enter the startdate of this assignment.")) a_smonth = int(input()) a_sday = int(input()) a_dyear = int(input("Please enter the duedate of this assignment.")) a_dmonth = int(input()) a_dday = int(input()) assignment_in_works = Assignment(a_id, start_date=date( a_syear, a_smonth, a_sday), due_date=date(a_dyear, a_dmonth, a_dday)) assignment_in_works.build_assignment() self.directory.write( json.dumps(a_id) + '\n' + json.dumps(date(a_syear, a_smonth, a_sday), cls=DateEncoder) + '\n' + json.dumps(date(a_dyear, a_dmonth, a_dday), cls=DateEncoder) + '\n')
def main(): import datetime today = datetime.date.today() begin = (today + datetime.timedelta(days=3)).strftime('%m/%d/%Y') end = (today + datetime.timedelta(days=6)).strftime('%m/%d/%Y') helper = StaxHelper() driver = StaxHelper.run_on(False) # start the code example helper.user.login(driver) helper.user.select_course(driver, category='biology') reading = 'test-read %s' % Assignment.rword(8) helper.teacher.add_assignment( driver=driver, assignment='reading', args={ 'title': reading, 'description': 'An auto-test assignment', 'periods': {'all': (begin, end)}, 'reading_list': ['4.0', '4.1', '4.2', 'ch5', '5.2'], 'status': 'draft', } ) homework = 'test-hw %s' % Assignment.rword(8) helper.teacher.add_assignment( driver=driver, assignment='homework', args={ 'title': homework, 'description': 'An auto-test assignment', 'periods': {'all': (begin, end)}, 'problems': {'4.0': None, '4.1': (4, 8), '4.2': 'all', '4.3': ['2102@1', '2104@1', '2175'], 'ch5': 5, 'tutor': 4}, } )
def test_order_domain_values_returns_all_domain_values(self): expected_values = set([1, 2, 3]) variables = [Variable('1', Domain(list(expected_values)))] constraints = [] csp = ConstraintSatisfactionProblem(variables, constraints) assignment = Assignment() values = set() # Act for value in csp.order_domain_values(variables[0], assignment): values.add(value) # Assert self.assertEqual(expected_values, values)
def test_set_adds_assignment(self): # Arrange assignment = Assignment() variable_name = 'A' variable_value = 10 # Act assignment.set(variable_name, variable_value) # Assert self.assertEqual(1, assignment.count()) self.assertTrue(assignment.is_set(variable_name)) self.assertEqual(variable_value, assignment.get(variable_name))
class BacktrackingSearch: def __init__(self, cp): self.cp = cp self.assignment = None def search(self): self.assignment = Assignment() return self._recursive_search() # dumb backtracking search def _recursive_search(self): if self.cp.is_complete(self.assignment): return self.assignment variable = self.cp.select_unassigned_variable(self.assignment) ordered_values = self.cp.order_domain_values(variable) for value in ordered_values: if self.cp.is_consistent(variable, value, self.assignment): self.assignment.add(variable, value) result = self._recursive_search() if result is not None: return result self.assignment.remove(variable) return None
def __init__(self): parser = argparse.ArgumentParser() parser.add_argument('config', help='JSON configuration file') parser.add_argument( '-v', '--verbose', help='increase output verbosity', action='store_true' ) args = parser.parse_args() Command.set_default_verbosity(args.verbose) self._a2pdf = Command( 'a2pdf --noperl-syntax --noline-numbers "{ins}" -o "{ins}.pdf"') self._pdfcat = Command('pdftk "{ins}" cat output "{outs}"') self._create_log = Command('git log > log.txt') self._rm = Command('rm "{ins}"') Assignment(args.config).accept(self.process_submission)
def read_repo(self): try: open_file = open(self.file_n, "rb") save_assignments_lists = pickle.load(open_file) for assignment_list in save_assignments_lists: # we created a assignment file_assignment = Assignment(assignment_list[1], assignment_list[2], assignment_list[0]) self.assignments.append( file_assignment) # we got him in the list open_file.close() except EOFError: # pickle will give an error if the file is empty pass except IOError as error: # if it's an input error raise error
def doInference(self, inferenceInfo, csp, variable, value): assignment = Assignment() assignment.addVariableToAssignment(variable, value) for con in csp.getConstraints(variable): otherVariables = csp.getNeighbour(variable, con) for ov in otherVariables: someValues = [] changed = False domVals = inferenceInfo.getDomainsOfAffectedVariables(ov) if domVals is None: domVals = csp.getDomainValues(ov) for domVal in domVals: assignment.addVariableToAssignment(ov, domVal) if not con.isConsistentWith(assignment): changed = True else: someValues.append(domVal) if changed: inferenceInfo.addToAffectedVariables(ov, someValues) assignment.removeVariableFromAssignment(ov) return []
def __init__(self, vocabulary, attribute_system, mapping): """ Construct a ConstantAssignment object. :param vocabulary: The Vocabulary object :math:`\Sigma` the \ ConstantAssignment is defined over. :type vocabulary: Vocabulary :param attribute_system: The AttributeSystem object \ :math:`\mathcal{S}` from which the objects \ :math:`\{s_{1}, \ldots, s_{n}\}` in the ConstantAssignment come from. :type attribute_system: AttributeSystem :param mapping: The mapping :math:`\\rho` from the constants C of \ the Vocabulary object :math:`\Sigma` in the ``vocabulary`` parameter \ to the objects :math:`\{s_{1}, \ldots, s_{n}\}` of the \ AttributeSystem object :math:`\mathcal{A}` in the \ ``attribute_system`` parameter. :type mapping: ``dict`` :raises TypeError: ``vocabulary`` parameter must be a Vocabulary \ object, ``attribute_system`` parameter must be an AttributeSystem \ object and ``mapping`` parameter must be a ``dict`` with ``str`` keys \ and values. :raises ValueError: All keys in the ``mapping`` parameter must be in \ the Vocabulary object in the ``vocabulary`` parameter's ``C`` member \ and all values in the ``mapping`` parameter must be unique and match \ some object in the ``object`` member of the AttributeSystem object in \ the ``attribute_system`` parameter. """ if not isinstance(mapping, dict): raise TypeError( "mapping parameter must be of type dict") if not all([isinstance(s, str) for s in mapping.keys()]): raise TypeError("mapping must be of form str: str") if not all([isinstance(s, str) for s in mapping.values()]): raise TypeError("mapping must be of form str: str") source = mapping.keys() target = mapping.values() if len(target) != len(set(target)): raise ValueError( "duplicate values in mapping parameter " "are not allowed; mapping must be 1-to-1.") # note: Vocabularies prevent duplicates as do dictionary keys source_condition = set(source) <= set(vocabulary._C) # note: AttributeSystems prevent duplicate objects target_condition = set(target) <= set(attribute_system._objects) if source_condition and target_condition: Assignment.__init__(self, vocabulary, attribute_system) self._mapping = mapping self._source = mapping.keys() self._target = mapping.values() self._is_ConstantAssignment = True else: raise ValueError( "ConstantAssignment must be a partial (or total) function " "from Vocabulary's C to AttributeSystem's objects")
def test_each(self): the_assignment = Assignment(sandbox.dir("assignment1.json")) the_assignment.accept(self.collector.visit) self.assertPathsExist()
print('''It's 8.40 and the office is almost empty. Oh, wait, I can see someone drinking their morning coffee in the kitchen. The students start to arrive very very slowly. Soothing music is playing in the background.''') input("") print("9 o'clock - GONG!") input("") print("Who's here already? Let's check the attendance!") input("") # script attendance check (late students) late = len([i for i in codecool_bp.students if i.late]) event = Athomosphere(-2, '"Oh, no, {0} students are late. It makes me really sad." Morale: '.format(late), -3, "{0} carries out roll call attendance. His energy level is: ".format(active_mentor.nick_name)) active_mentor.process(event.process_event()) active_mentor.process(event.process_atmosphere()) # for Assignment --- args: name, student, is_active, mentor active_project = Assignment("A mentor's life in an OO way", None, True, active_mentor) event = Event(-3, "{0} announces the project for the week. Energy level: ".format(active_mentor.nick_name)) active_mentor.process(event.process_event()) input("") codecool_bp.drink_coffee(50) input("") print('"Well, this week\'s assignment will be: {0}"'.format(active_project.name)) input("") print("Let's see whether our students are able to understand it right away.") input("") for i in codecool_bp.students: i.understanding_project(active_project.understand_assignment(i)) input("") codecool_bp.drink_coffee(50) input("") print("If you have any questions regarding the project, ask away! - says {0}.".format(active_mentor.nick_name))
def search(self): self.assignment = Assignment() return self._recursive_search()
print("Sometimes a mentor needs a feedback too, even if his name is Miki...") skip = input() print("Tomi is the mentor who always ready to help to his friends.") print("\nBefore feedback:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( miki.nickname, miki.knowledge_level, miki.energy_level, miki.joy_level)) skip = input() f.get_feedback(miki) skip = input() print("Before feedback:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( miki.nickname, miki.knowledge_level, miki.energy_level, miki.joy_level)) skip = input() print("At the end of the day, Tomi checks CANVAS.") skip = input() a = Assignment("OOP project", 24) a.check_assignment(tomi) skip = input() print("He forgets that the deadline hour doesn't come yet. But now he knows.") skip = input() print("And he checks an other assignment.") skip = input() print("Before checking:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( tomi.nickname, tomi.knowledge_level, tomi.energy_level, tomi.joy_level)) skip = input() b = Assignment("Inventory", 3) b.check_assignment(tomi) skip = input() print("After checking:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( tomi.nickname, tomi.knowledge_level, tomi.energy_level, tomi.joy_level)) skip = input()
def __init__(self, vocabulary, attribute_system, mapping, dummy=False): """ Construct a VariableAssignment object. :param vocabulary: The Vocabulary object :math:`\Sigma` the \ VariableAssignment is defined over. :type vocabulary: Vocabulary :param attribute_system: The AttributeSystem object \ :math:`\mathcal{S}` from which the objects \ :math:`\{s_{1}, \ldots, s_{n}\}` in the VariableAssignment come from. :type attribute_system: AttributeSystem :param mapping: The mapping :math:`\chi` from the variables V of \ the Vocabulary object :math:`\Sigma` in the ``vocabulary`` parameter \ to the objects :math:`\{s_{1}, \ldots, s_{n}\}` of the \ AttributeSystem object :math:`\mathcal{A}` in the \ ``attribute_system`` parameter. :type mapping: ``dict`` :param dummy: A flag for creating a dummy (i.e., empty) \ VariableAssignment object :math:`\chi_{dummy}`. :type dummy: ``bool`` :raises TypeError: ``vocabulary`` parameter must be a Vocabulary \ object, ``attribute_system`` parameter must be an AttributeSystem \ object and ``mapping`` parameter must be a ``dict`` with ``str`` keys \ and values. :raises ValueError: All keys in the ``mapping`` parameter must be in \ the Vocabulary object in the ``vocabulary`` parameter's ``V`` member \ and all values in the ``mapping`` parameter must be unique and match \ some object in the ``object`` member of the AttributeSystem object in \ the ``attribute_system`` parameter. """ if not isinstance(mapping, dict): raise TypeError( "mapping parameter must be of type dict") if not all([isinstance(s, str) for s in mapping.keys()]): raise TypeError("mapping must be of form str: str") if not all([isinstance(s, str) for s in mapping.values()]): raise TypeError("mapping must be of form str: str") if dummy: Assignment.__init__(self, vocabulary, attribute_system) self._mapping = {} self._is_VariableAssignment = True else: source = mapping.keys() target = mapping.values() if len(source) != len(set(source)) or len(target) != len(set(target)): raise ValueError( "duplicate values in mapping parameter " "are not allowed; mapping must be 1-to-1.") # total mapping so check for equality source_condition = set(source) <= set(vocabulary._V) target_condition = set(target) <= set(attribute_system._objects) if source_condition and target_condition: Assignment.__init__(self, vocabulary, attribute_system) self._mapping = mapping self._source = mapping.keys() self._target = mapping.values() self._is_VariableAssignment = True else: raise ValueError( "VariableAssignment must be a function from " "vocabulary._V to attribute_system._objects")
class Game: def __init__(self, players, roles, include_ai=0): if len(roles) != len(players) + 3 + (include_ai): raise Exception('you done fd up. %s != %s' % (players, roles)) self.roles = [Role(r) for r in roles] self.players = [Player(p.name, inform=p.inform, ask=p.ask) for p in players] + [Center(i) for i in range(3)] for i in range(include_ai): self.players.append(AIPlayer('AI_' + str(i), self.roles, self.players)) self.assignment = Assignment({}, roles) self.assign() self.inform_players() print self.assignment def assign(self): self.originals = {} roles = self.roles[:] for player in self.players: ri = random.randint(0, len(roles) - 1) self.assignment.assign(player, roles[ri]) self.originals[player] = roles[ri] del roles[ri] def inform_players(self, some_msg=None): for player in self.players: if player.active: if some_msg is not None: player.inform(some_msg, None) else: msg = 'You look at your card.' statement = RoleClaim(player, self.assignment.get(player), ORIGINAL) player.inform(msg, statement) def active_players(self): return [p for p in self.players if p.active] def get_players_for_role(self, role, solo=True): ps = filter(lambda x: self.assignment.get(x) == role and x.active, self.players) print 'Players for', role, [p.name for p in ps] if solo and len(ps) > 1: raise Exception('There should only be one %s.' % role) return ps def vote(self): votes = {} for player in self.active_players(): msg = 'Who do you want to kill?' choice = player.select(msg, self.active_players() + [None]) if not choice: return None else: votes[player.name] = choice.name return votes def play_night(self): self.current = self.assignment.copy() r = DOPPLEGANGER ps = self.get_players_for_role(r) if ps: player = ps[0] msg = '%s, wake up. Select one other player\'s role to impersonate.' % r opponent = player.select(msg, self.active_players()) self.dopplegang = self.current.get(opponent) r = WEREWOLF ps = self.get_players_for_role(r, solo=False) for player in ps: for opponent in ps: if player != opponent: msg = '%s, wake up. See the other werewolves.' % r player.inform(msg, RoleClaim(opponent, WEREWOLF, ORIGINAL)) if len(ps) == 1: msg = 'Werewolf, wake up. You may choose a card from the center to look at.' opponent = player.select(msg, [p for p in self.players if not p.active]) player.inform('You learn:', RoleClaim(opponent, self.current.get(opponent), ORIGINAL)) r = MINION werewolves = ps ps = self.get_players_for_role(r) if ps: player = ps[0] for w in werewolves: msg = '%s, wake up. See the werewolves.' % r player.inform(msg, RoleClaim(w, WEREWOLF, ORIGINAL)) r = MASON ps = self.get_players_for_role(r, solo=False) for player in ps: for opponent in ps: if player != opponent: msg = '%s, wake up. See the other masons.' % r player.inform(msg, RoleClaim(opponent, MASON, ORIGINAL)) r = SEER ps = self.get_players_for_role(r) if ps: player = ps[0] opponents_card = 'A single opponent\'s card.' center_card = 'Two cards from the center.' msg = 'Seer, wake up. You may choose to look at one other player\'s card or two cards from the center.' choice = player.select(msg, [opponents_card, center_card]) active = choice == opponents_card msg = 'Seer, select a card to look at.' opponent = player.select(msg, [p for p in self.players if p.active == active]) player.inform('You learn', RoleClaim(opponent, self.current.get(opponent), AFTER_DOPPLE)) if not active: opponent = player.select(msg, [p for p in self.players if p.active == active]) player.inform('You learn:', RoleClaim(opponent, self.current.get(opponent), AFTER_DOPPLE)) r = ROBBER ps = self.get_players_for_role(r) if ps: player = ps[0] msg = 'Robber, wake. You may swap cards with one other player.' opponent = player.select(msg, [p for p in self.players if p.active] + [None]) if opponent: opponent_role = self.current.get(opponent) player_role = self.current.get(player) player.inform('You look at your new card.', RoleClaim(player, opponent_role, AFTER_ROBBER)) player.inform('Which means...', RoleClaim(opponent, player_role, AFTER_ROBBER)) player.inform('and...', RoleClaim(opponent, opponent_role, AFTER_DOPPLE)) self.current.assign(player, opponent_role) self.current.assign(opponent, player_role) r = TROUBLEMAKER ps = self.get_players_for_role(r) if ps: player = ps[0] msg = '%s, wake up. You may swap the cards of two other players.' % r # TODO cannot swap with self opp1 = player.select(msg, self.active_players() + [None]) if opp1: msg = '...and the other player.' opp2 = player.select(msg, [p for p in self.players if p.active and p != opp1]) opp1_role = self.current.get(opp1) self.current.assign(opp1, self.current.get(opp2)) self.current.assign(opp2, opp1_role) r = DRUNK ps = self.get_players_for_role(r) if ps: player = ps[0] msg = '%s, wake up. Select a card from the center to swap with your own.' % r center = player.select(msg, [p for p in self.players if not p.active]) center_role = self.current.get(center) self.current.assign(center, self.current.get(player)) self.current.assign(player, center_role) r = INSOMNIAC ps = self.get_players_for_role(r) if ps: player = ps[0] msg = '%s, wake up. Look at your card.' % r player.inform(msg, RoleClaim(player, self.current.get(player), FINAL)) print print self.current return str(self.current)