def __init__(self): super().__init__() # 게임을 불러옴 self.game = Logic() # 전체 설정 self.setWindowTitle("BalckJack") self.setGeometry(300, 300, 500, 500) mainLayout = QGridLayout() # 딜러, 플레이어 패 레이아웃 설정 dealerBar = QLabel() dealerBar.setText("Dealer Bar") self.dealerLayout = QHBoxLayout() playerBar = QLabel() playerBar.setText("Player Bar") self.playerLayout = QHBoxLayout() # 메인레이아웃에 배치 mainLayout.addWidget(dealerBar, 0, 0, 1, 2) mainLayout.addLayout(self.dealerLayout, 1, 0, 1, 2) mainLayout.addWidget(playerBar, 2, 0, 1, 2) mainLayout.addLayout(self.playerLayout, 3, 0, 1, 2) # 상황판 배치 self.statusBox = QTextEdit() self.statusBox.setReadOnly(True) mainLayout.addWidget(self.statusBox, 4, 0, 1, 2) # 슬라이더 LCD 배치 self.poolSlider = QSlider(Qt.Horizontal) self.poolSlider.setRange(0, self.game.getMoney()) self.poolSlider.setSingleStep(1) poolLCD = QLCDNumber() self.poolSlider.valueChanged.connect(poolLCD.display) sliderLayout = QGridLayout() sliderLayout.addWidget(self.poolSlider, 1, 0) sliderLayout.addWidget(poolLCD, 0, 0) mainLayout.addLayout(sliderLayout, 5, 0) # 버튼 배치 buttonLayout = QGridLayout() self.raiseButton = Button('Raise', self.raiseEvent) self.dieButton = Button('Die', self.dieEvent) self.stayButton = Button('Stay', self.stayEvent) self.hitButton = Button('Hit', self.hitEvent) buttonLayout.addWidget(self.raiseButton, 0, 0) buttonLayout.addWidget(self.stayButton, 0, 1) buttonLayout.addWidget(self.dieButton, 1, 0) buttonLayout.addWidget(self.hitButton, 1, 1) mainLayout.addLayout(buttonLayout, 5, 1) # 전체 설정 self.setLayout(mainLayout) self.show() # 게임 시작 self.hitEvent()
def __init__(self, left_policy): Logic.__init__( self, left_policy) self.dql = Network( [23, 50, 1]) # self.dql.load( # './neuron/weight_7000.npy', './neuron/bias_7000.npy') self.dql.load( './new_neuron/weight_500.npy', './new_neuron/bias_500.npy')
def __init__(self): self.pixel_size = 20 self.camera = Webcam() self.size = self.camera.get_size() self.width = self.size[0] self.height = self.size[1] self.window = Window(self.width, self.height) self.logic = Logic(self.pixel_size, self.width, self.height, self.camera) self.run()
def testJudge(self): # 测试Logic类中的Judge函数 self.logic = Logic('test_1_JPG_63x25.jpg') self.logic = Logic('test_2_JPG_500x350.jpg') self.logic = Logic('test_3_JPG_500x519.jpg') self.logic = Logic('test_4_JPG_280x280.jpg') self.logic = Logic('test_5_JPG_288x288.jpg') self.logic = Logic('test_6_PNG_500x439.png') self.logic = Logic('test_7_PNG_15x15.png') self.logic = Logic('test_8_PNG_121X121.png') self.logic = Logic('test_9_PNG_46X32.png') self.logic = Logic('test_9_PNG_46X32.png') print('testJudge')
def Main(self): self.fps = 120 self.clock = pygame.time.Clock() window.fill((0, 0, 0)) self.logic = Logic(width, height, 1, window) while True: self.logic.run() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() pygame.display.update() self.clock.tick(self.fps)
def __init__(self, database_worker, sound_player): super().__init__() self.database_worker = database_worker self.sound_player = sound_player self.player = 'anonymous' self.get_name() self.status_bar_text = 'Space: pause, Esc: quit' self.cell = 40 self.pause = True self.logic = Logic() self.timer = QTimer() self.theme_worker = ThemeWorker() self.play_sounds = True self.init_ui()
class IFC_Interface_infos(Frame): def __init__(self, window, file_reader, itemId, **kwargs): Frame.__init__(self, window, width=1000, height=400, **kwargs) self.master.title("{} Infos".format(itemId)) self.pack(fill=BOTH) #self._processor = file_reader self._processor = Logic(file_reader, itemId) self.labelId = Label(self, text="ID : {}".format(itemId)) self.labelId.pack() self.labelItemType = Label(self, text="Type : {}".format( self._processor.getItemType())) self.labelItemType.pack() self.labelItemOwner = Label(self, text="Owner : {}".format( self._processor.getItemOwner())) self.labelItemOwner.pack() self.labelItemName = Label(self, text="Name : {}".format( self._processor.getItemCommonName())) self.labelItemName.pack() prologResults = self._processor.getSpaceProperty() if (isinstance(prologResults, dict)): self.lb_problems = Listbox(self, background="darkred", fg="white", width=50, height=20) self.lb_problems.pack(side="left") self.lb_validateds = Listbox(self, background="Green", fg="white", width=50, height=20) self.lb_validateds.pack(side="left") for item in prologResults: if (prologResults[item]): self.lb_validateds.insert(END, item) else: self.lb_problems.insert(END, item)
def teste(): # Apeleaza testele existente pe un domain de test db = "testFile.txt" file = open(db, "w") file.write("") file.close() repo = Domain(db) logic = Logic(repo) testeAdaugare(logic) print("Teste adaugare trecute") testeStergere(logic) print("Teste stergere trecute") testeModificare(logic) print("Teste modificare trecute") testeMutare(logic) print("Teste mutare trecute") testeConcatenare(logic) print("Teste concatenare trecute") testeRaportMaxim(logic) print("Teste raport maxim trecute") testeRaportSuma(logic) print("Teste raport suma trecute") testeRaportSort(logic) print("Teste sortare trecute") testeUndo(logic) print("Teste undo trecute") input("Apasati ENTER pentru a continua")
def __init__(self,configfn,background,verbose): """Initalisation for the server""" print "Starting Backend Server..." self.conf = Configuration(configfn) # TODO: Implement log_filename!! log_filename = "/dev/null" self.log = Logger(verbose,self.conf.log_filename) self.log.message("Opening database with '%s'" % self.conf.db_engine) try: self.db = Database(self.conf.db_engine, self.conf.db_username, self.conf.db_password, self.conf.db_host, self.conf.db_database) except: self.log.message("Unable connect to database with username, \ password, host, and database name",4) self.log.message("Check your configuration file \ /etc/truemix/truemix.conf for the correct options",4) sys.exit(2) self.log.message("Connected to database successfully.") self.log.message("Initialising Logic Object") self.logic = Logic(self.db, self.log) self.log.message("Checking database.") self.logic.users_init_check() #Check to see if there are any users self.log.message("Configuring XMLRPC interface") #Set up the XMLRPC server self.xmlrpcserver = XMLRPCServer("", self.conf.port_number, self.logic)
def logic_process(self): if not self.pause: l1 = len(self.logic.snake.body) self.logic.move() l2 = len(self.logic.snake.body) if self.logic.game_finished: self.database_worker.save_result( len(self.logic.snake.body) - 3, self.player) if self.play_sounds: self.sound_player.play_lose(self.theme_worker.theme) self.show_best() self.logic = Logic() self.pause_game() elif l2 - l1 == 1 and self.play_sounds: self.sound_player.play_apple() self.update()
def __init__(self): self.listOfAllOther = None # @type dbI DataBaseInteraction # @type sv ServerInteraction # @type log Logic self.dbI = DataBaseInteraction(self) # self wieder einfuegen! self.sv = ServerInteraction(self) self.log = Logic(self, self.dbI)
def __init__(self): self.exit = False self.logic = Logic() self.logic.bind('<<events>>', self.events) self.options = [] self.user = [] self.me = Player() self.logic.addPlayer(self.me) self.oDescription = {'chooseCharacter': 'Choose a Character'} self.oMethods = {'chooseCharacter': self._chooseCharacter} self.cmdCommands = { 'exit': self._exit, 'start': self._start, 'addKI': self._addKI }
def __init__(self): super(MainWindow, self).__init__() uic.loadUi('MainWindowForm.ui', self) self.logic = Logic() self.showTree = ShowTree(self.logic) self.info.triggered.connect(print_variant) self.generate_random_button.clicked.connect(self.generate_random) self.save.clicked.connect(self.save_info) self.table.itemChanged.connect(self.change_item) self.show_tree.clicked.connect(self.show_window([self.showTree]))
def __init__(self, left_policy): Logic.__init__(self, left_policy) self.phases = [[], [9, 10], [16, 17, 18, 19], [15], [0, 1, 2, 3], [20, 21], [5, 6, 7, 8], [4], [11, 12, 13, 14]] self.table_protected = [[1, 5], [2, 6], [3, 7], [4, 8]] self.table_prot_perm = [[1, 5, 2, 6], [3, 7, 4, 8]] self.ns_dir, self.ew_dir = { 'left': [1, 5], 'through': [6, 2] }, { 'left': [3, 7], 'through': [4, 8] } self.left_table = [1, 5, 3, 7] self.through_table = [6, 2, 8, 4] self.direction_threshold = 10 self.permissive_threshold = 20 self.protect_threshold = 3 # if in protect mode, change to left/through threshold self.getID = { 0: 'S0', 1: 'S1', 2: 'S2', 3: 'S3', 4: 'S4', 5: 'W0', 7: 'W1', 8: 'W2', 9: 'W3', 10: 'W4', 11: 'N0', 12: 'N1', 13: 'N2', 14: 'N3', 15: 'N4', 16: 'E0', 18: 'E1', 19: 'E2', 20: 'E3', 21: 'E4' }
def run_engine(self): print("\nRunning engine\ninitializing Logic") logic = Logic(self.LOCAL_PATH, self.dbx, self.sql_pswd) # Load all the information about the kindergarten and it's kids from the database logic.loadKindergartenFromDatabase() logic.start()
def readLogic(logicElement, thresholdMap): if logicElement.tag == 'InternalTrigger': return Lvl1InternalTrigger(logicElement.get('name')) if logicElement.tag == 'TriggerCondition': thr = thresholdMap[logicElement.get('triggerthreshold')] return ThrCondition(thr, int(logicElement.get('multi'))) L = Logic() if logicElement.tag == 'AND': L.logic = Logic.AND elif logicElement.tag == 'OR': L.logic = Logic.OR elif logicElement.tag == 'NOT': L.logic = Logic.NOT else: raise RuntimeError("ERROR: don't understand tag %s" % logicElement.tag) for c in logicElement.getchildren(): L.subConditions += [readLogic(c, thresholdMap)] return L
def __init__(self, ni, nj): self.speed = 10 # frames per second when the game is running self.ni = ni self.nj = nj pg.init() self.WIN = pg.display.set_mode((Grid.SCREEN_WIDTH, Grid.SCREEN_HEIGHT), pg.RESIZABLE) pg.display.set_caption('Conway\'s Game of Life v02') for i in range(self.ni): tempLst = [] for j in range(self.nj): tempLst.append( Tile(xpos=i * Grid.TileWidth, ypos=j * Grid.TileHeight, state=0, i=i, j=j)) # getrandbits(1) Grid.tilesMatrix.append(tempLst) for i in range(100): Grid.tilesMatrix[randint(0, ni - 1)][randint(0, nj - 1)].setState(1) self.logic = Logic(Grid.tilesMatrix) self.SCREEN_CENTER = (Grid.SCREEN_WIDTH / 2, Grid.SCREEN_HEIGHT / 2) self.gameLoop()
class Main: def __init__(self): self.pixel_size = 20 self.camera = Webcam() self.size = self.camera.get_size() self.width = self.size[0] self.height = self.size[1] self.window = Window(self.width, self.height) self.logic = Logic(self.pixel_size, self.width, self.height, self.camera) self.run() def run(self): loop_no = 0 got_two = False grid_even = [] grid_odd = [] while True: if (loop_no % 2 == 0): self.logic.generate_grid() grid_even = self.logic.get_grid() #self.window.show_image(grid_even, self.pixel_size) self.window.show_raw_image(self.camera.get_image()) else: self.logic.generate_grid() grid_odd = self.logic.get_grid() #self.window.show_image(grid_odd, self.pixel_size) self.window.show_raw_image(self.camera.get_image()) if (loop_no > 2): position = self.logic.compare_grids(grid_even, grid_odd) if (not (position == None)): self.window.draw_location(grid_odd, position, self.pixel_size) loop_no = loop_no + 1 if (loop_no > 10000): loop_no = 0
class MaraudersMapBackEnd(object): """BackEndHauptklasse""" listOfAllOther = None def __init__(self): self.listOfAllOther = None # @type dbI DataBaseInteraction # @type sv ServerInteraction # @type log Logic self.dbI = DataBaseInteraction(self) # self wieder einfuegen! self.sv = ServerInteraction(self) self.log = Logic(self, self.dbI) # User Settings def update_settings(self, jID, settings): """ Updates the settings for user with given jID """ return self.log.update_settings(jID, settings) def get_settings(self, jID): """ Get a list of all settings for a user with given jID. """ return self.log.get_settings(jID) # User info def get_user_info(self, callerjID, aboutjID): """ Get a dictionary of the infos about a user with given jID, and connetions to the caller. """ return self.log.get_user_info(callerjID, aboutjID) def get_jid_of_all_users(self): """ Returns a list of all user @rtype: list with jid as JID """ return self.log.get_jid_of_all_users() # User Availability def set_user_available(self, jid): """ @type jid: str """ self.log.set_user_available(jid) def set_user_unavailable(self, jid): """ @type jid: str """ self.log.set_user_unavailable(jid) # User Avatar def save_avatar(self, ownerJID, avatarData): return self.dbI.update_user_avatar(ownerJID, avatarData) def get_avatar_for_username(self, ownerName): return self.log.get_avatar_for_username(ownerName) def get_jid_from_username(self, username): return self.log.get_jid_from_username(username) def get_all_for_buddysight(self, jID): """ Gets a list of all users who will receive the buddy sight of the user with given jID. @rtype: list """ try: listofall = self.log.get_all_for_buddysight(jID) return listofall except: return list() # Geolocation related def get_all_in_radius(self, jID): """ Gets a list of all users who are in a radius for the user with the given JID. Thus returns a list of the users who are allowed to see the user with the given JID """ try: listofallinradius = self.log.get_list_of_all_in_radius(jID) return listofallinradius except: return list() def refresh_geo_loc(self, jID, long, lat, acc): """ Updates the location for user with given jID """ try: self.dbI.refresh_geo_loc(jID, long, lat, acc) except: print "db Error/ refresh Geo" return True def share_geo_loc(self, senderJID, receiverUsername, geodata): """ Send a location send by user with senderJID to user with recevierUsername """ self.log.share_geo_loc(senderJID, receiverUsername, geodata) # Friendhsips related def create_friendship(self, callerJID, friendJID): """ Establish a friendship between callerJID and friendJID on database of backende """ return self.log.create_friendship(callerJID, friendJID) def destroy_friendship(self, callerJID, lostFriendJID): """ Destroy a friendhsip between callerJID and lostFriendJID """ return self.log.destroy_friendship(callerJID, lostFriendJID)
import keyboard import winsound import threading import time from Logic import Logic from tabulate import tabulate dir_path = 'D:/osu!/Replays/*' # 'E:/Games/osu!/Replays/*' osu_api_key = '46de654115045a6e159919ebbc3f66a40fee404a' profile_scores_count = 15 logic = Logic(dir_path, osu_api_key) profiles = logic.get_profiles_sorted_by_total_pp() def success_beep(): frequency = 800 duration = 250 winsound.Beep(frequency, duration) def failed_beep(): frequency = 200 duration = 250 winsound.Beep(frequency, duration) def submit_replay(): result = logic.submit_replay() if result: success_beep() score, latest_score, latest_score_acc, latest_pp, ranked_pp_obtained, total_pp_obtained, ranks_obtained = result
def main(): game = Logic() Gui(game)
SPEED = 0.075 BULLET_SPEED = 10 BULLET_DURATION = 60 BULLET_SIZE = 5 ANGULAR_VELOCITY = 4 VELOCITY_CAP = 5 SHOOT_DELAY = 10 SHIELD_SIZE = 20 map_dimensions = (3200, 1800) num_walls = 20 handlers = [] logic = Logic() class EventLog: def __init__(self): self.bullet_deaths = [] self.ship_deaths = [] self.bullet_timeouts = [] self.wall_reflects = [] self.ship_reflects = [] def ship_log(self, ship): self.ship_deaths.append((ship, logic.current_tick)) def bullet_log(self, bullet, wall): self.bullet_deaths.append((bullet,wall, logic.current_tick))
SPEED = 0.075 BULLET_SPEED = 10 BULLET_DURATION = 60 BULLET_SIZE = 5 ANGULAR_VELOCITY = 4 VELOCITY_CAP = 5 SHOOT_DELAY = 10 SHIELD_SIZE = 20 map_dimensions = (3200, 1800) num_walls = 20 handlers = [] logic = Logic() class EventLog: def __init__(self): self.bullet_deaths = [] self.ship_deaths = [] self.bullet_timeouts = [] self.wall_reflects = [] self.ship_reflects = [] def ship_log(self, ship): self.ship_deaths.append((ship, logic.current_tick)) def bullet_log(self, bullet, wall): self.bullet_deaths.append((bullet, wall, logic.current_tick))
last_logsave = time.time() return 'OK' @app.route('/img/<filename>') def return_picture(filename): ''' all the images in the ./img directory are visible! ''' # based on https://github.com/chokepoint/flaskgur/blob/master/flaskgur/flaskgur.py return send_from_directory('./img', filename) if __name__ == "__main__": # use queue to store messages until they can be dealt with # https://docs.python.org/3.6/library/queue.html eventsQueue = Queue(maxsize=100) analyze_messages_threads = [] for i in range(5): analyze_messages_threads.append(Thread(target=analyze_messages)) # this will stop the thread when ctrl-c is called # https://stackoverflow.com/questions/11815947/cannot-kill-python-script-with-ctrl-c analyze_messages_threads[i].daemon = True analyze_messages_threads[i].start() port = int(os.getenv("PORT", 6000)) logic = Logic(flask=app) atexit.register(logic.save_log) app.run(host="0.0.0.0", port=port) rospy.spin() eventsQueue.join()
def doselectmodule(self): while True: (readable, writable, exceptional) = select.select(self.readlist, [], []) for soc in readable: if soc == self.servsock: newsock, (remhost, remport) = soc.accept() self.readlist.append( newsock ) self.writelist.append( newsock ) self.sendToAll('playernum ' + str(len(self.writelist))) if len(self.writelist) == 3: time.sleep(4) name = 'A' playerlist=[] for gamesoc in self.writelist: try: if name=='A': gamesoc.send('gamestart '+ name+ ' B'+' C' ) elif name=='B': gamesoc.send('gamestart '+ name+ ' C'+' A' ) else: gamesoc.send('gamestart '+ name+ ' A'+' B' ) playerlist.append(Player(gamesoc, name)) name = chr(ord(name)+1) except Exception, e: print e soc.close self.readlist.remove(soc) self.writelist.remove(soc) gamelogic = Logic(playerlist) gamelogic.dealcard() time.sleep(3) for i in xrange(len(playerlist[0].handcards)): time.sleep(0.5) for player in playerlist: player.handcards.sort() player.sock.send('dealcard '+ player.handcards[i]) time.sleep(1) self.sendToAll('turn '+gamelogic.turn.name) else: try: recvdata = soc.recv(1024) print 'recvdata',recvdata player = gamelogic.getPlayer(soc) (presend, sendtoplayer) = Conver.run(gamelogic, player, recvdata) if sendtoplayer == 'all': self.sendToAll(presend) else: sendtoplayer.sock.send(presend) time.sleep(0.3) (presend, sendtoplayer) = Conver.checkround(gamelogic) if sendtoplayer == 'all': self.sendToAll(presend) time.sleep(0.3) if gamelogic.isgameover == True: self.sendToAll('win '+ player.name) self.toclose() else: self.sendToAll('turn '+gamelogic.turn.name) print 'turn ', gamelogic.turn.name except Exception, e: print e soc.close self.readlist.remove(soc) self.writelist.remove(soc)
def setUp(self): self.t1 = Logic()
class Graphic(QWidget): def __init__(self): super().__init__() # 게임을 불러옴 self.game = Logic() # 전체 설정 self.setWindowTitle("BalckJack") self.setGeometry(300, 300, 500, 500) mainLayout = QGridLayout() # 딜러, 플레이어 패 레이아웃 설정 dealerBar = QLabel() dealerBar.setText("Dealer Bar") self.dealerLayout = QHBoxLayout() self.dealerLayout.addStretch(1) playerBar = QLabel() playerBar.setText("Player Bar") self.playerLayout = QHBoxLayout() self.playerLayout.addStretch(1) # 메인레이아웃에 배치 mainLayout.addWidget(dealerBar, 0, 0, 1, 2) mainLayout.addLayout(self.dealerLayout, 1, 0, 1, 2) mainLayout.addWidget(playerBar, 2, 0, 1, 2) mainLayout.addLayout(self.playerLayout, 3, 0, 1, 2) # 상황판 배치 self.statusBox = QTextEdit() self.statusBox.setReadOnly(True) self.statusBox.setFixedSize(1500, 100) mainLayout.addWidget(self.statusBox, 4, 0, 1, 2) # 슬라이더 LCD 배치 self.poolSlider = QSlider(Qt.Horizontal) self.poolSlider.setRange(0, self.game.getMoney()) self.poolSlider.setSingleStep(1) poolLCD = QLCDNumber() self.poolSlider.valueChanged.connect(poolLCD.display) sliderLayout = QGridLayout() sliderLayout.addWidget(self.poolSlider, 1, 0) sliderLayout.addWidget(poolLCD, 0, 0) mainLayout.addLayout(sliderLayout, 5, 0) # 버튼 배치 buttonLayout = QGridLayout() self.raiseButton = Button('Raise', self.raiseEvent) self.dieButton = Button('Die', self.dieEvent) self.stayButton = Button('Stay', self.stayEvent) self.hitButton = Button('Hit', self.hitEvent) buttonLayout.addWidget(self.raiseButton, 0, 0) buttonLayout.addWidget(self.stayButton, 0, 1) buttonLayout.addWidget(self.dieButton, 1, 0) buttonLayout.addWidget(self.hitButton, 1, 1) mainLayout.addLayout(buttonLayout, 5, 1) # 전체 설정 self.setLayout(mainLayout) self.show() # 게임 시작 self.hitEvent() def raiseEvent(self): # raise버튼 눌리면 연결 # setPool호출 -> 건 돈 전달 self.game.setPool(self.poolSlider.value()) # draw호출 ret = self.game.drawCard() # 마지막 글자가 D면 21이 넘어가 게임이 끝난 상태 if ret[-1] == "D": # 버튼 종료 self.buttonSwith(False) self.playerLayout.addWidget(ImageLabel(domain(ret[:-1]))) self.statusBox.setText("21이 넘어갔습니다. \ \n플레이어 : {}\n딜러 : {}" \ .format(self.game.playerNum, self.game.dealerNum)) # 게임이 종료되었는지 확인 if self.game.remainMoney(): self.gameOver() else: # 그렇지 않으면 카드를 화면에 추가 self.playerLayout.addWidget(ImageLabel(domain(ret))) self.poolSlider.setRange(0, self.game.getMoney()) self.statusBox.setText(self.game.getPlayerStatus() \ + "\n플레이어 : {}\n딜러 : {}" \ .format(self.game.playerNum, self.game.dealerNum)) def dieEvent(self): # die버튼 눌리면 연결 # 버튼부터 끄기 self.buttonSwith(False) # 라운드 정지 판정 self.statusBox.setText("다이하셨습니다.") self.game.die() # 돈을 다 잃으면 정지 if self.game.remainMoney(): self.gameOver() def stayEvent(self): # stay버튼 눌리면 연결 # 판돈 보내기 self.game.setPool(self.poolSlider.value()) # endGame 메서드 호출 result, dealerCards = self.game.endGame() # 딜러의 카드 배치 for card in dealerCards[2:]: self.dealerLayout.addWidget(ImageLabel(domain(card))) # 결과에 따른 메시지 출력 if result == 2: self.statusBox.setText("블랙잭! 2배로 받습니다.") elif result == 1: self.statusBox.setText("이기셨습니다. 판돈만큼 받습니다.") elif result == 0: self.statusBox.setText("비기셨습니다. 돈은 그대로 유지됩니다.") else: self.statusBox.setText("지셨습니다. 판돈만큼 잃습니다.") self.statusBox.append(self.game.getPlayerStatus()) self.buttonSwith(False) # 돈을 다 잃으면 정지 if self.game.remainMoney(): self.gameOver() def hitEvent(self): # hit 버튼 눌리면 연결 # 카드 패 모두 지우기 for i in reversed(range(self.dealerLayout.count())): try: self.dealerLayout.itemAt(i).widget().deleteLater() except: pass for i in reversed(range(self.playerLayout.count())): try: self.playerLayout.itemAt(i).widget().deleteLater() except: pass # hit 메서드 호출 cards = self.game.hit() # 카드 추가 self.dealerLayout.addWidget(ImageLabel(domain(cards[0][0]))) self.dealerLayout.addWidget(ImageLabel(domain(cards[0][1]))) self.playerLayout.addWidget(ImageLabel(domain(cards[1][0]))) self.playerLayout.addWidget(ImageLabel(domain(cards[1][1]))) # 버튼 키기 self.buttonSwith(True) # 상태바 슬라이더 정리 self.statusBox.setText("게임을 시작합니다.") self.statusBox.append(self.game.getPlayerStatus()) self.poolSlider.setRange(0, self.game.getMoney()) def gameOver(self): # 남은 돈이 없으면 호출 # 버튼 다 끄기 self.buttonSwith(False) self.hitButton.setEnabled(False) self.statusBox.setText("남은 돈이 없습니다.") def buttonSwith(self, boolean): # 코드 반복 방지를 위한 버튼 키고끄는 메서드 self.raiseButton.setEnabled(boolean) self.dieButton.setEnabled(boolean) self.stayButton.setEnabled(boolean) self.hitButton.setEnabled(not boolean)
class testLogic(unittest.TestCase): def setUp(self): self.t1 = Logic() def testDrawCard(self): newCard = self.t1.drawCard() try: self.assertIn(newCard, listOfCard) except: self.assertEqual(newCard[-1], 'D') def testCardSum(self): self.assertEqual(self.t1.cardSum(['spadesA', 'heart10', 'club5', 'diamond8']), 24) def testDie(self): self.t1.pool = 50 self.t1.playerMoney = 100 self.t1.die() self.assertEqual(self.t1.pool, 0) self.assertEqual(self.t1.playerMoney, 50) def testSetPool(self): self.t1.setPool(10) self.assertEqual(self.t1.pool, 10) self.t1.setPool(20) self.assertEqual(self.t1.pool, 30) def testEndGame(self): self.t1.dealerCard = ['club7', 'heart10'] for i in [(16, -1), (17, 0), (18, 1)]: self.t1.playerNum = i[0] self.t1.endGame() self.assertEqual(self.t1.endGame()[0], i[1]) self.t1.playerNum = 21 self.t1.endGame() self.assertEqual(self.t1.endGame()[0], 2)
def expandOnBestTest(self,data=None): '''expands the node based on the best test''' target = data.getTarget() #get the target clause = target+":-" #initialize clause learned at this node with empty body curr = self #while loop to obtain clause learned at this node ancestorTests = [] while curr.parent!="root": if curr.pos == "left": clause += curr.parent.test+";" ancestorTests.append(curr.parent.test) elif curr.pos == "right": clause += ""#"!"+curr.parent.test+"," ancestorTests.append(curr.parent.test) curr = curr.parent if self.level == node.maxDepth or round(self.information,2) == 0: if clause[-1]!='-': node.learnedDecisionTree.append(clause[:-1]+" "+str(Utils.getleafValue(self.examples))) else: node.learnedDecisionTree.append(clause+" "+str(Utils.getleafValue(self.examples))) return if clause[-2] == '-': clause = clause[:-1] print('-'*80) print("pos: ",self.pos) print("node depth: ",self.level) print("parent: ",self.parent) print("number of examples at node: ",len(self.examples)) if self.parent != "root": print("test at parent: ",self.parent.test) print("clause for generate test at current node: ",clause) #print "examples at current node: ",self.examples minScore = float('inf') #initialize minimum weighted variance to be 0 bestTest = "" #initalize best test to empty string bestTExamples = [] #list for best test examples that satisfy clause bestFExamples = [] #list for best test examples that don't satisfy clause literals = data.getLiterals() #get all the literals that the data (facts) contains tests = [] for literal in literals: #for every literal generate test conditions literalName = literal literalTypeSpecification = literals[literal] tests += Logic.generateTests(literalName,literalTypeSpecification,clause) #generate all possible literal, variable and constant combinations if self.parent!="root": tests = [test for test in tests if not test in ancestorTests] tests = sorted(list(set(tests))) if not tests: if clause[-1]!='-': node.learnedDecisionTree.append(clause[:-1]+" "+str(Utils.getleafValue(self.examples))) else: node.learnedDecisionTree.append(clause+" "+str(Utils.getleafValue(self.examples))) return for test in tests: #see which test scores the best tExamples = self.getTrueExamples(clause,test,data) #get examples satisfied fExamples = [example for example in self.examples if example not in tExamples] #get examples unsatsified (closed world assumption made) score = ((len(tExamples)/float(len(self.examples)))*Utils.variance(tExamples) + (len(fExamples)/float(len(self.examples)))*Utils.variance(fExamples)) #calculate weighted variance #score = len([example for example in tExamples if example in data.pos.keys()]) - len([example for example in tExamples if example in data.neg.keys()]) if score < minScore: #if score lower than current lowest minScore = score #assign new minimum bestTest = test #assign new best test bestTExamples = tExamples #collect satisfied examples bestFExamples = fExamples #collect unsatisfied examples Utils.addVariableTypes(bestTest) #add variable types of new variables self.test = bestTest #assign best test after going through all literal specs print("best test found at current node: ",self.test) #if self.parent != "root": #node.learnedDotFile.append(self.parent.test+str("->")+self.test) if len(bestTExamples) > 0: #if examples still need explaining create left node and add to queue self.left = node(None,bestTExamples,Utils.variance(bestTExamples),self.level+1,self,"left") if self.level+1 > node.depth: node.depth = self.level+1 if len(bestFExamples) > 0: #if examples still need explaining, create right node and add to queue self.right = node(None,bestFExamples,Utils.variance(bestFExamples),self.level+1,self,"right") if self.level+1 > node.depth: node.depth = self.level+1 if self.test == "" or round(self.information,2) == 0: #if no examples append clause as is if clause[-1]!='-': node.learnedDecisionTree.append(clause[:-1]) else: node.learnedDecisionTree.append(clause) return
SPEED = 0.075 BULLET_SPEED = 10 BULLET_DURATION = 60 BULLET_SIZE = 5 ANGULAR_VELOCITY = 4 VELOCITY_CAP = 5 SHOOT_DELAY = 10 SHIELD_SIZE = 20 NUM_BOTS = 10 NUM_WALLS = 20 map_dimensions = (3200, 1800) camera_bounds = (854, 480) logic = Logic() view = View(camera_bounds, logic, map_dimensions) min_respawn = (320, 240) max_respawn = (3000, 1600) respawn = random_respawn(min_respawn, max_respawn) player_ship = Ship((320, 240), (15, 15), SHOOT_DELAY, SPEED, VELOCITY_CAP, ANGULAR_VELOCITY, respawn) logic.add_ship(player_ship) controller = ServerSideController(player_ship, logic, BULLET_SIZE, BULLET_SPEED, BULLET_DURATION, SHOOT_DELAY, SHIELD_SIZE) def run_bot_func(bot): def on_run(): if not bot.isDead():
def setUp(self): # 测试方法前执行 self.logic = Logic('init.jpg') print('TestLogic.setUp')
SPEED = 0.075 BULLET_SPEED = 10 BULLET_DURATION = 60 BULLET_SIZE = 5 ANGULAR_VELOCITY = 4 VELOCITY_CAP = 5 SHOOT_DELAY = 10 SHIELD_SIZE = 20 NUM_BOTS = 10 NUM_WALLS = 20 map_dimensions = (3200, 1800) camera_bounds = (854, 480) logic = Logic() view = View(camera_bounds, logic, map_dimensions) min_respawn = (320, 240) max_respawn = (3000, 1600) respawn = random_respawn(min_respawn, max_respawn) player_ship = Ship((320, 240), (15, 15), SHOOT_DELAY, SPEED, VELOCITY_CAP, ANGULAR_VELOCITY, respawn) logic.add_ship(player_ship) controller = ServerSideController(player_ship, logic, BULLET_SIZE, BULLET_SPEED, BULLET_DURATION, SHOOT_DELAY, SHIELD_SIZE)
from abc import ABC, abstractmethod from Logic import Logic from Player import Player class User(ABC): def __init__(self, logic: Logic): self.player = Player() self.setLogic(logic) def setLogic(self, logic: Logic): self.logic = logic self.logic.bind('<<events>>', self.playerEvents) @abstractmethod def playerEvents(self, *args, **kv): pass if __name__ == '__main__': user = User() user.setLogic(Logic()) user.logic.addPlayer(user.player) user.logic.startGame() user.logic.endTurn(user.player)
class GUI: def __init__(self): self.exit = False self.logic = Logic() self.logic.bind('<<events>>', self.events) self.options = [] self.user = [] self.me = Player() self.logic.addPlayer(self.me) self.oDescription = {'chooseCharacter': 'Choose a Character'} self.oMethods = {'chooseCharacter': self._chooseCharacter} self.cmdCommands = { 'exit': self._exit, 'start': self._start, 'addKI': self._addKI } def events(self, *args, **kv): event = kv['event'] if event == 'GameStart': self._eventGameStart() elif event == 'NextPlayer': pass else: raise Exception('unhandled event:' + event) def cmd(self, line): args = line.split() arg = args[0] m = self.cmdCommands.get(arg) if m == None: d = {str(i): v for i, v in enumerate(self.logic.getOptions())} opt = d.get(line) if opt == None: print('unknown command') else: self.oMethods[opt](args) else: m(args) def _addKI(self, *args): self.user.append(KI(self.logic)) def _exit(self, *args): self.exit = True def _start(self, *args): self.logic.startGame() def loop(self): for x in self.cmdCommands.keys(): print(x) while not self.exit: self.printOptions() line = input('>> ') #print(line) self.cmd(line) def printOptions(self): ##print(self.logic.getOptions()) options = self.logic.getOptions() if len(options) > 0: print('Choose option:') for i, x in enumerate(options): print('[' + str(i) + ']: ' + self.oDescription[x]) def printOptions_(self): if len(self.options) == 0: return map: Mapping = self.options[len(self.options) - 1] for k, v in map.items(): print('[' + k + ']: ' + v) def _chooseCharacter(self, *args): char = self.chooseCharacter(self.logic.getAvailableCharacters()) if char == None: print('no such character') else: self.logic.chooseCharacterCard(self.me, char) def chooseCharacter(self, chars: List[CharacterCard]): print('Choose a Character:') dic = {str(i): c for i, c in enumerate(chars)} return dic.get(input('>> ')) def _eventGameStart(self): self.cmdCommands.pop('addKI') self.cmdCommands.pop('start')
print("signature valid!") # parse webhook body try: events = parser.parse(body, signature) print("") eventsQueue.put(events) except InvalidSignatureError: print("invalid signature") abort(400) print("returning 'OK'...") return 'OK' if __name__ == "__main__": # use queue to store messages until they can be dealt with # https://docs.python.org/3.6/library/queue.html eventsQueue = Queue(maxsize=100) analyze_messages_threads = [] for i in range(5): analyze_messages_threads.append(Thread(target=analyze_messages)) # this will stop the thread when ctrl-c is called # https://stackoverflow.com/questions/11815947/cannot-kill-python-script-with-ctrl-c analyze_messages_threads[i].daemon = True analyze_messages_threads[i].start() port = int(os.getenv("PORT", 5000)) logic = Logic() atexit.register(logic.save_log) app.run(host="0.0.0.0", port=port) eventsQueue.join()
#主界面登录模块 message = "" k = {} f = open( 'name.txt', 'r', encoding="utf-8-sig " ) #解决方法博客:https://blog.csdn.net/qq_38882327/article/details/89637884 for c in f.readlines(): a = c.split(" ") n = a[0] p = a[1].strip() k[n] = p f.close() #创建QApplication类的实例 app = QApplication(sys.argv) logic = Logic() main_call = Main_call() person_list = Person_list() people_talk = People_talk() senddata = people_talk.D_input all_chat = people_talk.D_textedit all_chat.setReadOnly(True) # 只读 all_chat.setText("") #------修改处 # 修改部分,为每一个聊天对象建立一个对象,只需在下面各自的点击函数修改对象名即可 person_talk_red = Person_talk() senddata_red = person_talk_red.D_input person_chat_red = person_talk_red.D_input_text person_chat_red.setReadOnly(True)