def __init__(self, player1, player2): pygame.init() pygame.font.init() self.player1 = player1 self.player2 = player2 self.neutralPlayer = Player('neutral', 10000000000000, 3, 'Neutrals') self.factory1 = UnitFactory(player1, self) self.factory2 = UnitFactory(player2, self) self.factoryNeutral = UnitFactory(self.neutralPlayer, self) self.player1.factory = self.factory1 self.player2.factory = self.factory2 self.neutralPlayer.factory = self.factoryNeutral self.board = Board(self) bw, bh = self.board.real_size_with_offsets() self.cpanel = CPanel(self, bw, self.board.top_offset, 400, self.board.real_size_with_offsets()[1]) self.screen = pygame.display.set_mode((bw + self.cpanel.width, bh)) self.clock = pygame.time.Clock() self.gamestate = GameState(player1, self) self.rules = Rules(self) self.render_mode = 'normal' self.board.generate_neutrals(Rules.NEUTRAL_GENERATING_STRATEGY())
class Greetings(QMainWindow): def __init__(self): super(Greetings, self).__init__() self.setWindowTitle("Игра \"Двумерный кубик Рубика\"") self.setGeometry(300, 300, 600, 600) self.label = QLabel(self) self.label.setFont(QFont('Courier New', 15)) self.label.setText("Игра \"Двумерный кубик Рубика\"") self.label.adjustSize() self.label.move(120, 200) self.btn_game = QPushButton(self) self.btn_game.move(200, 300) self.btn_game.setText("Начать игру") self.btn_game.clicked.connect(self.show_game) self.btn_game.clicked.connect(self.close) self.btn_rules = QPushButton(self) self.btn_rules.move(300, 300) self.btn_rules.setText("Правила игры") self.btn_rules.clicked.connect(self.show_rules) self.btn_rules.clicked.connect(self.close) self.show() def show_game(self): self.game = Example() self.game.show() def show_rules(self): self.rules = Rules() self.rules.show()
def testPostToBoard(): print('testPostToBoard') board = Board('53b92a578425b1f0ae215cdd') board.initializeBoard() rules = Rules() rules.apply = lambda ignored: {'gamello': 2} log = Empty() log.getLastUpdateTime = lambda : datetime.today() board.update(log, rules) print('testPostToBoard: passed')
def __init__(self, Animal): self._Animal = Animal rules = Rules() self._Rulelist = rules.get_rules() self._DB = Database() ''' Rulelist中的元素为 dic,其中包含一条规则的信息 键包括:'IF_feature','IF_label', 'THEN_feature','THEN_label', 'THEN_name' 值为相对应的信息列表 ''' self.judge() # 根据规则对 Animal 的 feature 和 label 进行更新 self.identify() # 识别动物
class MyTestCase(unittest.TestCase): def setUp(self): self.rules = Rules() def test_save_rules(self): self.rules.add_rule(Rule("truc", ["1", "2", "3"])) RulesJsonSerializer.save_rules("test_write.json", self.rules) read_data = RulesJsonSerializer.charge_rules("test_write.json") assert isinstance(read_data, Rules) assert read_data.__eq__(self.rules) pass
def __init__(self): self.player1Turn = False self.isGameOver = False self.p1 = player1() self.p2 = player2() self.b1 = [] self.b2 = [] self.b1Copy = [] self.b2Copy = [] self.p1Moves = [] self.p2Moves = [] self.r = Rules()
def accept_battle_action(self, action): action.log() if type(action) == NormalUnitAttack: self.hp -= int( action.damage * Rules.get_percentage(self.armor, action.damage_type)) if self.hp <= 0: self.die(action.source) elif type(action) == PriestHeal: self.hp += action.heal self.hp = min(self.hp, self.max_hp) elif type(action) == BomberDetonation: for r in range(1, self.bomb_radius + 1): s = set() x, y = self.cell for i in range(-r, r + 1): s.add((x + r, y + i)) s.add((x - r, y + i)) s.add((x + i, y + r)) s.add((x + i, y - r)) for pos in s: other_unit = self.board.units_array[pos[0]][pos[1]] if not other_unit is None: attack = NormalUnitAttack(self.bomb_damage, self.bomb_damage_type, self, other_unit) other_unit.accept_battle_action(attack) self.die()
def setUp(self): self.rules = Rules() self.facts = Facts() self.expert = Expert(self.rules, self.facts) self.rules.add_rule(Rule("C", ["A", "B"])) self.rules.add_rule(Rule("E", ["C", "D", "F"])) self.rules.add_rule(Rule("D", ["C"]))
def __init__(self): self.recTree = RecTree() self.lSys = LSystem() self.rules = Rules() self.base = False self.axis = "+X" self.diameter = 6 self.filepathCounter = 0
def act(self): # special method for neutral player; act when the move ends units_array = self.factory.game.board.units_array for i in range(len(units_array)): for j in range(len(units_array[i])): if not (units_array[i][j] is None) and units_array[i][j].owner.name == 'Neutrals': unit = units_array[i][j] cnt = unit.moves_left for _ in range(cnt): unit.act(Rules.NEUTRAL_ACT_STRATEGY())
def bot_vs_bot(color,board): Board = Rules(board) print(board) opponent = 'b' if color == 'w' else 'w' pt = time.time() best_move, high_score = evaluate_board(color, board) print(best_move, high_score) print(time.time() - pt) board_update=Board.update_board(color,best_move[0],best_move[1],best_move[2]) bot_vs_bot(opponent,board_update)
def add_rule(self, state1, state2, signal, action): """ Docstring :param state1: :param state2: :param signal: :param action: :return: """ new_rule = Rules(state1, state2, signal, action) self.Rules.append(new_rule)
def test_skip_non_util_question(self): self.facts = Facts() self.rules = Rules() self.rules.add_rule(Rule("C1", ["A", "B"])) self.rules.add_rule(Rule("C1", ["A", "D"])) self.facts.set_fact_value("A", False) self.expert = Expert(self.rules, self.facts) assert self.expert.infer_backward() is None
def part_one(data_input): vals = list(split_after(data_input, lambda x: x == '')) rule_str = vals[0][0:-1] sequences = vals[1] print('hello') total_passed = 0 rule = Rules() for rule_input in rule_str: rule_idx = re.findall("(\\d+)(?=:)", rule_input)[0] rule_val = re.findall("(?<=:\\s)[\\d\\sa-zA-Z|\\\"]+", rule_input)[0].replace("\"", "") rule.process_rule(int(rule_idx), rule_val) for sequence in sequences: # print(total_passed) if rule.validate_sequence(sequence): total_passed += 1 print("Part One: ", total_passed)
def test_skip_non_util_question_multiple_rules(self): self.facts = Facts() self.rules = Rules() self.rules.add_rule(Rule("C1", ["A", "B"])) self.rules.add_rule(Rule("C1", ["A", "D"])) self.rules.add_rule(Rule("C2", ["A1", "E1"])) self.rules.add_rule(Rule("C2", ["A1", "E2"])) self.rules.add_rule(Rule("C2", ["A2", "F"])) self.facts.set_fact_value("A", False) self.facts.set_fact_value("E1", False) self.facts.set_fact_value("E2", False) self.facts.set_fact_value("A2", True) self.expert = Expert(self.rules, self.facts) assert self.expert.infer_backward() is "F"
======= import sys, os import time >>>>>>> Stashed changes def blockPrint(): # Disable printing sys.stdout = open(os.devnull, 'w') def enablePrint(): # Restore printing sys.stdout = sys.__stdout__ zeros=np.zeros((4,4,4),dtype='str') initboard=np.array((('b','b','b','b'),(' ',' ',' ',' '),(' ',' ',' ',' '),('w','w','w','w'))) board=np.core.defchararray.add(zeros, initboard) unit_vectors = np.array([[0, 1, 0], [0, 0, 1], [0, 1, 1], [0, 1, -1], [0, -1, 1], [0, -1, 0], [0, 0, -1], [0, -1, -1]]) # defines the legal vectors for stone movement up to two spaces viable_vectors = np.concatenate((unit_vectors, unit_vectors * 2)) Board=Rules(board) <<<<<<< Updated upstream def find_my_stones(color,board): ======= def find_my_stones(color, board): >>>>>>> Stashed changes my_stones =[] for i in range(0, 4): for j in range(0,4): for k in range(0,4): if board[i][j][k]==color: my_stones.append((i,j,k)) return my_stones def potential_passive_moves(color,my_stones): # returns passive moves in the form of: (initial stone, move coordinate, vector)
def runSim(self): lowPopFlag = False for i in range(1, self.numTimePeriods + 1): if lowPopFlag: break newTrans = 0 numInts = int(round(self.intsPerTime * self.newPop.getSize())) for j in range(1, numInts + 1): deadCheck = True while deadCheck: edgeNum = random.randint(0, len(self.newPop.agents.es) - 1) randEdge = self.newPop.agents.es[edgeNum] vert1 = self.newPop.agents.vs[randEdge.source] vert2 = self.newPop.agents.vs[randEdge.target] agent1 = vert1["Agent"] agent2 = vert2["Agent"] newInt = Interaction(agent1, agent2) deadCheck = newInt.deadCheck() newInt.setStartVals() newRule = Rules([agent1, agent2]) newResult = newRule.gameResult(self.meanPosVal, self.meanAvoidVal) if newResult[0] == "Avoid": vert1["Agent"].updateValue(newResult[1]) vert2["Agent"].updateValue(newResult[2]) else: newTrans = newTrans + vert1["Agent"].updateDisease( vert2["Agent"], newResult[1]) newTrans = newTrans + vert2["Agent"].updateDisease( vert1["Agent"], newResult[2]) newInt.setEndVals() if self.logInteractions == True: interaction = [i, j, newInt, newRule, newResult] self.intLog.append(interaction) self.newPop.updateSickTime() self.newPop.updateDead() self.totalInts = self.totalInts + numInts self.newPop.logEnd() R0 = self.newPop.calcRo() newLogVals = [ i, self.newPop.getSize(), self.newPop.getFinalSick(), self.newPop.getFinalImmune(), newTrans, R0, numInts ] self.timeLog.append(newLogVals) print('Completed time ' + str(i)) if lowPopFlag: break newLogVals = [ i, numInts, self.newPop.getFinalSick(), self.newPop.getFinalImmune(), newTrans ] self.totalInts = self.totalInts + numInts self.timeLog.append(newLogVals) totalDied = self.newPop.calcNumDied() totalImmune = self.newPop.getFinalImmune() self.runVals.append(totalDied) self.runVals.append(totalImmune) self.endTime = time.time() self.runTime = round((self.endTime - self.startTime), 2) self.timePerInt = self.runTime / self.totalInts print('The simulation ran in ' + str(self.runTime) + ' seconds') print('Total number of interactions simulated: ' + str(self.totalInts)) print('Effective time per interaction: ' + str(self.timePerInt)) return self
def setUp(self): self.rules = Rules()
from Rules import Rules if __name__ == "__main__": r = Rules() assert r.matches((1,2,3), (1,2,3)) assert r.matches((_,2,3), (1,2,3)) assert not r.matches(3, 4) assert r.matches(_, 4) assert r.matches([1,2,_,(3,4,_)],[1,2,"holla",(3,4,5)]) r = Rules((1, 2, _), 'rule 1', (1, 2, 3), 'rule 2', (None, 2), 'rule 3', lambda x: x == 234, 'rule 4', 'something', 'rule 5') assert r(1,2,3) == 'rule 1' assert r(1,2,4) == 'rule 1' assert r(None, 2) == 'rule 3' assert r(234) == 'rule 4' assert r('something') == 'rule 5' f = Rules((1,1,1), 4, (_,5,_), lambda x,y,z: x*z, (_,_,_), lambda x,y,z: 100*x + 10*y + z) assert f(1,1,1) == 4 assert f(3,5,8) == 24 assert f(6,7,8) == 678
# Heya :) # Here is my completed game, it took me about 10~ hours to complete I believe. # In the requirements it is said not to treat this as a start of a bigger project, but I really hated having so much code in # one file so I separated it into small modules so it looks cleaner. Hope you dont mind ! # You can just run index.py and check the terminal for the output ! # ( I left the numerical values of each card in the terminal history output so it is easier for you to check the math. ) # I really hope you like it ! :) #-Sandi # Init Players p1 = Player('P1') p2 = Player('P2') p3 = Player('P3') p4 = Player('P4') p5 = Player('P5') players = [p1, p2, p3, p4, p5] # Init rules rules = Rules() # Init deck deck = Deck() # New Game newGame = Game(players, deck, rules) newGame.play_round()
def __init__(self): self.players = {} #Player dictionary. self.total = 1 # Keeps count of the number of active players. self.rules = Rules()
def getScore(self, tableCards): return Rules.calculateScore(self.cards, tableCards)
def get_ruledef(self): from Rules import Rules Rules = Rules() ruledef = Rules.get_ruledef() return ruledef
for rule in allRule: realRules[rule] = random.choice(allRule[rule]) matchRules =dict() for rules in realRules: t = list() for rule in realRules[rules]: corpus[rule] = list(corpus[rule]) t.append(random.choice(corpus[rule])) l = list() l = [realRules[rules], t] matchRules[rules] = l firstWord = next(iter(corpus[random.choice(corpus.keys())])) mRule = Rules(realRules, firstWord) mPos = PartOfSpeech(mRule) newRule =[mPos.checkPOS(firstWord)] print firstWord print newRule newDict = list() t = firstWord, newRule newDict.append(t) newSentence= list() for rule in newRule: for rules in matchRules: if rules == rule: for word in matchRules[rules][1]: newSentence.append(word) newSentence[0] = firstWord final = str()
class ExpertTest(unittest.TestCase): def setUp(self): self.rules = Rules() self.facts = Facts() self.expert = Expert(self.rules, self.facts) self.rules.add_rule(Rule("C", ["A", "B"])) self.rules.add_rule(Rule("E", ["C", "D", "F"])) self.rules.add_rule(Rule("D", ["C"])) def test_one_iteration(self): last_rule = self._return_result_for(["A", "B"]) assert last_rule.conclusion == "D" def test_two_iteration(self): last_rule = self._return_result_for(["A", "B", "F"]) assert last_rule.conclusion == "E" def test_zero_iteration(self): last_rule = self._return_result_for(["A", "F"]) assert last_rule is None def test_is_a_initial_premise(self): assert self.rules.is_initial_premise("A") assert self.rules.is_initial_premise("B") assert self.rules.is_initial_premise("F") assert not self.rules.is_initial_premise("C") assert not self.rules.is_initial_premise("D") assert not self.rules.is_initial_premise("E") def test_if_fact_is_not_set(self): for fact in ["A", "B", "C"]: assert not self.facts.is_fact_set(fact) def test_if_fact_set(self): assert not self.facts.is_fact_set("A") self.facts.set_fact_value("A", True) assert self.facts.is_fact_set("A") self.facts.set_fact_value("A", False) assert self.facts.is_fact_set("A") assert not self.facts.is_fact_set("B") self.facts.set_fact_value("B", False) assert self.facts.is_fact_set("B") self.facts.set_fact_value("B", True) assert self.facts.is_fact_set("B") def _return_result_for(self, enabled): for condition in enabled: self.facts.set_fact_value(condition, True) return self.expert.infer_forward() def test_backward(self): question = self.expert.infer_backward() assert question == "A" def test_can_retrieve_initial_premises(self): premises = self.rules.find_premises() assert len(premises) == 3 for premise in ["A", "B", "F"]: assert premise in premises def _is_conclusion_in_rules(self, conclusion, rules): for rule in rules: if conclusion == rule.conclusion: return True return False def test_skip_non_util_question(self): self.facts = Facts() self.rules = Rules() self.rules.add_rule(Rule("C1", ["A", "B"])) self.rules.add_rule(Rule("C1", ["A", "D"])) self.facts.set_fact_value("A", False) self.expert = Expert(self.rules, self.facts) assert self.expert.infer_backward() is None def test_skip_non_util_question_multiple_rules(self): self.facts = Facts() self.rules = Rules() self.rules.add_rule(Rule("C1", ["A", "B"])) self.rules.add_rule(Rule("C1", ["A", "D"])) self.rules.add_rule(Rule("C2", ["A1", "E1"])) self.rules.add_rule(Rule("C2", ["A1", "E2"])) self.rules.add_rule(Rule("C2", ["A2", "F"])) self.facts.set_fact_value("A", False) self.facts.set_fact_value("E1", False) self.facts.set_fact_value("E2", False) self.facts.set_fact_value("A2", True) self.expert = Expert(self.rules, self.facts) assert self.expert.infer_backward() is "F"
def __init__(self, models, group, phrase_style="", mess_caps=""): # Define properties self.models = models self.rules = Rules() # Define preferences pref = {'pricerange': '', 'area': '', 'food': ''} self.pref_df = pd.DataFrame(pref, index=[0]) # Manage states self.state = State.S1 self.__state_manager = StateManager() # Save last printed text for repeat utterance self.print_text = "" # Load the System utterances self.sys_utter = {} if phrase_style == "informal": file_name = "assets/inf_sys_utterances.txt" else: file_name = 'assets/sys_utterances.txt' with open(file_name, 'r') as inf: for line in inf: line = line.replace('\n', '') keys = line.split(' ') if mess_caps == "caps": self.sys_utter[keys[0]] = ' '.join(keys[1:]).upper() else: self.sys_utter[keys[0]] = ' '.join(keys[1:]) if group: self.delay = True self.delay_time = 0 self.delay_mess = False if group[0] == "G1NOM": if group[1] == "1": self.delay_time = 0.1 self.delay_mess = False elif group[1] == "2": self.delay_time = 0.1 self.delay_mess = True else: print("Warning: task number not defined") if group[0] == "G1MNO": if group[1] == "1": self.delay_time = 0.1 self.delay_mess = True elif group[1] == "2": self.delay_time = 0.1 self.delay_mess = False else: print("Warning: task number not defined") if group[0] == "G2NOM": if group[1] == "1": self.delay_time = 1.0 self.delay_mess = False elif group[1] == "2": self.delay_time = 1.0 self.delay_mess = True else: print("Warning: task number not defined") if group[0] == "G2MNO": if group[1] == "1": self.delay_time = 1.0 self.delay_mess = True elif group[1] == "2": self.delay_time = 1.0 self.delay_mess = False else: print("Warning: task number not defined") if group[0] == "G3NOM": if group[1] == "1": self.delay_time = 10.0 self.delay_mess = False elif group[1] == "2": self.delay_time = 10.0 self.delay_mess = True else: print("Warning: task number not defined") if group[0] == "G3MNO": if group[1] == "1": self.delay_time = 10.0 self.delay_mess = True elif group[1] == "2": self.delay_time = 10.0 self.delay_mess = False else: print("Warning: task number not defined") else: print("Warning: No group has been given.") self.delay = False # Print the first system message print(self.sys_utter['welcome'])
class ChatManager: def __init__(self, models, group, phrase_style="", mess_caps=""): # Define properties self.models = models self.rules = Rules() # Define preferences pref = {'pricerange': '', 'area': '', 'food': ''} self.pref_df = pd.DataFrame(pref, index=[0]) # Manage states self.state = State.S1 self.__state_manager = StateManager() # Save last printed text for repeat utterance self.print_text = "" # Load the System utterances self.sys_utter = {} if phrase_style == "informal": file_name = "assets/inf_sys_utterances.txt" else: file_name = 'assets/sys_utterances.txt' with open(file_name, 'r') as inf: for line in inf: line = line.replace('\n', '') keys = line.split(' ') if mess_caps == "caps": self.sys_utter[keys[0]] = ' '.join(keys[1:]).upper() else: self.sys_utter[keys[0]] = ' '.join(keys[1:]) if group: self.delay = True self.delay_time = 0 self.delay_mess = False if group[0] == "G1NOM": if group[1] == "1": self.delay_time = 0.1 self.delay_mess = False elif group[1] == "2": self.delay_time = 0.1 self.delay_mess = True else: print("Warning: task number not defined") if group[0] == "G1MNO": if group[1] == "1": self.delay_time = 0.1 self.delay_mess = True elif group[1] == "2": self.delay_time = 0.1 self.delay_mess = False else: print("Warning: task number not defined") if group[0] == "G2NOM": if group[1] == "1": self.delay_time = 1.0 self.delay_mess = False elif group[1] == "2": self.delay_time = 1.0 self.delay_mess = True else: print("Warning: task number not defined") if group[0] == "G2MNO": if group[1] == "1": self.delay_time = 1.0 self.delay_mess = True elif group[1] == "2": self.delay_time = 1.0 self.delay_mess = False else: print("Warning: task number not defined") if group[0] == "G3NOM": if group[1] == "1": self.delay_time = 10.0 self.delay_mess = False elif group[1] == "2": self.delay_time = 10.0 self.delay_mess = True else: print("Warning: task number not defined") if group[0] == "G3MNO": if group[1] == "1": self.delay_time = 10.0 self.delay_mess = True elif group[1] == "2": self.delay_time = 10.0 self.delay_mess = False else: print("Warning: task number not defined") else: print("Warning: No group has been given.") self.delay = False # Print the first system message print(self.sys_utter['welcome']) def run(self): # Start the chat loop while True: # Check system state and preferences self.systemStateUtterance() if self.state == State.S1: # Define preferences # necessary if user wants to start from beginning again pref = {'pricerange': '', 'area': '', 'food': ''} self.pref_df = pd.DataFrame(pref, index=[0]) self.models.index = -1 # S5 is the end state, therefore terminate the program if self.state == State.S5: break # Ask user for input user_input = input('-----> ') # introduce delay if applicable if self.delay: if self.delay_mess: print(self.sys_utter['loading']) time.sleep(self.delay_time) # Evaluate inputted utterance and check the next state utterance = self.models.evalueNewUtterance(user_input) # print(utterance) # React based on what utterance self.reactToUtterance(utterance, user_input) # Use state manager to set new state new_state = self.__state_manager.processState( self.state, utterance, self.pref_df) # Print extra message to inform user that deny utterance was understood. if new_state == State.S2 and self.state == State.S3 and utterance == 'deny' and user_input == 'wrong': print('-----> We will restart because it is wrong') elif new_state == State.S2 and self.state == State.S3 and utterance == 'deny': print('-----> Okay then we will take that into account') # if new state is S3, look up possible restaurants, that will be recommended in self.SystemStateUtterance() # ensure that current state is either not S3 or the utterance asks for another result # otherwise, it would recommend a different restaurant even though the user just asked for confirmation if new_state == State.S3 and (self.state != State.S3 or utterance == 'reqmore' or utterance == 'reqalts' or utterance == 'negate'): self.models.recommend(self.pref_df) # Prints that can be uncommented for debugging (show utterance, state, preferences, new state) # print('') # print('utterance: ') # print(utterance) # print('preference: ') # print(self.pref_df.loc[0]) # print('current state: ') # print(self.state) # print('new state: ') # print(new_state) self.state = new_state def systemStateUtterance(self): # Function that prints a message to the user at the beginning of each state to either ask a question # or inform user about the thing he requested in the previous iteration # Check whether the preferences are filled food = True if self.pref_df['food'].tolist()[0] != '' else False area = True if self.pref_df['area'].tolist()[0] != '' else False price = True if self.pref_df['pricerange'].tolist()[0] != '' else False if self.state == State.S1: self.print_text = self.sys_utter['state1'] print(self.print_text) return # ask for food if preference is not set and multiple restaurants apply for other preferences if self.state == State.S2 and not food: self.models.lookupInRestaurantInfo(self.pref_df) # If there are 0 or 1 restaurants for the preferences, go to state 3 if len(self.models.restaurants) <= 1: self.state = State.S3 self.models.recommend(self.pref_df) # If the length of the restaurant recommendations is >1, continue normally else: self.print_text = self.sys_utter['askfood'] print(self.print_text) return # ask for area if preference is not set and multiple restaurants apply for other preferences if self.state == State.S2 and not area: self.models.lookupInRestaurantInfo(self.pref_df) # If there are 0 or 1 restaurants for the preferences, go to state 3 if len(self.models.restaurants) <= 1: self.state = State.S3 self.models.recommend(self.pref_df) # If the length of the restaurant recommendations is >1, continue normally else: self.print_text = self.sys_utter['askarea'] print(self.print_text) return # ask for price if preference is not set and multiple restaurants apply for other preferences if self.state == State.S2 and not price: self.models.lookupInRestaurantInfo(self.pref_df) # If there are 0 or 1 restaurants for the preferences, go to state 3 if len(self.models.restaurants) <= 1: self.state = State.S3 self.models.recommend(self.pref_df) # If the length of the restaurant recommendations is >1, continue normally else: self.print_text = self.sys_utter['askprice'] print(self.print_text) return if self.state == State.S2 and food and area and price: # when changing a preference in state 3, the user gets send back to state 2. # If however, all preferences are set again, # the user gets asked this irrelevant question to avoid an empty line, where user has to press enter # ask user to either confirm their choice for food, area or price if self.pref_df['food'].tolist()[0] != 'any': self.print_text = self.sys_utter['confirmquestion'].replace('preference_name', 'food')\ .replace('preference_value', self.pref_df['food'].tolist()[0]) print(self.print_text) elif self.pref_df['area'].tolist()[0] != 'any': self.print_text = self.sys_utter['confirmquestion'].replace('preference_name', 'area') \ .replace('preference_value', self.pref_df['area'].tolist()[0]) print(self.print_text) elif self.pref_df['pricerange'].tolist()[0] != 'any': self.print_text = self.sys_utter['confirmquestion'].replace('preference_name', 'pricerange') \ .replace('preference_value', self.pref_df['pricerange'].tolist()[0]) print(self.print_text) return # recommend restaurant if self.state == State.S3: if len(self.models.recommendation) == 0: # Suggest alternative options if there are no options self.suggestRes(self.pref_df) print(self.print_text) elif len(self.models.recommendation ) == 1 and self.models.recommendation[0] == -1: # recommendation is set to -1 if the user looped through all recommended restaurants. # Warning will be printed to make user aware of this self.print_text = self.sys_utter['nomoreresults'] print(self.print_text) else: # suggest possible restaurant self.print_text = self.sys_utter['suggestrest']\ .replace('restaurant_name', self.models.recommendation['restaurantname'])\ .replace('RESTAURANT_NAME',self.models.recommendation['restaurantname']) # Compute implications consequents, reason = self.rules.solveRule( self.models.recommendation) # Inform about the implications for cons in consequents: if consequents[cons] is not None: self.print_text += '\n' text = 'not ' if str(cons) == 'children' or str(cons) == 'long time': text = 'not for ' if consequents[cons]: self.print_text += self.sys_utter['askforimplication'].replace('qualities', cons)\ .replace('QUALITIES', cons) else: self.print_text += self.sys_utter['askforimplication']\ .replace('qualities', ''.join([text, cons])).replace('QUALITIES', ''.join([text, cons])) # "What about .... print(self.print_text) return if self.state == State.S5: self.print_text = self.sys_utter['bye'] print(self.print_text) return def reactToUtterance(self, utterance, user_input): # Function that calls the correct function or prints the correct system utterance # based on the classified utterance. if utterance == 'ack': # same as affirm, kept separate to ease expandability in future, if the usage of one utterance changes if self.state == State.S2: # obligatory question will be asked to user, if he responds yes, go to state 3 # necessary, if user changes one preference in state 3 and goes back to state 2, # even though all preferences are set again return if self.state == State.S3 and len( self.models.recommendation ) != 0 and self.models.recommendation[0] != -1: self.print_text = self.sys_utter['affirm'].replace('restaurant_name', self.models.recommendation['restaurantname'])\ .replace('RESTAURANT_NAME', self.models .recommendation['restaurantname']) print(self.print_text) return if utterance == 'affirm': # same as ack, kept separate to ease expandability in future, if the usage of one utterance changes if self.state == State.S2: # obligatory question will be asked to user, if he responds yes, go to state 3 # necessary, if user changes one preference in state 3 and goes back to state 2, # even though all preferences are set again return if self.state == State.S3 and len( self.models.recommendation ) != 0 and self.models.recommendation[0] != -1: self.print_text = self.sys_utter['affirm'].replace('restaurant_name', self.models.recommendation['restaurantname'])\ .replace('RESTAURANT_NAME', self.models .recommendation['restaurantname']) print(self.print_text) return if utterance == 'bye': # don't need to do anything as it will automatically move to state S5 and print goodbye message return if utterance == 'confirm': food_pref = self.pref_df['food'].tolist()[0] area_pref = self.pref_df['area'].tolist()[0] price_pref = self.pref_df['pricerange'].tolist()[0] confirmtrue = 'confirmtrue' confirmfalse = 'confirmfalse' recommend = False if (self.state == State.S3 or self.state == State.S4) and len(self.models.recommendation) != 0 \ and self.models.recommendation[0] != -1: # if user has restaurant recommended, use the info from that place rather than the search preference food_pref = self.models.recommendation['food'] area_pref = self.models.recommendation['area'] price_pref = self.models.recommendation['pricerange'] confirmtrue = 'confirmtruerest' confirmfalse = 'confirmfalserest' # set recommend to true if there is currently a recommended restaurant recommend = True # Extract preference to confirm new_preferences = self.models.extractPreference( user_input, self.sys_utter) # check what preference did the user ask for # example input: is the restaurant expensive? food = True if new_preferences['food'] != '' else False area = True if new_preferences['area'] != '' else False price = True if new_preferences['pricerange'] != '' else False # check if the preference is correct food_correct = True if food_pref == new_preferences[ 'food'] else False area_correct = True if area_pref == new_preferences[ 'area'] else False price_correct = True if price_pref == new_preferences[ 'pricerange'] else False # check that preference is not empty food_given = True if food_pref != '' else False area_given = True if area_pref != '' else False price_given = True if price_pref != '' else False if food: if food_correct: text = self.sys_utter[confirmtrue].replace('preference_name', 'type')\ .replace('preference_value', food_pref).replace('PREFERENCE_NAME', 'TYPE')\ .replace('PREFERENCE_VALUE', food_pref) elif food_given: text = self.sys_utter[confirmfalse].replace('preference_name', 'type')\ .replace('preference_value', food_pref).replace('PREFERENCE_NAME', 'TYPE')\ .replace('PREFERENCE_VALUE', food_pref) else: text = self.sys_utter[confirmfalse].replace('preference_name', 'type of restaurant')\ .replace('preference_value', 'not specified').replace('PREFERENCE_NAME', 'TYPE OF RESTAURANT')\ .replace('PREFERENCE_VALUE', 'NOT SPECIFIED') if recommend: text = text.replace('restaurant_name', self.models.recommendation['restaurantname'])\ .replace('RESTAURANT_NAME', self.models.recommendation['restaurantname']) print(text) if area: if area_correct: text = self.sys_utter[confirmtrue].replace('preference_name', 'area')\ .replace('preference_value', area_pref).replace('PREFERENCE_NAME', 'AREA')\ .replace('PREFERENCE_VALUE', area_pref) elif area_given: text = self.sys_utter[confirmfalse].replace('preference_name', 'area')\ .replace('preference_value', area_pref).replace('PREFERENCE_NAME', 'AREA')\ .replace('PREFERENCE_VALUE', area_pref) else: text = self.sys_utter[confirmfalse].replace('preference_name', 'area')\ .replace('preference_value', 'not specified').replace('PREFERENCE_NAME', 'AREA')\ .replace('PREFERENCE_VALUE', 'NOT SPECIFIED') if recommend: text = text.replace('restaurant_name', self.models.recommendation['restaurantname'])\ .replace('RESTAURANT_NAME', self.models.recommendation['restaurantname']) print(text) if price: if price_correct: text = self.sys_utter[confirmtrue].replace('preference_name', 'price')\ .replace('preference_value', price_pref).replace('PREFERENCE_NAME', 'PRICE')\ .replace('PREFERENCE_VALUE', price_pref) elif price_given: text = self.sys_utter[confirmfalse].replace('preference_name', 'price')\ .replace('preference_value', price_pref).replace('PREFERENCE_NAME', 'PRICE')\ .replace('PREFERENCE_VALUE', price_pref) else: text = self.sys_utter[confirmfalse].replace('preference_name', 'price')\ .replace('preference_value', 'not specified').replace('PREFERENCE_NAME', 'PRICE')\ .replace('PREFERENCE_VALUE', 'NOT SPECIFIED') if recommend: text = text.replace('restaurant_name', self.models.recommendation['restaurantname'])\ .replace('RESTAURANT_NAME', self.models.recommendation['restaurantname']) print(text) return if utterance == 'deny': # Wrong # I dont want user_input_split = user_input.split() for i in user_input_split: if i == 'dont': for preferences in ['food', 'area', 'pricerange']: if self.pref_df[preferences].tolist()[0] in user_input: # remove preference that was not wanted and reset list of recommended restaurants self.pref_df[preferences] = '' self.models.restaurants = [] return if i == 'wrong': for preferences in ['food', 'area', 'pricerange']: # remove all preferences and reset list of recommended restaurants self.pref_df[preferences] = '' self.models.restaurants = [] return if utterance == 'hello': # don't need to do anything, will automatically restart the conversation return if utterance == 'inform': # Extract preferences of user new_preferences = self.models.extractPreference( user_input, self.sys_utter) # Change preferences where necessary if new_preferences['food'] != '': self.pref_df.at[0, 'food'] = new_preferences['food'] self.models.restaurants = [] if new_preferences['area'] != '': self.pref_df.at[0, 'area'] = new_preferences['area'] self.models.restaurants = [] if new_preferences['pricerange'] != '': self.pref_df.at[0, 'pricerange'] = new_preferences['pricerange'] self.models.restaurants = [] return if utterance == 'negate': # When 'not' is mentioned if 'not' in user_input: for preferences in self.pref_df: if preferences in user_input: self.pref_df[preferences] = '' self.models.restaurant = [] # no in any area or no i want korean food # Extract preferences of user new_preferences = self.models.extractPreference( user_input, self.sys_utter) # Change preferences where necessary if new_preferences['food'] != '': self.pref_df.at[0, 'food'] = new_preferences['food'] self.models.restaurants = [] if new_preferences['area'] != '': self.pref_df.at[0, 'area'] = new_preferences['area'] self.models.restaurants = [] if new_preferences['pricerange'] != '': self.pref_df.at[0, 'pricerange'] = new_preferences['pricerange'] self.models.restaurants = [] return if utterance == 'null': # don't need to do anything, as the text for misunderstanding will be printed if command was not understood # important: use pass not return here to let it print sys_utter['misunderstanding'] pass if utterance == 'repeat': print(self.print_text) return if utterance == 'reqalts': # same as inform new_preferences = self.models.extractPreference( user_input, self.sys_utter) # Change preferences where necessary if new_preferences['food'] != '': self.pref_df.at[0, 'food'] = new_preferences['food'] self.models.restaurants = [] if new_preferences['area'] != '': self.pref_df.at[0, 'area'] = new_preferences['area'] self.models.restaurants = [] if new_preferences['pricerange'] != '': self.pref_df.at[0, 'pricerange'] = new_preferences['pricerange'] self.models.restaurants = [] return if utterance == 'reqmore': # don't need to do anything, as it is already updated in the run method (if new state == S3) return if utterance == 'request': # evaluate the utterance if the user asks for more information (phone number, address, ...) if self.state == State.S4: details = self.models.extractDetails(user_input) for element in details: print(self.sys_utter['details'].replace( 'detail_type', element[0]).replace('detail_info', element[1]).replace( 'DETAIL_TYPE', element[0]).replace('DETAIL_INFO', element[1])) return if utterance == 'restart': self.print_text = self.sys_utter['restart'] print(self.print_text) return if utterance == 'thankyou': # don't need to do anything, as it will automatically move to final state and print bye utterance return # if utterance was not handled above, print message that input was not understood # can for example happen, because it is not defined for the current state self.print_text = self.sys_utter['misunderstanding'] print(self.print_text) return def suggestRes(self, preferences): # Function to suggest alternatives for the restaurant # If a preference is filled, choose one preference to suggest alternatives. Set the other two to 'any'. if preferences.loc[0]['food'] != 'any' or preferences.loc[0][ 'food'] != '': self.pref_df['area'] = 'any' self.pref_df['pricerange'] = 'any' self.models.lookupInRestaurantInfo(self.pref_df) self.models.recommend(self.pref_df) elif preferences.loc[0]['area'] != 'any' or preferences.loc[0][ 'area'] != '': self.pref_df['food'] = 'any' self.pref_df['pricerange'] = 'any' self.models.lookupInRestaurantInfo(self.pref_df) self.models.recommend(self.pref_df) elif preferences.loc[0]['pricerange'] != 'any' or preferences.loc[0][ 'pricerange'] != '': self.pref_df['area'] = 'any' self.pref_df['food'] = 'any' self.models.lookupInRestaurantInfo(self.pref_df) self.models.recommend(self.pref_df) # Suggest start over or the alternative self.print_text = self.sys_utter['alt1'] + '\n' alt_1 = self.sys_utter['alternatives'].replace('restaurant_name', self.models.recommendation['restaurantname'])\ .replace('food_name', self.models.recommendation['food'])\ .replace('area_name', self.models.recommendation['area'])\ .replace('price_range', self.models.recommendation['pricerange'])\ .replace('RESTAURANT_NAME', self.models.recommendation['restaurantname']) \ .replace('FOOD_NAME', self.models.recommendation['food']) \ .replace('AREA_NAME', self.models.recommendation['area']) \ .replace('PRICE_RANGE', self.models.recommendation['pricerange']) self.print_text += alt_1 + '\n' self.print_text += self.sys_utter['alt2']
class BabylonApp(App): """ Class for building the user interface for the Babylon application, inherits from Kivy's App class. """ userInput = UserIn("Example: I want a program to add two numbers.") chat = ChatPage() # Container for adding messages hold = ch() chatPannel = ChatPannel() # Container for scrolling rules = Rules() def build(self): """ Method that is called when the class is initialised. Handels building the user interface for the app. """ #Create the base sections for the app grid = ChatPageMain(1, 3) #Create the header section which contains the #App title and settings button header = ChatPageMain(2, 1) #Set the header to fill 10% of the app height header.size_hint_y = 0.10 #App title set to 80% width of the header title = Lab("Babylon", 0.80, [255, 0, 0, 0.25], 0) #title.size_hint_x = 0.80 #Settings button set to 10% width of the header settings = Button(text="Settings", size_hint_x=0.10) #Add title and settings button to the app header.add_widget(title) header.add_widget(settings) #Create the footer section which contains the #User input and submit button footer = ChatPageMain(2, 1) footer.size_hint_y = 0.10 #User input set to 80% width of the footer self.userInput.size_hint_x = 0.80 #Submit button set to 10% width of the footer submit = Button(text="Submit", size_hint_x=0.10) #On clicking submit call user_submit function submit.bind(on_press=self.user_submit) #Add user input and submit button to the app footer.add_widget(self.userInput) footer.add_widget(submit) #Add header section to the app grid.add_widget(header) #Create the section where the chat will appear #Allow the chat to be scrollable self.chat.bind(minimum_height=self.chat.setter('height')) #Add chat section to the app self.chatPannel.add_widget(self.chat) grid.add_widget(self.chatPannel) #Add footer section to the app grid.add_widget(footer) #When user presses key call the on_key_down function Window.bind(on_key_down=self.on_key_down) return grid #Reset user input to original state def focus_text_input(self, _): """ Mehtod returns focus to the user input section once the user has submitted text """ self.userInput.focus = True self.userInput.do_backspace(from_undo=False, mode='bkspc') def botResponse(self, userInput): """ Method handles getting the response from the bot based on its response. Takes the input from the user and calls method to analyse. it """ chatLog = self.hold.writeFile("./chat.csv", ("bParroting: " + userInput)) def user_submit(self, _): """ Method manages handeling the user input. """ #Refresh the chat chatLog = self.hold.writeFile("./chat.csv", ('u' + self.userInput.text)) self.botResponse(self.userInput.text) self.chatPannel.remove_widget(self.chat) self.chat = ChatPage() self.chat.bind(minimum_height=self.chat.setter('height')) self.chatPannel.add_widget(self.chat) #Set the user input to original state self.userInput.text = '' Clock.schedule_once(self.focus_text_input, 0.1) def on_key_down(self, instance, keyboard, keycode, text, modifiers): """ Method is activated when the user press down a key. It listens for when the user presses enter and submits the user input for analysis. """ #Allows the user to press enter to submit input if keycode == 40: self.user_submit(None)
# logger.log('start load demand',2) demand = People() demand.loadFromXLS(workbook='demand_' + str(year) + '.xlsm', worksheet='demand') # print('demand') if printflag else None # printDict(demand.people,"\t") if printflag else None # logger.log('start load history',2) history = People() history.loadFromXLS('demand_' + str(year) + '.xlsm', worksheet='histor') # print('history') if printflag else None # printDict(history.people,"\t") if printflag else None # logger.log('start load rules',2) rules = Rules() rules.loadFromCSV('rules2_' + str(year) + '.csv') # print('rules') if printflag else None # printDict(rules.rules) if printflag else None # print('rules end') if printflag else None # logger.log('delete demand trainig if it is in history',2) deleted = demand.removeIfTRainigIsInOtherList(history.people) # print('Deleted trainings - is in History '+str(len(deleted))+': '+str(deleted)) if printflag else None # logger.log('delete trainigs without demands and add order',2) deleted2 = demand.deleteIfDependenceIsNotInHistry(history, rules) # printDict(demand.people,"\t") if printflag else None # print('Deleted trainings 2: '+str(deleted2)) if printflag else None # logger.log('make trainings-people object and load',2) prts_for_trainings = Trainings(rules)
def __init__(self): self.rules = Rules() self.alpha = [(),(),-inf] self.beta = [(),(),inf] self.missedPieces =[]
import subprocess import MySQLdb as sql import pushover from Rules import Rules # Determine location of first found DS18B20 sensor base_dir = '/sys/bus/w1/devices/' device_folder = glob.glob(base_dir + '28*')[0] device_file = device_folder + '/w1_slave' # Configure GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Setup Rules rf = Rules('localhost', 'rpi', 'rpi', 'sensordata') # Log data to the MySQL database def logData(id, value): try: # Insert new data cur.execute( "insert into sensor_data(sensor_id,value) values( {0}, {1} )". format(id, value)) # Save changes con.commit() return except: if con: con.rollback()
class AI: def __init__(self): self.rules = Rules() self.alpha = [(),(),-inf] self.beta = [(),(),inf] self.missedPieces =[] def minimax(self,state,depth,playerMove,color): if not playerMove: best = [(), (), -inf] else: best = [(), (), +inf] if depth == 0: if 'N' in color: color = "Blanco" else: color = "Negro" value = self.getStateValue(state,color) return [(), (), value] for row in range(8): for col in range(8): if color[0] in state[row][col]: for move in self.rules.GetListOfValidMoves(state,color,(row,col)): stateCopy=copyBoard(state) x, y = move[0], move[1] stateCopy[x][y] = state[row][col] stateCopy[row][col]="" if('N' in color): score = self.minimax(stateCopy,depth-1,not playerMove,"Blanco") else: score = self.minimax(stateCopy,depth-1,not playerMove,"Negro") score[0], score[1] = (row,col),(x,y) rand = random.randint(0, 100) if not playerMove: if(rand>85): if score[2] >= best[2]: best = score # max value if best[2] >= self.alpha[2]: self.alpha = best else: if score[2] > best[2]: best = score # max value if best[2] > self.alpha[2]: self.alpha = best else: if(rand>85): if score[2] <= best[2]: best = score # min value if best[2] <= self.beta[2]: self.beta = best else: if score[2] < best[2]: best = score # min value if best[2] < self.beta[2]: self.beta = best if self.beta[2]-self.alpha[2]<=0: if not playerMove: self.alpha = [(),(),-inf] else: self.beta = [(),(),inf] return best if not playerMove: self.alpha = [(),(),-inf] else: self.beta = [(),(),inf] return best def play(self,board,color): state=copyBoard(board) #start_time = time.time() move=self.minimax(state,3,False,color) #print("--- %s seconds ---" % (time.time() - start_time)) self.alpha = [(),(),-inf] self.beta = [(),(),inf] if(move[0] == () or move[2]==-inf): fixMoves=[] for row in range(8): for col in range(8): if color[0] in board[row][col]: moves=self.rules.GetListOfValidMoves(board,color,(row,col)) for m in self.rules.GetListOfValidMoves(board,color,(row,col)): fixMoves.append([(row,col),(m[0],m[1]),0]) move=random.choice(fixMoves) #print(move) return move def getStateValue(self,state,myColFull): if myColFull=="Negro": enemyColFull="Blanco" else: enemyColFull="Negro" res=0 res+=self.getStateValueAux(state,myColFull,enemyColFull) res-=(self.getStateValueAux(state,enemyColFull,myColFull))*(1/2) return res def getStateValueAux(self,state,myCol,enemyCol): res=0 for row in range(8): for col in range(8): if(myCol[0] in state[row][col]): res+=self.getPieceValue(state[row][col],row) return res def getMove(self,board,posIni,posFin): tempBoard = copyBoard(board) piece = tempBoard[posIni[0]][posIni[1]] tempBoard[posIni[0]][posIni[1]] = "" tempBoard[posFin[0]][posFin[1]] = piece return tempBoard def getMaxMissedPiece(self,color): values = [] if(len(self.missedPieces)==0): if ('N' in color): return "NP" else: return "BP" for i in range(len(self.missedPieces)): values.append(self.getPieceValue(self.missedPieces[i],0)) maxInd=values.index(max(values)) newPiece =self.missedPieces[maxInd] self.missedPieces.remove(newPiece) return newPiece def getPieceValue(self,piece,row): if ('P' in piece): if len(self.missedPieces)>0: if('N' in piece): if(row==0): return 5 return 1+((row)*0.1) else: if(row==8): return 5 return 1+((8-row)*0.1) else: return 1 elif('A' in piece) or ('C' in piece) : return 3 elif('T' in piece): return 5 elif ('D' in piece): return 9 else: return 0
def get_rules(self): from Rules import Rules Rules = Rules() rule_files = Rules.get_rules() return rule_files
class GameManager(): def __init__(self): self.player1Turn = False self.isGameOver = False self.p1 = player1() self.p2 = player2() self.b1 = [] self.b2 = [] self.b1Copy = [] self.b2Copy = [] self.p1Moves = [] self.p2Moves = [] self.r = Rules() #initializes one game, checks validity of piece placement #returns 1 if player one wins, returns 0 if player 2 wins def startGame(self): self.isGameOver = False #initialize player1 self.p1.amIFirst = self.player1Turn self.p1.startGame() self.b1 = copy.deepcopy(self.p1.pieces) self.b1Copy = copy.deepcopy(self.b1) #check placement of player_ones pieces if (not self.r.checkPieces(self.b1)): print("Invalid piece placement, Player 1 forfeited this game") self.gameOver() return 0 #initialize player2 self.p2.amIFirst = not self.player1Turn self.p2.startGame() self.b2 = copy.deepcopy(self.p2.pieces) self.b2Copy = copy.deepcopy(self.b2) #check placement of player_two pieces if (not self.r.checkPieces(self.b2)): print("Invalid piece placement, Player 2 forfeited this game") self.gameOver() return 1 return self.play() #runs one game, when the game is over it calls the gameOver method then #returns 1 or 0 depending on who won def play(self): #run till game is over while (not self.isGameOver): self.playerShoot() self.gameOver() #if it is my turn to shoot, but the game is over, then I lost if (self.player1Turn): return 0 else: return 1 #Let a player shoot, Check whether the shot hit or missed def playerShoot(self): if (self.player1Turn): [i, j] = self.p1.makeMove() #save move for later analysis self.p1Moves.append([i, j]) #Let player know whether their shot hit missed or sunk self.p1.lastMoveResult = self.checkShot(i, j, self.b2) else: [i, j] = self.p2.makeMove() self.p2.lastMoveResult = self.checkShot(i, j, self.b1) self.p2Moves.append([i, j]) self.player1Turn = not self.player1Turn #check whether a shot hit missed or sunk def checkShot(self, row, col, pieces): #check each piece for p in pieces: #check if shot coordinates are contained in that piece if [row, col] in p: #remove coordinate from the piece p.remove([row, col]) #if piece contains no more coordinates then that ship has sunk if len(p) == 0: pieces.remove(p) #if pieces is empty than all the ships have been sunk if len(pieces) == 0: self.isGameOver = True return -1 #return sunk return 1 # return hit return 0 #return missed #Give each player the data from the other player so they can analyze it if they choose for better #play in the future. def gameOver(self): self.p1.gameOver(self.b2Copy, self.p2Moves) self.p2.gameOver(self.b1Copy, self.p1Moves)
def doCalculation(self): # Create first node y_1 = Rules.getInstance().valueOfY_firstRule z_1 = Rules.getInstance().totalValue_firstRule y_2 = Rules.getInstance().valueOfY_secondRule z_2 = Rules.getInstance().totalValue_secondRule if Rules.getInstance().valueOfX_secondRule > Rules.getInstance( ).valueOfX_firstRule: if Rules.getInstance().valueOfX_firstRule == 1: y_1 = Rules.getInstance( ).valueOfY_firstRule * Rules.getInstance().valueOfX_secondRule z_1 = Rules.getInstance( ).totalValue_firstRule * Rules.getInstance( ).valueOfX_secondRule else: if Rules.getInstance().valueOfX_secondRule % Rules.getInstance( ).valueOfX_firstRule != 0: y_1 = Rules.getInstance( ).valueOfY_firstRule * Rules.getInstance( ).valueOfX_secondRule z_1 = Rules.getInstance( ).totalValue_firstRule * Rules.getInstance( ).valueOfX_secondRule y_2 = Rules.getInstance( ).valueOfY_secondRule * Rules.getInstance( ).valueOfX_firstRule z_2 = Rules.getInstance( ).totalValue_secondRule * Rules.getInstance( ).valueOfX_firstRule else: aConversionValue = Rules.getInstance( ).valueOfX_secondRule / Rules.getInstance( ).valueOfX_firstRule y_1 = Rules.getInstance( ).valueOfY_firstRule * aConversionValue z_1 = Rules.getInstance( ).totalValue_firstRule * aConversionValue elif Rules.getInstance().valueOfX_secondRule < Rules.getInstance( ).valueOfX_firstRule: if Rules.getInstance().valueOfX_secondRule == 1: y_2 = Rules.getInstance( ).valueOfY_secondRule * Rules.getInstance().valueOfX_secondRule else: if Rules.getInstance().valueOfX_firstRule % Rules.getInstance( ).valueOfX_secondRule != 0: y_1 = Rules.getInstance( ).valueOfY_firstRule * Rules.getInstance( ).valueOfX_secondRule z_1 = Rules.getInstance( ).totalValue_firstRule * Rules.getInstance( ).valueOfX_secondRule y_2 = Rules.getInstance( ).valueOfY_secondRule * Rules.getInstance( ).valueOfX_firstRule z_2 = Rules.getInstance( ).totalValue_secondRule * Rules.getInstance( ).valueOfX_firstRule else: aConversionValue = Rules.getInstance( ).valueOfX_firstRule / Rules.getInstance( ).valueOfX_secondRule y_2 = Rules.getInstance( ).valueOfY_secondRule * aConversionValue z_2 = Rules.getInstance( ).totalValue_secondRule * aConversionValue elif Rules.getInstance().valueOfX_secondRule == Rules.getInstance( ).valueOfX_firstRule: y_1 = Rules.getInstance().valueOfY_firstRule z_1 = Rules.getInstance().totalValue_firstRule y_2 = Rules.getInstance().valueOfY_secondRule z_2 = Rules.getInstance().totalValue_secondRule getY_Value = abs(z_1 - z_2) / abs(y_1 - y_2) getX_Value = (Rules.getInstance().totalValue_firstRule - (Rules.getInstance().valueOfY_firstRule * getY_Value)) / Rules.getInstance().valueOfX_firstRule totalValue = (Rules.getInstance().valueOfX * getX_Value) + (Rules.getInstance().valueOfY * getY_Value) self.node = Model_Nodes(0, getX_Value, getY_Value, totalValue) doLoopForCreateTree = True numberOfChildNode = 1 parrentNode = 0 startGetConstraintFrom = "y" listOfPosibleValueNode = dict() while doLoopForCreateTree: getParentValue = { 'x': self.node.getValueOfSelectedNode(parrentNode)['x'], 'y': self.node.getValueOfSelectedNode(parrentNode)['y'] } getMaxValue = max(getParentValue.keys(), key=(lambda k: getParentValue[k])) if self.number_of_digits_post_decimal( getParentValue['x'] ) != None and self.number_of_digits_post_decimal( getParentValue['y']) != None: getMaxValue = max(getParentValue.keys(), key=(lambda k: getParentValue[k])) else: if self.number_of_digits_post_decimal( getParentValue['x'] ) != None and self.number_of_digits_post_decimal( getParentValue['y']) == None: getMaxValue = 'x' elif self.number_of_digits_post_decimal( getParentValue['x'] ) == None and self.number_of_digits_post_decimal( getParentValue['y']) != None: getMaxValue = 'y' # if self.number_of_digits_post_decimal(getParentValue[getMinValue]) == None : # if getMinValue == 'x' : # getMinValue = 'y' # elif getMinValue == 'y': # getMinValue = 'x' if startGetConstraintFrom == "x": getX_Value_right = int(getParentValue[getMaxValue]) getY_Value_right = (Rules.getInstance().totalValue_secondRule - (Rules.getInstance().valueOfX_secondRule * getX_Value_right) ) / Rules.getInstance().valueOfY_secondRule getZ_Value_right = ( Rules.getInstance().valueOfX * getX_Value_right) + ( Rules.getInstance().valueOfY * getY_Value_right) if getZ_Value_right > self.node.getValueOfSelectedNode(0)['z']: self.node.setNodesRight(numberOfChildNode, getX_Value_right, getY_Value_right, getZ_Value_right, parrentNode, "infeasible") else: self.node.setNodesRight(numberOfChildNode, getX_Value_right, getY_Value_right, getZ_Value_right, parrentNode) getX_Value_left = int(getParentValue[getMaxValue]) + 1 getY_Value_left = ( Rules.getInstance().totalValue_firstRule - (Rules.getInstance().valueOfX_firstRule * getX_Value_left)) / Rules.getInstance().valueOfY_firstRule getZ_Value_left = ( Rules.getInstance().valueOfX * getX_Value_left) + ( Rules.getInstance().valueOfY * getY_Value_left) if getZ_Value_left > self.node.getValueOfSelectedNode(0)['z']: self.node.setNodesLeft(numberOfChildNode + 1, getX_Value_left, getY_Value_left, getZ_Value_left, parrentNode, "infeasible") else: self.node.setNodesLeft(numberOfChildNode + 1, getX_Value_left, getY_Value_left, getZ_Value_left, parrentNode) elif startGetConstraintFrom == "y": getY_Value_right = int(getParentValue[getMaxValue]) + 1 getX_Value_right = (Rules.getInstance().totalValue_secondRule - (Rules.getInstance().valueOfY_secondRule * getY_Value_right) ) / Rules.getInstance().valueOfX_secondRule getZ_Value_right = ( Rules.getInstance().valueOfX * getX_Value_right) + ( Rules.getInstance().valueOfY * getY_Value_right) if getZ_Value_right > self.node.getValueOfSelectedNode(0)['z']: self.node.setNodesRight(numberOfChildNode, getX_Value_right, getY_Value_right, getZ_Value_right, parrentNode, "infeasible") else: self.node.setNodesRight(numberOfChildNode, getX_Value_right, getY_Value_right, getZ_Value_right, parrentNode) getY_Value_left = int(getParentValue[getMaxValue]) getX_Value_left = ( Rules.getInstance().totalValue_firstRule - (Rules.getInstance().valueOfY_firstRule * getY_Value_left)) / Rules.getInstance().valueOfX_firstRule getZ_Value_left = ( Rules.getInstance().valueOfX * getX_Value_left) + ( Rules.getInstance().valueOfY * getY_Value_left) if getZ_Value_left > self.node.getValueOfSelectedNode(0)['z']: self.node.setNodesLeft(numberOfChildNode + 1, getX_Value_left, getY_Value_left, getZ_Value_left, parrentNode, "infeasible") else: self.node.setNodesLeft(numberOfChildNode + 1, getX_Value_left, getY_Value_left, getZ_Value_left, parrentNode) if self.node.getValueOfSelectedNode( numberOfChildNode + 1 )['status'] != "infeasible" and self.number_of_digits_post_decimal( getZ_Value_left) == None: listOfPosibleValueNode[numberOfChildNode + 1] = self.node.getValueOfSelectedNode( numberOfChildNode + 1)['z'] if self.node.getValueOfSelectedNode( numberOfChildNode )['status'] != "infeasible" and self.number_of_digits_post_decimal( getZ_Value_right) == None: listOfPosibleValueNode[ numberOfChildNode] = self.node.getValueOfSelectedNode( numberOfChildNode)['z'] if getZ_Value_right > getZ_Value_left: if self.node.getValueOfSelectedNode( numberOfChildNode + 1 )['status'] != "infeasible" and self.number_of_digits_post_decimal( getZ_Value_left) != None: parrentNode = numberOfChildNode + 1 else: if self.node.getValueOfSelectedNode( numberOfChildNode )['status'] != "infeasible" and self.number_of_digits_post_decimal( getZ_Value_right) != None: parrentNode = numberOfChildNode else: doLoopForCreateTree = False break elif getZ_Value_right < getZ_Value_left: if self.node.getValueOfSelectedNode( numberOfChildNode )['status'] != "infeasible" and self.number_of_digits_post_decimal( getZ_Value_right) != None: parrentNode = numberOfChildNode else: doLoopForCreateTree = False break numberOfChildNode = numberOfChildNode + 2 if startGetConstraintFrom == "x": startGetConstraintFrom = "y" elif startGetConstraintFrom == "y": startGetConstraintFrom = "x" # if numberOfChildNode == 7 : # doLoopForCreateTree = False # break self.node.showDetail() getNode = max(listOfPosibleValueNode.keys(), key=(lambda k: listOfPosibleValueNode[k])) print("node yang memenuhi persyaratan adalah: \n") print("Number of node: " + str(self.node.getValueOfSelectedNode(getNode)['NumberNode'])) print("X value: " + str(self.node.getValueOfSelectedNode(getNode)['x'])) print("Y value: " + str(self.node.getValueOfSelectedNode(getNode)['y'])) print("Z value: " + str(self.node.getValueOfSelectedNode(getNode)['z'])) print("Status: " + str(self.node.getValueOfSelectedNode(getNode)['status']))
class NewGame: def __init__(self): self.players = {} #Player dictionary. self.total = 1 # Keeps count of the number of active players. self.rules = Rules() #This function modifys the Rules class with the input of the user. def rule_change(self): rulescreen = tkinter.Tk() rulescreen.title("MyScrabble") rulescreen.geometry('400x250+700+400') rulescreen.configure(background='#0F0268') def rule_confirm(): self.rules.set_board_size(boardsize.get()) self.rules.set_turn_time_limit(turntime.get()) self.rules.set_game_time_limit(gametime.get()) self.rules.set_rack_size(racksize.get()) print(self.rules.get_details()) rulescreen.destroy() tkinter.Label(rulescreen, text="Board Size:", bg='#0F0268', fg='white', font=("Segoe UI Bold", 13)).place(x=40, y=40) tkinter.Label(rulescreen, text="Turn Time:", bg='#0F0268', fg='white', font=("Segoe UI Bold", 13)).place(x=40, y=70) tkinter.Label(rulescreen, text="Game Time:", bg='#0F0268', fg='white', font=("Segoe UI Bold", 13)).place(x=40, y=100) tkinter.Label(rulescreen, text="Rack Size:", bg='#0F0268', fg='white', font=("Segoe UI Bold", 13)).place(x=40, y=130) boardsize = tkinter.Entry(rulescreen) boardsize.place(x=240, y=40) boardsize.insert(0, self.rules.board_size) turntime = tkinter.Entry(rulescreen) turntime.place(x=240, y=70) turntime.insert(0, self.rules.turn_time_limit) gametime = tkinter.Entry(rulescreen) gametime.place(x=240, y=100) gametime.insert(0, self.rules.game_time_limit) racksize = tkinter.Entry(rulescreen) racksize.place(x=240, y=130) racksize.insert(0, self.rules.rack_size) tkinter.Button(rulescreen, font=("Segoe UI Bold", 13), borderwidth=5, text="Confirm Rules", width=15, height=1, command=rule_confirm).place(x=120, y=180) rulescreen.mainloop() def play_online(self): pass def play_local(self): homescreen.destroy() setup = tkinter.Tk() setup.title("MyScrabble") setup.geometry('450x600+720+200') setup.configure(background='#0F0268') def player_confirm(): userlist = users.get().split(",") usercolours = colours.get().split(",") for x in range(0, len(userlist)): self.add_player(userlist[x], usercolours[x], "English", x + 1) for y in range(1, len(userlist) + 1): print(self.players[y].get_all()) #######Commands to jump to board go here##### scrabble = Game() scrabble.run() setup.destroy() pixelVirtual = tkinter.PhotoImage(width=1, height=1) tkinter.Label(setup, bg="#C82323", image=pixelVirtual, width=303, height=88, compound="c").place(x=72, y=48) tkinter.Label(setup, text="MyScrabble", font=("Segoe UI Bold", 38), bg="#FF1717", fg="white", image=pixelVirtual, width=293, height=78, compound="c").place(x=76, y=52) tkinter.Label(setup, text="Player Names:", bg="#0F0268", fg="white", image=pixelVirtual, width=174, height=33, compound="c", font=("Segoe UI Bold", 20)).place(x=47, y=184) tkinter.Label(setup, text="Player Colours:", bg="#0F0268", fg="white", image=pixelVirtual, width=190, height=33, compound="c", font=("Segoe UI Bold", 20)).place(x=47, y=256) tkinter.Button(setup, font=("Segoe UI Bold", 13), borderwidth=5, text="Edit Rules", image=pixelVirtual, width=119, height=25, compound="c", command=test.rule_change).place(x=163, y=455) users = tkinter.Entry(setup, width=30) users.place(x=240, y=200) colours = tkinter.Entry(setup, width=28) colours.place(x=250, y=270) tkinter.Button(setup, font=("Segoe UI Bold", 25), image=pixelVirtual, borderwidth=5, height=68, width=201, text="Start Game", compound="c", command=player_confirm).place(x=121, y=362) setup.mainloop() # Creates a new player and adds it to the player dictionary. def add_player(self, name, player_colour, language, turn): new_player = Player(name, player_colour, language, turn) # Creates an object for a player. self.players[ self. total] = new_player # adds to the player_dict which is a dictionary. self.total = self.total + 1 # Increments the player count by one. return
import pushover from Rules import Rules rf = Rules( 'localhost', 'rpi', 'rpi', 'sensordata' ) rf.run_rule( 1 ) pushover.send_notification( rf.getDescription(), rf.getOutput(), None, None )
def runSim(self): lowPopFlag = False for i in range(1, self.numTimePeriods+1): if lowPopFlag: break newTrans = 0 numInts = int(round(self.intsPerTime * self.newPop.getSize())) for j in range(1,numInts+1): deadCheck = True while deadCheck: edgeNum = random.randint(0, len(self.newPop.agents.es)-1) randEdge = self.newPop.agents.es[edgeNum] vert1 = self.newPop.agents.vs[randEdge.source] vert2 = self.newPop.agents.vs[randEdge.target] agent1 = vert1["Agent"] agent2 = vert2["Agent"] newInt = Interaction(agent1, agent2) deadCheck = newInt.deadCheck() newInt.setStartVals() newRule = Rules([agent1, agent2]) newResult = newRule.gameResult(self.meanPosVal, self.meanAvoidVal) if newResult[0] == "Avoid": vert1["Agent"].updateValue(newResult[1]) vert2["Agent"].updateValue(newResult[2]) else: newTrans = newTrans + vert1["Agent"].updateDisease(vert2["Agent"], newResult[1]) newTrans = newTrans + vert2["Agent"].updateDisease(vert1["Agent"], newResult[2]) newInt.setEndVals() if self.logInteractions == True: interaction = [i, j, newInt, newRule, newResult] self.intLog.append(interaction) self.newPop.updateSickTime() self.newPop.updateDead() self.totalInts = self.totalInts + numInts self.newPop.logEnd() R0 = self.newPop.calcRo() newLogVals = [i, self.newPop.getSize(), self.newPop.getFinalSick(), self.newPop.getFinalImmune(), newTrans, R0, numInts] self.timeLog.append(newLogVals) print('Completed time ' + str(i)) if lowPopFlag: break newLogVals = [i, numInts, self.newPop.getFinalSick(), self.newPop.getFinalImmune(), newTrans] self.totalInts = self.totalInts + numInts self.timeLog.append(newLogVals) totalDied = self.newPop.calcNumDied() totalImmune = self.newPop.getFinalImmune() self.runVals.append(totalDied) self.runVals.append(totalImmune) self.endTime = time.time() self.runTime = round((self.endTime - self.startTime), 2) self.timePerInt = self.runTime / self.totalInts print('The simulation ran in ' + str(self.runTime) + ' seconds') print('Total number of interactions simulated: ' + str(self.totalInts)) print('Effective time per interaction: ' + str(self.timePerInt)) return self
from Analysis import Analysis from datetime import datetime, timedelta from Rules import Rules API_KEY = "ff5c476f-1b99-4fc7-a747-0bed31268f11" #The API Key of the monitor ENDPOINT = "https://graph.api.smartthings.com/api/smartapps/installations/39077465-2039-4f2b-87d7-07807b0cd548" #The API endpoint of the monitor IMPORTANT = ["Door"] #important devices to keep track of state changes log_output = 'deviceInfos/alldevicelog.txt' #output folder for analysis of device logs rule_output = 'deviceInfos/alldevicerule.txt' #output folder for analysis of log according to rules rule_input = 'rules/rule.txt' #input for our rules #rule_input = None #since = datetime.utcnow() - timedelta(minutes=110) #check interaction since last hour print("Analyzing events since") since = None if not since: print(datetime.utcnow() - timedelta(days = 7)) else: print(since) An = Analysis(API_KEY, ENDPOINT, important = IMPORTANT) An.analyze(log_output, since) if rule_input: print("rule file:" + rule_input) Ru = Rules(rule_input, An.mevents, An.allevts, An.items) Ru.ruleAnalysis(rule_output)
def __init__(self): self.database = Database() self.rules = Rules(self.database)
class API_Rules(): reader = JSON() text_analysis = TA() write = PC() new_line = "\n" indent = " " imports = [] test_r = Rules() pro = "" def api_rule_test(self, sentence): hold = sentence program = '' count = 0 file = input("What do you want to call file: ") file_add = {file: {"functions": []}} func_list_in = input( "What functoion(s) would you like to create, e.g. get, post, put... \n Input list of functions e.g. get, post, pacth: " ) func_list_in = func_list_in.replace(" ", "") func_list = func_list_in.split(",") hold = self.reader.getData("py", "functions") data_funcs = ["post", "put", "patch"] program = "" for key in hold: if key in func_list: func = hold[key] imp = func["import"] if imp not in self.imports: self.imports.append(imp) name = input("What do you want to call the function: ") temp_func = file_add[file]["functions"] temp_func.append(name) file_add[file]["functions"] = temp_func line_one = func["start"] line_one = line_one.replace("<name>", name) address = input("What url are you trying to call: ") user_input = [ "url", ] params = [ address, ] line_two = func["body"] line_three = '"' + address + '"' + ", " alt_three = "\"" + "url" + "\"" + ", " if key in data_funcs: data_query = input( "This function can pass data as JSON, do you wish to pass data. \n Yes or No " ) d = False data = {} if data_query.lower() == "yes": d = True else: d = False while d == True: key_value = input( "Enter data in key value pairs seperated by a comma (e.g. key,value), to end type end. \n Data: " ) if key_value == "end": d = False else: key_value = key_value.replace(":", ",") #key_value = key_value.replace(" ", "") temp = key_value.split(",") if len(temp) == 2: data[temp[0]] = temp[1] else: print("Not recognised") if len(data) > 0: temp_hold = func["data_json"] temp_hold = temp_hold.replace("<data>", str(json.dumps(data))) line_three += temp_hold + ", " params.append(data) user_input.append("data") temp_hold = func["data_json"] temp_hold = temp_hold.replace("<data>", "data") alt_three += temp_hold + ", " query = input( "Is there any query string parameters, e.g. www.test.com/?q=test. Yes or No: " ) querys = {} q = False if query.lower() == "yes": q = True else: q = False while q == True: key_value = input( "Enter querys in key value pairs seperated by a comma (e.g. key,value), to end type end. \n Query: " ) if key_value == "end": q = False else: key_value = key_value.replace(":", ",") #key_value = key_value.replace(" ", "") temp = key_value.split(",") if len(temp) == 2: querys[temp[0]] = temp[1] else: print("Not recognised") if len(querys) > 0: temp_hold = func["params"] temp_hold = temp_hold.replace("<query>", str(querys)) line_three += temp_hold + ", " params.append(querys) user_input.append("query") temp_hold = func["params"] temp_hold = temp_hold.replace("<query>", "query") alt_three += temp_hold + ", " head = input( "Is there any header parameters, e.g. Autherization : token. Yes or No: " ) headers = {} h = False if head.lower() == "yes": h = True else: h = False while h == True: key_value = key_value.replace(" ", "") key_value = input( "Enter header values in key value pairs seperated by a comma (e.g. key,value), to end type end. \n Header: " ) if key_value == "end": h = False else: key_value = key_value.replace(":", ",") #key_value = key_value.replace(" ", "") temp = key_value.split(",") if len(temp) == 2: headers[temp[0]] = temp[1] else: print("Not recognised") if len(headers) > 0: temp_hold = func["headers"] temp_hold = temp_hold.replace("<head>", str(headers)) line_three += temp_hold + ", " params.append(headers) user_input.append("head") temp_hold = func["headers"] temp_hold = temp_hold.replace("<head>", "head") alt_three += temp_hold + ", " auth = input( "Is there any authorisation parameters, e.g. username, password. Yes or No: " ) if auth.lower() == "yes": cred = input( "Enter credentials sperated by a comma, e.g. user, pass. \n username, password: "******",") pass_hold = (cred[0], cred[1]) temp_hold = func["auth"] temp_hold = temp_hold.replace("<user>", "\"" + pass_hold[0] + "\"") temp_hold = temp_hold.replace("<pass>", "\"" + pass_hold[1] + "\"") line_three += temp_hold + ", " params.append(pass_hold) user_input.append("auth") temp_hold = func["auth_rep"] temp_hold = temp_hold.replace("<name>", "auth") alt_three += temp_hold + ", " var = input( "Do you want to verify SSL certificate. Yes or No: ") if var.lower() == "no": var = False temp_hold = func["verify"] temp_hold = temp_hold.replace("<ver>", str(var)) line_three += temp_hold + ", " params.append(var) user_input.append("verify") temp_hold = func["verify"] temp_hold = temp_hold.replace("<ver>", "verify") alt_three += temp_hold + ", " time_out = input( "Do you want to set a timeout for call. Yes or No: ") if time_out.lower() == "yes": tim = int( input( "Enter timeout, e.g. 1.15 is 1 minute 15 seconds. \n Time: " )) temp_hold = func["timeout"] temp_hold = temp_hold.replace("<tim>", str(tim)) line_three += temp_hold params.append(tim) user_input.append("timeout") temp_hold = func["timeout"] temp_hold = temp_hold.replace("<tim>", "timeout") alt_three += temp_hold + ", " line_param = "" for i in user_input: line_param += i + ", " line_four = func["body2"] line_five = "" line_six = func["body3"] line_seven = func["return_fail"] ret = input( "How do you want the response, \n for status code type S, for response in text format type T, for response in JSON formate type J, for specific data type D. \n Return: " ) if ret.lower() == "s": line_five = func["return_response"] elif ret.lower() == "t": line_five = func["return_text"] elif ret.lower() == "d": key = input( "Name of data being searched for, e.g. autherization. \n Name: " ) temp_hold = func["return_spec"] temp_hold = temp_hold.replace("<name>", str(key)) line_five = temp_hold + ", " else: line_five = func["return_json"] if line_three[-2:-1] == ",": line_three = line_three[:-2] if line_param[-2:-1] == ",": line_param = line_param[:-2] if alt_three[-2:-1] == ",": line_param = line_param[:-2] line_param.strip() line_three.strip() end_start = func["end"] body_end = func["bod_end"] save = input( "Do you want to save the settings input or save function as generic template. Yes for saving input, No for saving as generic template. \n Yes or No: " ) start = "" body = "" if save.lower() == "yes": start = line_one + end_start + self.new_line + self.indent body = line_two + line_three + body_end + self.new_line + self.indent \ + line_four + self.new_line + self.indent \ + self.new_line + self.indent + self.indent + line_five \ + self.new_line + self.indent + line_six \ + self.new_line + self.indent + self.indent + line_seven else: start = line_one + line_param + end_start + self.new_line + self.indent body = line_two + alt_three + body_end + self.new_line + self.indent \ + line_four + self.new_line + self.indent \ + self.new_line + self.indent + self.indent + line_five \ + self.new_line + self.indent + line_six \ + self.new_line + self.indent + self.indent + line_seven program += start + body + self.new_line + self.new_line line_zero = "" imp_code = self.reader.getData("py", "import") for imp in self.imports: line_zero_hold = imp_code line_zero_hold = line_zero_hold.replace("<name>", imp) line_zero += line_zero_hold + self.new_line print(line_zero, program) write_conf = input( "Do you want to write the program to file? \n Yes or No: ") if write_conf.lower() == "yes": data = self.reader.loadData("apis") data[file] = file_add[file] self.reader.addData("apis", data) self.write.write_line(file + ".py", (line_zero + program)) self.pro = line_zero + program return line_zero + program else: self.pro = line_zero + program return line_zero + program def call_api(self): data = self.reader.loadData("apis") for key in data: print(key) temp_hold = self.reader.getData("apis", key) print(temp_hold["functions"]) select = input( "Enter file and function. e.g. Test, test_get. \n Pair: ") select = select.replace(":", ",") select = select.replace(" ", "") temp = select.split(",") if len(temp) == 2: self.test_r.run_program(temp[0], {}, temp[1]) self.test_r.run_pro("run_pro.py") else: print("I can not handle that")
class Parser: def __init__(self): self.database = Database() self.rules = Rules(self.database) #self.messenger = Messenger() def parse(self,msgqueue,command): #print "Command received: "+command ''' rules: if a connection is matched, should be blocked. if a connection is not matched, just log is. if a connection is matched as an alert, the messenger thread must be alerted problem: we have to alert the messenger somehow. solution: alert all the threads and the messenger thread will hold the message to themself ''' ## EDIT RULE # RULE(id,description,source_object,source_port,destination_ip,destination_port,service,parameters,enabled,alert) expr = re.compile("^RULE\((.+)\)$",re.I|re.S) match = expr.match(command) if match: data = match.group(1).strip() rule = data.split(",") if len(rule) < 10 and rule[1] != "delete": return "Invalid Arguments" if self.rules.editRule(rule) == True: self.rules.loadRules() return "OK" else: return "FAIL" # OBJECT(id,name,value) expr = re.compile("^OBJECT\((.+)\)$",re.I|re.S) match = expr.match(command) if match: data = match.group(1).strip() rule = data.split(",") if len(rule) < 3 and rule[1] != "delete": return "Invalid Arguments" if self.rules.editObject(rule) == True: self.rules.loadRules() return "OK" else: return "FAIL" ## NEW CONNECTION expr = re.compile("^NEW\((.+)\)$",re.I|re.S) match = expr.match(command) if match: data = match.group(1).strip() connection = data.split(",") if len(connection) < 5: return "Invalid Arguments" self.rules.logConnection(connection) alert_desc = [] ret = self.rules.createRuleIfMatch(connection,alert_desc) if ret == 0: ## did not match any rule or alert pass elif ret == 1: ## rule was created! pass elif ret == 2: ## alert match, tell messenger msgqueue.put("messenger: ALERT("+','.join(alert_desc)+")") return "OK" return "OK"
def show_rules(self): self.rules = Rules() self.rules.show()
class Game: def __init__(self, player1, player2): pygame.init() pygame.font.init() self.player1 = player1 self.player2 = player2 self.neutralPlayer = Player('neutral', 10000000000000, 3, 'Neutrals') self.factory1 = UnitFactory(player1, self) self.factory2 = UnitFactory(player2, self) self.factoryNeutral = UnitFactory(self.neutralPlayer, self) self.player1.factory = self.factory1 self.player2.factory = self.factory2 self.neutralPlayer.factory = self.factoryNeutral self.board = Board(self) bw, bh = self.board.real_size_with_offsets() self.cpanel = CPanel(self, bw, self.board.top_offset, 400, self.board.real_size_with_offsets()[1]) self.screen = pygame.display.set_mode((bw + self.cpanel.width, bh)) self.clock = pygame.time.Clock() self.gamestate = GameState(player1, self) self.rules = Rules(self) self.render_mode = 'normal' self.board.generate_neutrals(Rules.NEUTRAL_GENERATING_STRATEGY()) def render(self): self.board.render() self.cpanel.render() def endmove(self): if isinstance(self.gamestate.chosen_unit, Unit): self.gamestate.chosen_unit.chosen = False self.gamestate.chosen_unit = None self.gamestate.state = 0 self.board.endmove() self.gamestate.player = self.player1 if self.gamestate.player == self.player2 else self.player2 self.cpanel.endmove() self.player1.gold += self.rules.gold_add(self.player1) self.player2.gold += self.rules.gold_add(self.player2) self.neutralPlayer.act() res = self.rules.game_result() if res != 0: print('Player {} win!!!'.format(res)) exit(0) def handle_keyup(self, key): zero = self.gamestate.state == 0 if key == ord('e'): self.endmove() elif key == 308 or key == ord('q'): self.gamestate.default() elif key == ord('f') and zero: self.try_choose_unit_to_train('footman') elif key == ord('g') and zero: self.try_choose_unit_to_train('grunt') elif key == ord('r') and zero: self.try_choose_unit_to_train('rifleman') elif key == ord('h') and zero: self.try_choose_unit_to_train('headhunter') elif key == ord('p') and zero: self.try_choose_unit_to_train('priest') elif key == ord('b') and zero: self.try_choose_unit_to_train('bomber') elif key == ord('c') and zero: self.gamestate.state = 3 elif key == ord('s') and zero: if self.render_mode == 'normal': self.render_mode = 'subordination' else: self.render_mode = 'normal' def try_choose_unit_to_train(self, name): if self.gamestate.player.factory.affordable(name): self.gamestate.state = 2 # gamestate 2: ready to drop unit self.gamestate.chosen_unit = name def handle_mouseup(self, pos, mouse_button): cell = self.board.get_cell(pos) button = self.cpanel.get_button(pos) if self.gamestate.state == 0: if not cell is None and mouse_button == 1: unit = self.board.units_array[cell[0]][cell[1]] if not unit is None and unit.owner == self.gamestate.player: self.gamestate.state = 1 self.gamestate.chosen_unit = unit unit.chosen = True elif not button is None: if button == "endmove": self.endmove() elif button.startswith('train_'): name = button[6:] self.try_choose_unit_to_train(name) else: self.gamestate.default() elif self.gamestate.state == 1: if not cell is None and mouse_button == 3: unit = self.gamestate.chosen_unit if unit.able(cell): unit.take_action(cell) elif not cell is None and mouse_button == 1: unit = self.board.units_array[cell[0]][cell[1]] if not unit is None and unit.owner == self.gamestate.player: self.gamestate.chosen_unit.chosen = False self.gamestate.chosen_unit = unit unit.chosen = True else: self.gamestate.default() elif not button is None and mouse_button == 1: if button == 'endmove': self.endmove() elif button.startswith('train_'): name = button[6:] self.try_choose_unit_to_train(name) else: self.gamestate.default() elif self.gamestate.state == 2: if not cell is None and mouse_button == 1: unit = self.board.units_array[cell[0]][cell[1]] if self.gamestate.player.factory.creatable(self.gamestate.chosen_unit, cell): self.gamestate.player.factory.create_unit(self.gamestate.chosen_unit, cell) elif not unit is None and unit.owner == self.gamestate.player: self.gamestate.chosen_unit = unit unit.chosen = True self.gamestate.state = 1 else: self.gamestate.default() elif not button is None and mouse_button == 1: if button == 'endmove': self.endmove() elif button.startswith('train_'): name = button[6:] self.try_choose_unit_to_train(name) else: self.gamestate.default() elif self.gamestate.state == 3: # state of choosing first (child) unit for bounding if not cell is None and mouse_button == 1: unit = self.board.units_array[cell[0]][cell[1]] if not unit is None and unit.owner == self.gamestate.player: self.gamestate.state = 4 self.gamestate.chosen_unit = unit unit.chosen_to_bound = True else: self.gamestate.default() else: self.gamestate.default() elif self.gamestate.state == 4: if not cell is None and mouse_button == 1: unit = self.board.units_array[cell[0]][cell[1]] if not unit is None and unit.owner == self.gamestate.player and\ self.gamestate.chosen_unit.able_to_set_parent(unit): self.gamestate.chosen_unit.set_parent(unit) self.gamestate.default() else: self.gamestate.default() def run(self): while True: self.clock.tick(50) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONUP: try: self.handle_mouseup(event.pos, event.button) except Exception: print('Error =(') elif event.type == pygame.KEYUP: try: self.handle_keyup(event.key) except Exception: print("Error =(") self.render() pygame.display.flip()
import subprocess import MySQLdb as sql import pushover from Rules import Rules # Determine location of first found DS18B20 sensor base_dir = '/sys/bus/w1/devices/' device_folder = glob.glob( base_dir + '28*' )[0] device_file = device_folder + '/w1_slave' # Configure GPIO GPIO.setmode( GPIO.BCM ) GPIO.setwarnings( False ) # Setup Rules rf = Rules( 'localhost', 'rpi', 'rpi', 'sensordata' ) # Log data to the MySQL database def logData( id, value): try: # Insert new data cur.execute( "insert into sensor_data(sensor_id,value) values( {0}, {1} )".format( id, value ) ) # Save changes con.commit() return except: if con: con.rollback() return # Controle state for LED pin (turn on/off the connected LED)
cipherDistance = 1 #choose the number of robots, needs at least 2, no catch for invalid/non-int inputs print("Choose the number of robots:") numRobotsInput = int(input()) if numRobotsInput < 2: numRobots = 2 else: numRobots = numRobotsInput if(badBots): print("Please give the number of malicious robots: ") numBad = int(input()) numRobots+=numBad rules = Rules(numRobots, m, condition) rules.start() robots = [] robotIDs = [] numGoodBots = numRobots-numBad for i in range(0,numGoodBots): uniqueIDfound = False while not uniqueIDfound: newID = random.randint(1, 99) if newID not in robotIDs: uniqueIDfound = True robotIDs.append(newID)