def __init__(self, id, vieja=None): Observable.__init__(self, id) self.vieja = None if vieja is not None: self.vieja = vieja else: self.vieja = Vieja()
def __init__(self, neighborhood, x, y): Observable.__init__(self) self.population = random.randrange(0, 10, 1) self.monsterMash = [] self.humansSaved = 0 self.add_observer(neighborhood) for i in range(0, self.population): pickMonster = random.randint(0, 3) monsterMash = self.monsterMash if (pickMonster == 0): monster = ghoul(self) monsterMash.append(monster) elif (pickMonster == 1): monster = vampire(self) monsterMash.append(monster) elif (pickMonster == 2): monster = zombie(self) monsterMash.append(monster) else: monster = werewolf(self) monsterMash.append(monster) self.myX = x self.myY = y if (self.population == 0): self.updateNeighborhood(self)
def __init__(self, exchange, symbol, contract_type, dry_run=True): Observable.__init__(self) self.id = None self.dry_run = dry_run self.exchange = exchange self.symbol = symbol.replace('_', '/').upper() self.contract_type = contract_type self.id = Contract.id Contract.id += 1 self.status = Contract.Status.NONE self.order_type = None self.price = None self.cost = None self.margin = 0 self.margin_rate = 0 self.fee = 0 self.guarantee = 20 self.amount = 0 self.filled = 0 self.remaining = 0 self.lever_rate = 10 self.timestamp = None
def update(self, *args, **kwargs): """ Updating that there was change :rtype: void """ Observable.update_observers(self)
def __init__(self, conffile): Observable.__init__(self) cp = ConfigParser() cp.read(conffile) if not Globals.globSimulate: wiringpi.wiringPiSetupGpio() self.md = MotorDriver([ cp.getint("MotorDriver", "LEFT_L"), cp.getint("MotorDriver", "LEFT_R"), cp.getint("MotorDriver", "RIGHT_L"), cp.getint("MotorDriver", "RIGHT_R"), cp.getint("MotorDriver", "VERTICAL_L"), cp.getint("MotorDriver", "VERTICAL_R"), ]) self.md.start() self.ds = DistanceSensor( cp.getint("DistanceSensor", "TRIGGER"), cp.getint("DistanceSensor", "ECHO") ) self.ds.start() self.acl = AltitudeControlLoop(self.md, self.ds) self.update("MotorDriver", self.md) self.update("DistanceSensor", self.ds) self.update("AltitudeControlLoop", self.acl) self.md.subscribe(self.update) self.ds.subscribe(self.update) self.acl.subscribe(self.update) self.setCamera(False)
def raise_event(self, page): ''' (Observable, tk.Frame) -> None Notifys all Observers ''' self.page = page; Observable.raise_event(self)
class UnitTestObserver(unittest.TestCase): '''Testing class''' def setUp(self): self.undOb = Observable() self.bot1 = TestObserver() self.bot2 = TestObserver() def tearDown(self): del self.undOb del self.bot1 del self.bot2 def test_defaultNoObserver(self): self.assertEqual(len(self.undOb.observers),0," Observer list is not empty") def test_DuplicateObservers(self): self.undOb.register(self.bot1) self.undOb.register(self.bot2) self.undOb.register(self.bot1) self.assertEqual(len(self.undOb.observers),2,"Duplicate observers registered") def test_RemoveAllSubscribers(self): self.undOb.register(self.bot1) self.undOb.register(self.bot2) self.undOb.register(self.bot1) self.undOb.unregister_all() self.assertEqual(len(self.undOb.observers), 0, "Observers still registered")
def __init__(self, qubits, observable=Observable.Z()): """ - qubit (int): The index of the qubit - observable=Observable.Z() (matrix, tuple, or QNN-Gen Observable object): The observable to meausre with respect to - If matrix it should be a list or numpy.ndarray - If tuple, it should be of the form ("name": matrix) """ if isinstance(qubits, int): self.qubits = [qubits] else: self.qubits = qubits # just single-qubit for now if isinstance(observable, (list, np.ndarray)): self.observable = Observable(observable) elif isinstance(observable, tuple): self.observable = Observable(matrix=observable[1], name=observable[0]) elif isinstance(observable, Observable): self.observable = observable else: raise ValueError( "Observable argument is not a correct type. Check the __init__ docstring." ) if self.observable.name == "Z": requires_rotation = False else: requires_rotation = True super().__init__(qubits=self.qubits, rotate=requires_rotation)
def _init_(self, house): name = "Default" attack = 0 #compiler said to initialize these health = 0 Observable.__init__(self) self.add_observer(house)
def __init__(self, button=None): ''' (Observable, Button) -> None Initialize a ButtonObservable object ''' Observable.__init__(self) self.button = button self.template = ''
def __init__(self, id, x, y, w, h, text): super() self.Text = text self.Location = Point(x, y) self.Height = w self.Width = h self.observable = Observable(id) self.Click += self.buttonPressed
def search(): observable = Observable() query = request.get_json() py_client(host="localhost", port_expose=server_port, top_k=100).search(input_fn=read_query_data(query["searchQuery"]), output_fn=lambda x: observable.callback(x)) results = observable.format_response() return jsonify(results)
def __init__(self, pt, pe): threading.Thread.__init__(self) Observable.__init__(self) self.pinTrigger = pt self.pinEcho = pe if not Globals.globSimulate: wiringpi.pinMode(self.pinTrigger, GPIO_OUTPUT) wiringpi.pinMode(self.pinEcho, GPIO_INPUT)
def search(): observable = Observable() query = request.get_json() query = query["data"] answer = requests.post(f"http://0.0.0.0:{server_port}/api/search", json={"data": query, "top_k": 10}).text answer = json.loads(answer) observable.result = answer results = observable.format_response() return jsonify(results)
def __init__(self, playerName, address, port): Thread.__init__(self, name="PlayerClient-"+str(playerName)) Observable.__init__(self) self.address = address self.port = port #initialize the socket that this player will use self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.playerName = playerName #data received from the server self.data = None #connect to the server self.connect()
def checkVictory(self):#If all the non clicked buttons are mines, the user wins the game and all the mines become checked. countRightPointsClicked = 0 for i in range(self._model.getLenModelsGridButtons()): if not(self._model.getItemModelsGridButtons(i).isMine) and self._model.getItemModelsGridButtons(i).isClicked: countRightPointsClicked += 1 if countRightPointsClicked == self._model.W * self._model.H - self._model.mines: self._model.isWin = True if self._ui.lcdTime.value() == 0: totalTime = 0 else: if self._ui.lcdTime.value() == 99999: totalTime = 99999 else: totalTime = self._ui.lcdTime.value() + (time.time() - self._model.gameTime) for i in range(self._model.getLenModelsGridButtons()): self._model.getItemModelsGridButtons(i).isActive = False if self._model.getItemModelsGridButtons(i).isMine: self._model.getItemModelsGridButtons(i).isChecked = True self._model.getItemModelsGridButtons(i).isClicked = True self._ui.statusbar.setStyleSheet("color:green; font-size: 14pt;") self._ui.statusbar.showMessage("You Win!") self._model.counterMines = 0 #The maximum number of rankings positions are 20. So if the considered ranking is not already full, the user can insert his record; else if his game time is less than the last position one, the user does a new record; else the user does not have the possibility to insert his game time on the ranking. if self._model.rankingType != 3: if self._model.getLenRanking(self._model.rankingType) < 20 or totalTime < self._model.getMaxRanking(self._model.rankingType): isRecord = Observable(False) nameRecord = Observable(None) # A dialog gives the possibility to a user who does a new record to insert his name. dialog = RecordDialog(totalTime, isRecord, nameRecord) dialog.exec_() #If there is a new record in the ranking, the rankings-related file is updated. if isRecord.value: self._model.setItemRanking(self._model.rankingType, [nameRecord.value, totalTime]) if os.path.exists("DataSaved/Rankings/Rankings.pkl"): os.remove("DataSaved/Rankings/Rankings.pkl") vectorToSave = [[], [], []] for i in range(3): for j in range(self._model.getLenRanking(i)): vectorToSave[i].append(self._model.getItemRanking(i, j)) with open("DataSaved/Rankings/Rankings.pkl", "wb") as output: pickle.dump(vectorToSave, output) self.makeRankings(self._model.rankingType) return True else: return False
def __init__(self, host, port, myRam, nodeName, instructionFile): Observable.__init__(self) self.myRam = myRam self.nodeName = nodeName self.diskAccessCount = 0 self.localCacheHitCount = 0 self.neighbourCacheHitCount = 0 self.diskAccessCount = 0 self.localCacheHitCount = 0 self.instructionSheet = [] if instructionFile: self.instructionSheet = InstructionParser.getInstructionFromFile(instructionFile)
def __init__(self, exchange, symbol, period, contract_type): Observable.__init__(self) self.exchange = exchange self.symbol = symbol self.period = period self.contract_type = contract_type self.name = 'K[%s/%s/%s/%s]' % (self.exchange.name, self.symbol, self.period, self.contract_type) self.last_period = None self.speed = _K.SLOW self.k = None self.started = False logger.info('New K instance %s' % self.name)
class AuthModel(object): def __init__(self): self.message = Observable(None) self.users = [] self.users.append(User("admin", "1234", True)) self.users.append(User("reader", "qwerty", False)) self.users.append(User("q", "q", True)) gettext.install("IMsg", "./locale", unicode=True) def login(self, login, password): if self.validation(login, password): return self.authentication(login, password) else: return None def authentication(self, login, password): user_found = False password_found = False result = None for user in self.users: if user.login == login: user_found = True if user.password == password: password_found = True result = user if password_found == False: if user_found == True: self.message.set(_("Wrong Password")) self.state = "Error" else: self.message.set(_("User not found")) return result def validation(self, login, password): pv = self.validate(password) lv = self.validate(login) if not (pv or lv == True): self.message.set(_("Login and password are empty")) else: if pv == False: self.message.set(_("Password is empty")) else: if lv == False: self.message.set(_("Login is empty")) return pv and lv def validate(self, elem): if not (elem == ""): return True else: return False
def __init__(self, ip='0.0.0.0', port=0, username='', password='', autoReconnect=True): self.loginId = C_LLONG() self.client = NetClient() self.client.InitEx(fDisConnect(self.disconnectCallback)) autoReconnect and self.client.SetAutoReconnect( fHaveReConnect(self.reconnectCallback)) self.clientInfo = None self.ip = ip self.port = port self.username = username self.password = password ## 通道(channel) self.channel = 0 ## 码流类型(0:主码流; 1:辅码流) self.streamtype = 0 self.onConnect = Observable() self.onDisconnect = Observable() self.onReconnect = Observable() self.onError = Observable()
def __init__(self, pins): threading.Thread.__init__(self) Observable.__init__(self) if len(pins) != 6: raise "MotorDriver needs 6 pins" self.motorPins = pins if not Globals.globSimulate: for pn in range(0, 6): pin = self.motorPins[pn] wiringpi.pinMode(pin, GPIO_OUTPUT) wiringpi.pinMode(18, GPIO_PWM) wiringpi.pwmWrite(18, self.pwmValue)
def __init__(self, game, rows, columns): self.hauntedHouses = rows * columns; #houses = [[house() for x in range(columns)] for y in range(rows)]; #This nested for loop will fill the board with new houses in a grid. Observable.__init__(self); r = rows c = columns self.add_observer(game); for x in range(0, c): self.houses.append([]); for y in range(0, r): newHome = house(self, x, y); newHome.add_observer(self); self.houses[x].append(newHome); self.hauntedHouses = self.hauntedHouses + 1;
def do_steps(self, delay): if self.delay > delay: self.delay = math.exp(-self.count) + 0.0005 self.count = self.count + 0.01 GPIO.setmode(GPIO.BCM) GPIO.setup(DIR, GPIO.OUT) GPIO.setup(STEP, GPIO.OUT) GPIO.output(STEP, GPIO.HIGH) sleep(self.delay) GPIO.output(STEP, GPIO.LOW) sleep(self.delay) self.steps_taken += 1 self.update_position() Observable.dispatch(self, str(self.get_x()) + ";" + str(self.get_y()))
def callingDeleteOperation(self): if self._model.getLenSavedGames() == 0: if self._ui.scrollAreaWidgetContents.layout().count() == 3: #"scrollAreaWidgetContents" is the dialog main area. self._ui.scrollAreaWidgetContents.layout().addWidget(QLabel("Select at least one game to delete.")) self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setStyleSheet("color:red; font-size:11pt;") else: countGameChecked = 0 for i in reversed(range(self._ui.savedGamesArea.layout().count())): if self._ui.savedGamesArea.layout().itemAt(i).widget().isChecked(): if self._ui.scrollAreaWidgetContents.layout().count() == 4: self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setParent(None) countGameChecked += 1 if countGameChecked == 1: isDelete = Observable(False) # A dialog asks to the user if he wants the imminent elimination of some selected games. dialog = WarningDeleteDialog(isDelete) dialog.exec_() if not(isDelete.value): break self.deleteGame(self._model.getItemSavedGames(i)) self._model.delItemSavedGames(i) self._ui.savedGamesArea.layout().itemAt(i).widget().setParent(None) if self._ui.scrollAreaWidgetContents.layout().count() == 3 and countGameChecked == 0: self._ui.scrollAreaWidgetContents.layout().addWidget(QLabel("Select at least one game to delete.")) self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setStyleSheet("color:red; font-size:11pt;") if self._model.getLenSavedGames() == 0: self._ui.savedGamesArea.layout().addWidget(QLabel("No Games Saved.")) self._ui.savedGamesArea.layout().itemAt(0).widget().setStyleSheet("font-size:11pt;")
def callingSaveOperation(self): if len(self._ui.nameGame.text()) == 0: if self._ui.scrollAreaWidgetContents.layout().count() == 3: #"scrollAreaWidgetContents" is the dialog main area. self._ui.scrollAreaWidgetContents.layout().addWidget(QLabel("Insert a game name.")) self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setStyleSheet("color:red; font-size:11pt;") else: self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setText("Insert a game name.") else: if not(self._ui.nameGame.text().isalnum()): if self._ui.scrollAreaWidgetContents.layout().count() == 3: self._ui.scrollAreaWidgetContents.layout().addWidget(QLabel("Insert a name without character special or spaces.")) self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setStyleSheet("color:red; font-size:11pt;") else: self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setText("Insert a name without character special or spaces.") else: if self._ui.scrollAreaWidgetContents.layout().count() == 4: self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setParent(None) count = 0 for i in range(self._model.getLenSavedGames()): if self._ui.nameGame.text() == self._model.getItemSavedGames(i): isReplacing = Observable(False) #If the user inserts a same name of another saved game, a dialog appears: he can replace this saved game or change the typed name. dialog = WarningSaveDialog(isReplacing) dialog.exec_() if isReplacing.value: self._model.gameObservable.value = self._ui.nameGame.text() self.close() break else: count += 1 if count == self._model.getLenSavedGames(): self._model.gameObservable.value = self._ui.nameGame.text() self.close()
def __init__(self): self.message = Observable(None) self.users = [] self.users.append(User("admin", "1234", True)) self.users.append(User("reader", "qwerty", False)) self.users.append(User("q", "q", True)) gettext.install("IMsg", "./locale", unicode=True)
def do_steps_slow(self): if self.delay > 0.001: self.delay = math.exp(-self.count) + 0.0005 self.count = self.count + 0.0075 GPIO.setmode(GPIO.BCM) GPIO.setup(DIR, GPIO.OUT) GPIO.setup(STEP, GPIO.OUT) GPIO.output(STEP, GPIO.HIGH) sleep(self.delay) GPIO.output(STEP, GPIO.LOW) sleep(self.delay) self.steps_taken += 1 self.update_position() print("[ StepperH ] Steps taken: " + str(self.steps_taken)) Observable.dispatch(self, str(self.get_x()) + ";" + str(self.get_y()))
def __init__(self): super().__init__() self.ui = Ui_PhotoGlue() self.ui.setupUi(self) self.ui.refreshButton.clicked.connect(self.insertPhotoConf) self.countPhotos = Observable(0) self.countPhotos.observe(self.updateStatusBar) self.ui.imageChoice.clicked.connect(self.setBackgroundChoice) self.ui.imageChoice.clicked.connect(self.updateStatusBar) self.ui.customChoice.clicked.connect(self.setBackgroundChoice) self.ui.customChoice.clicked.connect(self.updateStatusBar) self.ui.makeCollageButton.clicked.connect(self.makeCollageControl)
class Boton(Button): def __init__(self, id, x, y, w, h, text): super() self.Text = text self.Location = Point(x, y) self.Height = w self.Width = h self.observable = Observable(id) self.Click += self.buttonPressed def getId(self): return self.observable.getId() def agregar(self, objeto): self.observable.agregar(objeto) def buttonPressed(self, sender, args): self.Text = 'X' self.observable.actualizar(1)
def __init__(self, result_queue): print("[ StepperH ] initialising") self.result_queue = result_queue GPIO.setmode(GPIO.BCM) GPIO.setup(DIR, GPIO.OUT) GPIO.setup(STEP, GPIO.OUT) GPIO.output(DIR, CCW) Observable.__init__(self) self.amount_of_steps = 0 self.steps_taken = 1 self.delay = 0.06 self.count = 5 self.running = True # to stop stepper from main thread in the end self.sm = StateMachine.get_stepperh_machine(self, StepperH._states) print("[ StepperH ] Set delay between steps to " + str(self.delay) + "s") print("[ StepperH ] initialized")
def __init__(self, serialNumber, baudRate, device): Observable.__init__(self) # Attributes: self.setSerialNumber(serialNumber) # (string) self.__device = device self.__bytesize = serial.EIGHTBITS self.__parity = serial.PARITY_NONE self.__stopbits = serial.STOPBITS_ONE self.__xonxoff = 0 self.__connection = None self.__messageSize = None #we set the baud rate depending on the type of microcontroller self.__baudrate = baudRate #we open the connection try: self.__connection = serial.Serial(port=self.__device, baudrate=self.__baudrate, bytesize=self.__bytesize, parity=self.__parity, stopbits=self.__stopbits, xonxoff=self.__xonxoff) except serial.SerialException: print "Unable to connect to the device!"
def __init__(self, sock, server): '''Initialize a new PlayerHandler to communicate with the client's game engine''' #create a new Thread to handle this Player's Communication Thread.__init__(self, name="PlayerHandler"+str(PlayerHandler.PID)) #initialize the parent Observable.__init__(self) #assign our unique ID self.pid = PlayerHandler.PID #increment the PID for the next player PlayerHandler.PID+=1 #my name self.playerName = 'BOB' #server instance self.server = server #the socket connection for this Player self.sock = sock #data to be sent down the socket self.data = None #ack the connection self.ack()
def __init__(self, game): Observable.__init__(self) self.add_observer(game) self.health = random.randrange(0, 25) + 100 self.attack = random.randrange(0, 10) + 10 startingWeapon = HersheyKisses() self.inventory.append(startingWeapon) for i in range(0, 9): startingGear = random.randint(0, 2) if (startingGear == 0): candy = chocolateBars() self.inventory.append(candy) elif (startingGear == 1): candy = nerdBombs() self.inventory.append(candy) else: candy = sourStraw() self.inventory.append(candy)
def __init__(self, listenAddress="127.0.0.1", listenPort=8080): AbstractModule.__init__(self) threading.Thread.__init__(self) Observable.__init__(self) # Attributes: self.__oscInterpreters = [] # (OscInterpreter) self.setListenAddress(listenAddress) # (string) self.setListenPort(listenPort) # (int) self.__inSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.__inSocket.settimeout(10) self.__active = False #runnables for the CLI self.runnables.append("getActive()") self.runnables.append("setActive(bool active)") self.runnables.append("getListenPort()") self.runnables.append("setListenPort(int listenPort)") self.runnables.append("getListenAddress()") self.runnables.append("setListenAddress(string listenAddress)") self.runnables.append("addOscInterpreter(OscInterpreter obj)") self.runnables.append("removeOscInterpreter(OscInterpreter obj)")
def __init__(self, oscAddressPatternPrefix, hostAddress="127.0.0.1", hostPort=8000): AbstractModule.__init__(self) Observable.__init__(self) # Attributes: self.setOscAddressPatternPrefix(oscAddressPatternPrefix) # (string) if self.__oscAddressPatternPrefix.endswith("/"): self.setOscAddressPatternPrefix(self.__oscAddressPatternPrefix[:-1]) self.setHostAddress(hostAddress) # (string) self.setHostPort(hostPort) # (int) self.__msgBuffer = [] # (OscMsg[]) self.__outSocket = None#socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.__active = False #runnables for the CLI self.runnables.append("getActive()") self.runnables.append("setActive(bool active)") self.runnables.append("getHostAddress()") self.runnables.append("setHostAddress(string hostAddress)") self.runnables.append("getHostPort()") self.runnables.append("setHostPort(int hostPort)") self.runnables.append("getOscAddressPatternPrefix()") self.runnables.append("setOscAddressPatternPrefix(string oscAddressPatternPrefix)")
def openLoadDialog(self):#The user can load a saved game with this dialog. blockedValue = self._model.isBlocked self._model.isBlocked = True gameToLoad = Observable(None) self.setEnabled(False) self.setHidden(True) dialog = LoadDialog(gameToLoad) dialog.exec_() self.setEnabled(True) self.setHidden(False) if gameToLoad.value is not None: self.loadGame("DataSaved/SavedGames/" + gameToLoad.value + ".pkl") self._model.isBlocked = blockedValue
def __init__(self, num): """ Initilizes the model to represent a start board - A board of the given size with only one randomly placed block of value 2 Will throw TypeError if num is not an integer greater than or equal to 2 """ if num < 2: raise TypeError('Arugment number must be larger than 2') self.size = int(num) self.unoccupied_squares = [] l = [] # build the grid of empty squares, and add all to the list of unoccupied squares for i in range(num): m = [] for j in range(num): coordinate = i, j self.unoccupied_squares.append(coordinate) m.append(EMPTY_SQUARE_VALUE) l.append(m) # the grid is observable, so the controller can listen for changes self.grid = l self.last_move = Observable(None)
def __init__(self, **kwargs): super().__init__(**kwargs) self.playId = C_LLONG() self.m_RealDataCallBack = fRealDataCallBackEx2(self.realDataCallback) self.onRealData = Observable() self.onRealPlay = Observable() self.onRealStop = Observable()
def setBackgroundChoice(self): for i in reversed(range(self.ui.chosenBackgroundLayout.count())): self.ui.chosenBackgroundLayout.itemAt(i).widget().setParent(None) if self.ui.imageChoice.isChecked(): self.ui.chosenBackgroundLayout.addWidget(BackgroundImageConf()) self.ui.chosenBackgroundLayout.itemAt( 0).widget().ui.backgroundImagePath.textChanged.connect( self.backgroundControlForStatusBar) if self.ui.customChoice.isChecked(): self.countColors = Observable(0) self.countColors.observe(self.colorBackgroundControlForStatusBar) self.ui.chosenBackgroundLayout.addWidget( BackgroundCustomConf(self.countColors)) self.ui.chosenBackgroundLayout.itemAt( 0).widget().ui.colorChoice.clicked.connect( self.updateStatusBar) self.ui.chosenBackgroundLayout.itemAt( 0).widget().ui.gradientChoice.clicked.connect( self.updateStatusBar)
class Model: def __init__(self): self.myMoney = Observable(0) def addMoney(self, value): self.myMoney.set(self.myMoney.get() + value) def removeMoney(self, value): self.myMoney.set(self.myMoney.get() - value)
def openSaveAsDialog(self):#The user can save a game with this dialog. blockedValue = self._model.isBlocked self._model.isBlocked = True gameToSave = Observable(None) self.setEnabled(False) self.setHidden(True) dialog = SaveAsDialog(gameToSave) dialog.exec_() if gameToSave.value is not None: self.saveGameAs("DataSaved/SavedGames/" + gameToSave.value + ".pkl", blockedValue) dialog = SuccessSaveDialog() dialog.exec_() self._model.isBlocked = blockedValue self.setEnabled(True) self.setHidden(False)
def __init__(self, parent, filepath): Thread.__init__(self) self.setDaemon(True) amaroKObject.__init__(self, parent) Observable.__init__(self)
def __init__(self, parent): amaroKObject.__init__(self, parent) Observable.__init__(self)
def __init__(self, path): Observable.__init__(self) self.player = amaroKPlayer(self) self.monitor = amaroKMonitor(self, sys.stdin) self.contextBrowser = amaroKContextBrowser(self, path)
def __init__(self): Observable.__init__(self) self.__oscInterpreter = None self.__oscOut = [] # (MonomeOscOut)
def __init__(self, action = None, data=None): Observable.__init__(self) self._action = action self._data = data
def __init__(self): dict.__init__(self) Observable.__init__(self) self.load()
def __init__(self): self.__contained = [] Observable.__init__(self)
def __init__(self, name, menu_id, title, subtitle, description): GalleryObject.__init__(self, menu_id, title, subtitle) Observable.__init__(self) self.__name = name self.__description = description
def __init__(self): Observable.__init__(self) Thread.__init__(self) if Globals.globFakeCamera: self.cmd = ["./fakecam.py", "fakecam.mjpg"]
def __init__(self, md, ds): Observable.__init__(self) self.motorDriver = md self.distanceSensor = ds self.distanceSensor.subscribe(self.update)
def __init__(self, device): self.device = device #AbstractDevice Observable.__init__(self) self.__acceptedAddressPrefixesIn = [] # (string[])
class Model: def __init__(self, num): """ Initilizes the model to represent a start board - A board of the given size with only one randomly placed block of value 2 Will throw TypeError if num is not an integer greater than or equal to 2 """ if num < 2: raise TypeError('Arugment number must be larger than 2') self.size = int(num) self.unoccupied_squares = [] l = [] # build the grid of empty squares, and add all to the list of unoccupied squares for i in range(num): m = [] for j in range(num): coordinate = i, j self.unoccupied_squares.append(coordinate) m.append(EMPTY_SQUARE_VALUE) l.append(m) # the grid is observable, so the controller can listen for changes self.grid = l self.last_move = Observable(None) def subscribe_to_moves(self, func): self.last_move.addCallback(func) def add_block_at(self, x, y, value): """ Adds a block at a specific point on the board Overwrites any value that is at the coordinate defined by (x,y) Does not check to see if coordinate is valid before adding """ self.grid[x][y] = value if (x, y) in self.unoccupied_squares and value != EMPTY_SQUARE_VALUE: self.unoccupied_squares.remove((x, y)) elif value == EMPTY_SQUARE_VALUE: self.unoccupied_squares.append((x, y)) def add_new_block(self): """ Adds a new block to a random non-occupied (value of zero) square on the board Returns the coordinates of the addition as a tuple """ if len(self.unoccupied_squares) == 0: raise slideexceptions.AddBlockError("GameBoard is Full") new_x, new_y = self.unoccupied_squares.pop(int(random.random() * len(self.unoccupied_squares))) # randomly picks 2 or 4 as the value of the new block val = int(random.random() * 2 + 1) * 2 self.grid[new_x][new_y] = val return (new_x, new_y) def value_at(self, x, y): """ Gets the value of the grid at the coordinate (x,y) on the board. Arugments: x (int) - x coordinate y (int) - y coordinate """ return self.grid[x][y] def count_blocks(self): """ Counts the number of blocks on the board Returns an integer representing the number of blocks on the board """ result = 0 for i in range(self.size): for j in range(self.size): b = self.value_at(i, j) if b > EMPTY_SQUARE_VALUE: result += 1 return result def shift_blocks_left(self): """ Shifts all blocks left and collapses same-valued blocks into their left neighbor """ return self._shift_blocks(1, 1) def shift_blocks_right(self): """ Shifts all blocks right and collapses same-valued blocks """ return self._shift_blocks(1, 0) def shift_blocks_up(self): """ Shifts all blocks up and collapses same-valued blocks """ return self._shift_blocks(0, 1) def shift_blocks_down(self): """ Shifts all blocks down and collapses same-valued blocks """ return self._shift_blocks(0, 0) def _shift_blocks(self, shift_horizontal, shift_to_bottom_left): """ Abstraction for shifting blocks in a direction Takes two arguements: shift_horizontal: Boolean - True means movement left-right, False means up-down shift_to_bottom_left: Boolean - True means movement toward origin(down,left), false means away(up,right) this means that the four direction have the following arguments: Left: self._shift_blocks(1,1) Right: self._shift_blocks(1,0) Up: self._shift_blocks(0,0) Down: self._shift_blocks(0,1) returns True if no blocks have moved positions, otherwise returns false """ no_merged = True no_moves = 0 for outer_iteration_value in range(self.size): last_block_val = EMPTY_SQUARE_VALUE # initialize the last open grid square to be the first square that will be checked, which is the lowest # number on the axis if moving down or left, otherwise it is the highest if shift_to_bottom_left: last_open = 0 else: last_open = self.size - 1 for inner_iteration_value in range(self.size): # if the blocks are being shifted down or left, the algorithm should look for blocks # with a lower coordinate value on the axis of movement (Y and X respectively), and should # begin its search from the lowest value of the axis of non movement (X and Y respectively) # if the blocks are being shfited up or right, the opposite is true if shift_to_bottom_left: directional_adjustment = -1 else: inner_iteration_value = self.size - inner_iteration_value - 1 directional_adjustment = 1 # if the blocks are being shifted horizontailly, iterate first by y coord, then x coord, i.e. # check spot (0,0), then (0,1), then (0,2). Otherwise, do the reverse if shift_horizontal: x_coord_old = inner_iteration_value y_coord_old = outer_iteration_value else: x_coord_old = outer_iteration_value y_coord_old = inner_iteration_value val = self.grid[x_coord_old][y_coord_old] # Check for case where blocks could merge if val > EMPTY_SQUARE_VALUE and val == last_block_val: last_block_val = val + val m = self._block_merge(last_block_val, x_coord_old, y_coord_old, last_open, directional_adjustment, shift_horizontal, shift_to_bottom_left) self.last_move.set(m) no_merged = False # Check for case where block could slide and collide elif val > EMPTY_SQUARE_VALUE: m = self._block_collide(val, x_coord_old, y_coord_old, last_open, shift_horizontal, shift_to_bottom_left) last_block_val = val last_open = last_open + (0 - directional_adjustment) if m[0] != m[1]: self.last_move.set(m) else: no_moves += 1 return no_moves == self.count_blocks() and no_merged def _block_merge(self, new_val, x_coord_old, y_coord_old, last_open, directional_adjustment, shift_horizontal, shift_to_bottom_left): """ Handles blocks of same value colliding with eachother and becoming a single block of twice their value Returns a tuple of coordinates - (old coordinates, new coordinates) """ if shift_horizontal: x_coord_new = last_open + directional_adjustment y_coord_new = y_coord_old else: x_coord_new = x_coord_old y_coord_new = last_open + directional_adjustment self.grid[x_coord_new][y_coord_new] = new_val self.grid[x_coord_old][y_coord_old] = EMPTY_SQUARE_VALUE self.unoccupied_squares.append((x_coord_old, y_coord_old)) old_coords = (x_coord_old, y_coord_old) new_coords = (x_coord_new, y_coord_new) return (old_coords, new_coords) def _block_collide(self, new_val, x_coord_old, y_coord_old, last_open, shift_horizontal, shift_to_bottom_left): """ Handles blocks moving and colliding with their right-most obstacle (wall or block of different value) Returns a tuple of coordinates - (old coordinates, new coordinates) """ if shift_horizontal: x_coord_new = last_open y_coord_new = y_coord_old else: x_coord_new = x_coord_old y_coord_new = last_open self.grid[x_coord_old][y_coord_old] = 0 self.grid[x_coord_new][y_coord_new] = new_val self.unoccupied_squares.append((x_coord_old, y_coord_old)) self.unoccupied_squares.remove((x_coord_new, y_coord_new)) old_coords = (x_coord_old, y_coord_old) new_coords = (x_coord_new, y_coord_new) return (old_coords, new_coords) def game_state_check(self): """ Returns the state of the game, which is one of the three values in the game_states class dictionary """ column_maxes = [] for column in self.grid: column_maxes.append(max(column)) board_max = max(column_maxes) if board_max == GAME_GOAL: return GAME_STATE["Win"] if self.no_valid_moves(): return GAME_STATE["Loss"] return GAME_STATE["Play"] def no_valid_moves(self): """ Determine if there are any valid moves available Returns a boolean - True if any of the four moves are possible """ if self.count_blocks() == (self.size * self.size): #The board is full of blocks, now check if any could be merged for i in range(self.size): for j in range(self.size): val = self.grid[i][j] left = (i > 0) and (self.grid[i - 1][j] == val) right = (i < self.size - 1) and (self.grid[i + 1][j] == val) down = (j > 0) and (self.grid[i][j - 1] == val) up = (j < self.size - 1) and (self.grid[i][j + 1] == val) if left or right or down or up: #Theres a direction that you can move in! return False # Theres no direction you can move in! return True # Board is not full, so obviously there is a spot a block could slide into return False