def _loop(self): while (True): bytes = ProtoSLIP.decodeFromSLIP(self.serial_port) values = [] if len(bytes) >= 2: for i in range(0, len(bytes), 2): values.append(bytes[i] << 8 | bytes[i + 1]) self.callback( values, lambda x: SerialComm.writeToSerialPort( self.serial_port, x)) time.sleep(self.sleep_time) self.serial_port.flush() SerialComm.disconnectFromSerialPort(self.serial_port) return
def __init__(self): #Board initialization code self.ser = SerialComm() self.board = [[0 for x in xrange(8)] for x in xrange(8)] self.board[0][0] = Rook(0, 0, "white", "Rook") self.board[7][0] = Rook(7, 0, "white", "Rook") self.board[1][0] = Knight(1, 0, "white", "Knight") self.board[6][0] = Knight(6, 0, "white", "Knight") self.board[2][0] = Bishop(2, 0, "white", "Bishop") self.board[5][0] = Bishop(5, 0, "white", "Bishop") self.board[3][0] = Queen(3, 0, "white", "Queen") self.board[4][0] = King(4, 0, "white", "King") for i in xrange(0,8): self.board[i][1] = Pawn(i, 1, "white", "Pawn") self.board[0][7] = Rook(0, 7, "black", "Rook") self.board[7][7] = Rook(7, 7, "black", "Rook") self.board[1][7] = Knight(1, 7, "black", "Knight") self.board[6][7] = Knight(6, 7, "black", "Knight") self.board[2][7] = Bishop(2, 7, "black", "Bishop") self.board[5][7] = Bishop(5, 7, "black", "Bishop") self.board[3][7] = Queen(3, 7, "black", "Queen") self.board[4][7] = King(4, 7, "black", "King") for i in xrange(0,8): self.board[i][6] = Pawn(i, 6, "black", "Pawn")
def __init__(self, port_name, baud_rate, callback, sleep_time=0.002): # 0.002 est un chiffre arbitraire, vous pouvez le modifier si vous avez des problèmes de performance self.sleep_time = 0.002 self.port_name = port_name self.baud_rate = baud_rate self.serial_port = SerialComm.connectToSerialPort(port_name, baud_rate) self.callback = callback self.thread = None
def convertMove(command): try: print command if command == "origin": s = SerialComm() s.moveToPosition([0,0],[0,0]) exit() temp = command.split() col1 = temp[0][0] col2 = temp[2][0] row1 = int(temp[0][1]) row2 = int(temp[2][1]) if col1 not in validSet or col2 not in validSet or \ row1 < 1 or row1 > 8 or row2 < 1 or row2 > 8: return () else: return (col1, row1, col2, row2) except Exception as e: print e.message return ()
def __init__(self): # Init bt + wifi # self.wifi = WifiComm("IP_ADDRESS", 7777) # Change serial port when using with Raspberry Pi self.ser = SerialComm("/dev/ttyACM0", 9600)
class CommController: bt = None wifi = None ser = None # Message queue -> whenever the queue is not empty, send it to the correct device # Message queue is updated when RPi reads something from whichever communication link btQueue = queue.Queue() wifiQueue = queue.Queue() serQueue = queue.Queue() def __init__(self): # Init bt + wifi # self.wifi = WifiComm("IP_ADDRESS", 7777) # Change serial port when using with Raspberry Pi self.ser = SerialComm("/dev/ttyACM0", 9600) def serialRead(self): while True: # Data is None if there is nothing being read (empty string) print("Before data read!") data = self.ser.read() if data != None and len(data) > 0: # Do data processing here # Determine the targeted device and send it there # if data begins with 0: # wifiQueue.put(data) # elif data begins with 1: # btQueue.put(data) # For testing purpose -> see that the Arduino should read "A" self.serQueue.put("A") # Give time between reading time.sleep(INTER_READ_DELAY) def serialWrite(self): while True: if not self.serQueue.empty(): # Blocking "get" -> block until an item is available data = self.serQueue.get() self.ser.write(data) print("Serial data writing is done!") # Give time between writing time.sleep(INTER_WRITE_DELAY) def wifiRead(self): while True: data = self.wifi.read() if data != None: # Do data processing here print("DATA READ WIFI: " + str(data)) self.wifiQueue.put("W") # Give time between reading time.sleep(INTER_READ_DELAY) def wifiWrite(self): while True: if not self.wifiQueue.empty(): # Blocking "get" -> block until an item is available data = self.wifiQueue.get() self.wifi.write(data) print("Serial data writing is done!") # Give time between writing time.sleep(INTER_WRITE_DELAY) def initialize(self): self.ser.start() # self.bt.start() # self.wifi.start() # Checking whether Android, Arduino, and Laptop are all ready # PING Serial # self.ser.write("R") # while self.ser.read() != "00000000": # time.sleep(0.3) # PING Android # PING Laptop # self.wifi.write("R") # while self.wifi.read() != "00000010": # time.sleep(0.3) print("RPi is ready for receiving and sending data!") print("Initialize threads!") # Thread initialization threading.Thread(target=self.serialRead).start() threading.Thread(target=self.serialWrite).start()
import SerialComm ser = SerialComm.SerialComm(port='/dev/ttyUSB0', baudrate=115200, timeout=1) print ser.login_status() ser.login('root', 'zilogic') print ser.login_status()
import swig.cometos as cometos from RemoteAccess import * from SerialComm import * from threading import Thread import time # Call this script with python -i ./remote.py to run interactive mode # don't forget to call shutdown() # INSTANTIATION --------------------------------------- comm=SerialComm("COM44",57600) crc=Crc16Layer() remote=RemoteAccess() disp=cometos.Dispatcher2() #printf=cometos.PrintfApp() # WIRING ---------------------------------------------- comm.gateIndOut.connectTo(crc.gateIndIn); crc.gateIndOut.connectTo(disp.gateIndIn); disp.gateIndOut.get(0).connectTo(remote.gateIndIn); #disp.gateIndOut.get(1).connectTo(printf.gateIndIn); #printf.gateReqOut.connectTo(disp.gateReqIn.get(1)); remote.gateReqOut.connectTo(disp.gateReqIn.get(0)); disp.gateReqOut.connectTo(crc.gateReqIn); crc.gateReqOut.connectTo(comm.gateReqIn);
class CommController: bt = None wifi = None ser = None # Message queue -> whenever the queue is not empty, send it to the correct device # Message queue is updated when RPi reads something from whichever communication link btQueue = queue.Queue() wifiQueue = queue.Queue() serQueue = queue.Queue() def __init__(self): # Init bt + wifi # self.wifi = WifiComm("IP_ADDRESS", 7777) # Change serial port when using with Raspberry Pi self.ser = SerialComm("/dev/ttyACM0", 9600) def serialRead(self): while True: # Data is None if there is nothing being read (empty string) print("Before data read!") data = self.ser.read() if data != None and len(data) > 0: # Do data processing here # Determine the targeted device and send it there # if data begins with 0: # wifiQueue.put(data) # elif data begins with 1: # btQueue.put(data) # For testing purpose -> see that the Arduino should read "A" self.serQueue.put("A") # Give time between reading time.sleep(INTER_READ_DELAY) def serialWrite(self): while True: if not self.serQueue.empty(): # Blocking "get" -> block until an item is available data = self.serQueue.get() self.ser.write(data) print("Serial data writing is done!") # Give time between writing time.sleep(INTER_WRITE_DELAY) def wifiRead(self): while True: data = self.wifi.read() if data != None: # Do data processing here print("DATA READ WIFI: " + str(data)) self.wifiQueue.put("W") # Give time between reading time.sleep(INTER_READ_DELAY) def wifiWrite(self): while True: if not self.wifiQueue.empty(): # Blocking "get" -> block until an item is available data = self.wifiQueue.get() self.wifi.write(data) print("Serial data writing is done!") # Give time between writing time.sleep(INTER_WRITE_DELAY) def initialize(self): self.ser.start() # self.bt.start() # self.wifi.start() # Checking whether Android, Arduino, and Laptop are all ready # PING Serial #self.ser.write("R") #while self.ser.read() != "00000000": # time.sleep(0.3) # PING Android # PING Laptop #self.wifi.write("R") #while self.wifi.read() != "00000010": # time.sleep(0.3) print("RPi is ready for receiving and sending data!") print("Initialize threads!") # Thread initialization threading.Thread(target=self.serialRead).start() threading.Thread(target=self.serialWrite).start()
def __init__(self): """ """ QtGui.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("Perkin Elmer Spectro") self.setWindowIcon(QtGui.QIcon('resources/icon/icon2.png')) # Create file menu self.__file_menu = QtGui.QMenu('&File', self) self.__file_menu.addAction('&Quit', self.file_quit, QtCore.Qt.CTRL + QtCore.Qt.Key_Q) self.menuBar().addMenu(self.__file_menu) # Create help menu self.__help_menu = QtGui.QMenu('&Help', self) self.menuBar().addSeparator() self.menuBar().addMenu(self.__help_menu) # self.__help_menu.addAction('&About', self.about) # Define main layout self.main_widget = QtGui.QWidget(self) __layout = QtGui.QGridLayout(self.main_widget) # Add buttons self.__btn_start_stop = QtGui.QPushButton('Start') self.__btn_clear = QtGui.QPushButton('Clear') self.__btn_add = QtGui.QPushButton('Add plot') self.__btn_clear.setDisabled(True) # Add Combo box self.__cb = QtGui.QComboBox() # Create & Define plot from PyQtgraph self.__main_plot = pg.PlotWidget() self.__rs_plot = pg.PlotWidget() self.curve = self.__main_plot.plot() self.curve1 = self.__rs_plot.plot() # Set X Range self.__rs_plot.setXRange(0.0, 4000) self.__main_plot.setXRange(0.0, 200) self.__main_plot.setYRange(0.0, 1024) # Add long plot of region selection self.lr = pg.LinearRegionItem([0, 200]) self.lr.setZValue(10) self.__rs_plot.addItem(self.lr) # Set config for each Plot Widget self.set_plot_conf(self.__main_plot) self.set_plot_conf(self.__rs_plot) # Defining cross hair self.v_line = pg.InfiniteLine(angle=90, pos=-1000, movable=False) self.h_line = pg.InfiniteLine(angle=0, pos=-1000, movable=False) # Defining the label for numeric value of every dot in spectrum self.xy_label = pg.LabelItem(justify='right', text='') # Adding Two lines and label to plot self.__main_plot.addItem(self.v_line) self.__main_plot.addItem(self.h_line) self.__main_plot.addItem(self.xy_label) # Create instance of some data, which we should plot self.__dev = SerialComm() self.__data = [Data()] self.index = self.__cb.currentIndex() self.__cb.addItem('Default plot') self.__cb.setEditable(True) self.timer = QtCore.QTimer() # Add some objects on Grid Layout (x position, y position, eat x rows, eat y columns ) __layout.addWidget(self.__btn_start_stop, 2, 0, 1, 2) __layout.addWidget(self.__btn_clear, 3, 0) __layout.addWidget(self.__btn_add, 3, 1) __layout.addWidget(self.__cb, 1, 0, 1, 2) __layout.addWidget(self.__rs_plot, 1, 4, 10, 1) # __plot goes on right side, spanning 11 rows __layout.addWidget(self.__main_plot, 11, 4, 2, 1) # __plot goes on right side, spanning 11 rows # Define signal&slots for buttons and Data instance self.connect(self.__btn_start_stop, QtCore.SIGNAL('clicked()'), self.clicked_start_stop) self.connect(self.__btn_clear, QtCore.SIGNAL('clicked()'), self.clicked_clear_data) self.connect(self.__btn_add, QtCore.SIGNAL('clicked()'), self.clicked_add_data) self.connect(self.__cb, QtCore.SIGNAL('currentIndexChanged()'), self.change_current_plot) # self.__cb.currentIndexChanged(self.change_current_plot) self.connect(self.__dev, QtCore.SIGNAL('started()'), self.on_started) self.connect(self.__dev, QtCore.SIGNAL('finished()'), self.on_finished) # Signal& slot connection for Thread which reads data from Serial port self.connect(self.__dev, QtCore.SIGNAL('run_signal(float,float)'), self.on_change, QtCore.Qt.QueuedConnection) # Signal& slot connection self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.re_plot) # Making signals for resizing __main_plot when region changed self.lr.sigRegionChanged.connect( lambda: self.__main_plot.setXRange(padding=0, *self.lr.getRegion())) self.__rs_plot.sigXRangeChanged.connect( lambda: self.lr.setRegion(self.__main_plot.plotItem.getViewBox().viewRange()[0])) self.__main_plot.plotItem.sigXRangeChanged.connect( lambda: self.lr.setRegion(self.__main_plot.plotItem.getViewBox().viewRange()[0]) ) self.__main_plot.scene().sigMouseMoved.connect(self.mouse_moved) self.main_widget.setFocus() self.setCentralWidget(self.main_widget)
class ApplicationWindow(QtGui.QMainWindow): """ This is simple program collecting and performing __data from spectrometer Perkin Elmer 599b. """ def __init__(self): """ """ QtGui.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("Perkin Elmer Spectro") self.setWindowIcon(QtGui.QIcon('resources/icon/icon2.png')) # Create file menu self.__file_menu = QtGui.QMenu('&File', self) self.__file_menu.addAction('&Quit', self.file_quit, QtCore.Qt.CTRL + QtCore.Qt.Key_Q) self.menuBar().addMenu(self.__file_menu) # Create help menu self.__help_menu = QtGui.QMenu('&Help', self) self.menuBar().addSeparator() self.menuBar().addMenu(self.__help_menu) # self.__help_menu.addAction('&About', self.about) # Define main layout self.main_widget = QtGui.QWidget(self) __layout = QtGui.QGridLayout(self.main_widget) # Add buttons self.__btn_start_stop = QtGui.QPushButton('Start') self.__btn_clear = QtGui.QPushButton('Clear') self.__btn_add = QtGui.QPushButton('Add plot') self.__btn_clear.setDisabled(True) # Add Combo box self.__cb = QtGui.QComboBox() # Create & Define plot from PyQtgraph self.__main_plot = pg.PlotWidget() self.__rs_plot = pg.PlotWidget() self.curve = self.__main_plot.plot() self.curve1 = self.__rs_plot.plot() # Set X Range self.__rs_plot.setXRange(0.0, 4000) self.__main_plot.setXRange(0.0, 200) self.__main_plot.setYRange(0.0, 1024) # Add long plot of region selection self.lr = pg.LinearRegionItem([0, 200]) self.lr.setZValue(10) self.__rs_plot.addItem(self.lr) # Set config for each Plot Widget self.set_plot_conf(self.__main_plot) self.set_plot_conf(self.__rs_plot) # Defining cross hair self.v_line = pg.InfiniteLine(angle=90, pos=-1000, movable=False) self.h_line = pg.InfiniteLine(angle=0, pos=-1000, movable=False) # Defining the label for numeric value of every dot in spectrum self.xy_label = pg.LabelItem(justify='right', text='') # Adding Two lines and label to plot self.__main_plot.addItem(self.v_line) self.__main_plot.addItem(self.h_line) self.__main_plot.addItem(self.xy_label) # Create instance of some data, which we should plot self.__dev = SerialComm() self.__data = [Data()] self.index = self.__cb.currentIndex() self.__cb.addItem('Default plot') self.__cb.setEditable(True) self.timer = QtCore.QTimer() # Add some objects on Grid Layout (x position, y position, eat x rows, eat y columns ) __layout.addWidget(self.__btn_start_stop, 2, 0, 1, 2) __layout.addWidget(self.__btn_clear, 3, 0) __layout.addWidget(self.__btn_add, 3, 1) __layout.addWidget(self.__cb, 1, 0, 1, 2) __layout.addWidget(self.__rs_plot, 1, 4, 10, 1) # __plot goes on right side, spanning 11 rows __layout.addWidget(self.__main_plot, 11, 4, 2, 1) # __plot goes on right side, spanning 11 rows # Define signal&slots for buttons and Data instance self.connect(self.__btn_start_stop, QtCore.SIGNAL('clicked()'), self.clicked_start_stop) self.connect(self.__btn_clear, QtCore.SIGNAL('clicked()'), self.clicked_clear_data) self.connect(self.__btn_add, QtCore.SIGNAL('clicked()'), self.clicked_add_data) self.connect(self.__cb, QtCore.SIGNAL('currentIndexChanged()'), self.change_current_plot) # self.__cb.currentIndexChanged(self.change_current_plot) self.connect(self.__dev, QtCore.SIGNAL('started()'), self.on_started) self.connect(self.__dev, QtCore.SIGNAL('finished()'), self.on_finished) # Signal& slot connection for Thread which reads data from Serial port self.connect(self.__dev, QtCore.SIGNAL('run_signal(float,float)'), self.on_change, QtCore.Qt.QueuedConnection) # Signal& slot connection self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.re_plot) # Making signals for resizing __main_plot when region changed self.lr.sigRegionChanged.connect( lambda: self.__main_plot.setXRange(padding=0, *self.lr.getRegion())) self.__rs_plot.sigXRangeChanged.connect( lambda: self.lr.setRegion(self.__main_plot.plotItem.getViewBox().viewRange()[0])) self.__main_plot.plotItem.sigXRangeChanged.connect( lambda: self.lr.setRegion(self.__main_plot.plotItem.getViewBox().viewRange()[0]) ) self.__main_plot.scene().sigMouseMoved.connect(self.mouse_moved) self.main_widget.setFocus() self.setCentralWidget(self.main_widget) def mouse_moved(self, evt): """ Actions for performing changing cross hair lines from mouse moving :param evt: type: QPointF. Coordinates of Mouse on Plot. """ # performing Moving Slot if self.__main_plot.plotItem.sceneBoundingRect().contains(evt): mouse_point = self.__main_plot.plotItem.vb.mapSceneToView(evt) index = int(mouse_point.x()) if 0 < index < len(self.__data[self.index].x_data): self.xy_label.setText( "<span style='font-size: 12pt'>x=%0.1f</span>, " "<span style='color: red'>y1=%0.1f</span>" % (mouse_point.x(), self.__data[self.index].y_data[index])) self.v_line.setPos(mouse_point.x()) self.h_line.setPos(self.__data[self.index].y_data[index]) def on_change(self, a, b): index = self.__cb.currentIndex() self.__data[index].x_data.append(a) self.__data[index].y_data.append(b) # self.__curve.setData(self.__data.x_data, self.__data.y_data, _callSync='off') def clicked_start_stop(self): """ Slot Function for Start/Stop button :return: """ index = self.__cb.currentIndex() if len(self.__data[index].x_data) > 1: self.__btn_clear.setDisabled(False) if not self.__dev.is_connected: self.__btn_start_stop.setText("Stop") self.__dev.connect() self.__dev.start() else: self.__btn_start_stop.setText("Start") self.__dev.disconnect() self.timer.stop() def on_started(self): """ Slot Function for starting Thread. :return: """ self.statusBar().showMessage("Connected and Started!", 2000) self.timer.start(100) print ("Timer started") def on_finished(self): self.statusBar().showMessage("Finished!", 2000) self.timer.stop() def clicked_clear_data(self): self.__data.pop() def clicked_add_data(self): name, ok = QtGui.QInputDialog.getText(self, "QInputDialog.getText()", "Plot name:", QtGui.QLineEdit.Normal) if ok: # name.setComboBoxEditable() self.__data.append(Data()) # print name.getItem() self.__cb.addItem(name) def change_current_plot(self): x = self.__data[self.index].x_data y = self.__data[self.index].y_data self.curve1.setData(x, y, pen=(0, 0, 255)) @staticmethod def set_plot_conf(obj): """ Sets some pyQtGraph settings such as WindowTitle, OX and OY labels, measuring units. :type obj: pyqtpraph Widqget """ # self.__plot.setWindowTitle('pyqtgraph example: __plotSpeedTest') try: obj.setLabel('bottom', 'WaveNumber', units='1/cm') obj.setLabel('left', 'Transmittance') obj.showGrid(x=True, y=True) obj.invertX() except AttributeError: print(AttributeError) pass def re_plot(self): """ :return: """ try: self.curve.setData(self.__data[self.index].x_data, self.__data[self.index].y_data) self.curve1.setData(self.__data[self.index].x_data, self.__data[self.index].y_data) except Exception as e: print(e) return 1, e return 0 def file_quit(self): """ :return: """ if self.__dev.isRunning(): self.__dev.disconnect() def closeEvent(self, event): self.file_quit() self.hide() event.accept()
class Board(): #TODO: Fix move peices off board def __init__(self): #Board initialization code self.ser = SerialComm() self.board = [[0 for x in xrange(8)] for x in xrange(8)] self.board[0][0] = Rook(0, 0, "white", "Rook") self.board[7][0] = Rook(7, 0, "white", "Rook") self.board[1][0] = Knight(1, 0, "white", "Knight") self.board[6][0] = Knight(6, 0, "white", "Knight") self.board[2][0] = Bishop(2, 0, "white", "Bishop") self.board[5][0] = Bishop(5, 0, "white", "Bishop") self.board[3][0] = Queen(3, 0, "white", "Queen") self.board[4][0] = King(4, 0, "white", "King") for i in xrange(0,8): self.board[i][1] = Pawn(i, 1, "white", "Pawn") self.board[0][7] = Rook(0, 7, "black", "Rook") self.board[7][7] = Rook(7, 7, "black", "Rook") self.board[1][7] = Knight(1, 7, "black", "Knight") self.board[6][7] = Knight(6, 7, "black", "Knight") self.board[2][7] = Bishop(2, 7, "black", "Bishop") self.board[5][7] = Bishop(5, 7, "black", "Bishop") self.board[3][7] = Queen(3, 7, "black", "Queen") self.board[4][7] = King(4, 7, "black", "King") for i in xrange(0,8): self.board[i][6] = Pawn(i, 6, "black", "Pawn") def checkValidMove(self, x, y, newX, newY, colorTurn): piece = self.board[x][y] if(piece == 0): return False elif(x == newX and y == newY): return False elif(piece.get_color() != colorTurn): return False elif(not piece.move(newX, newY)): return False #Vertical if(x == newX): for i in range(piece.get_y(), newY): if i != piece.get_y() and self.board[x][i]: return False return self.takeLastPiece(piece, newX, newY, False) #Horizontal elif(y == newY): for i in range(piece.get_x(), newX): if i != piece.get_x() and self.board[i][y]: return False return self.takeLastPiece(piece, newX, newY, False) #Knight elif(piece.get_name() == "Knight"): if(self.board[newX][newY] == 0 or self.board[newX][newY].get_color() != piece.get_color()): if(abs(piece.get_x() - newX) == 2): dir = 1 if(piece.get_x() < newX) else - 1 coordinates = self.move_for_knight(x + dir, y, newX, newY) else: dir = 1 if(piece.get_y() < newY) else - 1 coordinates = self.move_for_knight(x, y + dir, newX, newY) if(coordinates): if(self.board[newX][newY] != 0): self.move_piece_off_board(newX, newY) else: return False else: return False if(abs(piece.get_x() - newX) == 2): dir = 1 if(piece.get_x() < newX) else -1 self.move_piece_serial(x , y, x + dir, y) self.move_piece_serial(x + dir, y, newX, newY) piece.update_coordinate(newX, newY) else: dir = 1 if(piece.get_y() < newY) else -1 self.move_piece_serial(x, y, x, y + dir) self.move_piece_serial(x, y + dir, newX, newY) piece.update_coordinate(newX, newY) self.board[newX][newY] = piece if(len(coordinates) == 4): self.board[coordinates[0]][coordinates[1]] = self.board[coordinates[2]][coordinates[3]] self.move_piece_serial(coordinates[2], coordinates[3], coordinates[0], coordinates[1]) return True #Diagonal else: xDir = 1 if(piece.get_x() < newX) else -1 yDir = 1 if(piece.get_y() < newY) else -1 lateralDist = abs(newX - piece.get_x()) for i in range(0, lateralDist): if(i != 0 and self.board[piece.get_x() + xDir * i][piece.get_y() + yDir * i]): return False return self.takeLastPiece(piece, newX, newY, piece.get_name() == "Pawn") def takeLastPiece(self, piece, newX, newY, isPawnDiag): if(isPawnDiag): if(self.board[newX][newY] == 0 or self.board[newX][newY].get_color() == piece.get_color()): piece.decrementMoves() return False elif(self.board[newX][newY] != 0 and (self.board[newX][newY].get_color() == piece.get_color() or piece.get_name() == "Pawn")): return False self.board[piece.get_x()][piece.get_y()] = 0 if(self.board[newX][newY] != 0): self.move_piece_off_board(newX, newY) #Handle move off board self.move_piece_serial(piece.get_x(), piece.get_y(), newX, newY) self.board[newX][newY] = piece piece.update_coordinate(newX, newY) return True #Pass coordinates for serial movement def move_piece_serial(self, x, y, newX, newY): self.board[x][y] = 0 self.ser.moveToPosition((x, y), (newX, newY)) pass def move_piece_off_board(self, newX, newY): print "move off board" left =0 right = 0 stack = [] for i in range(0, 8): if i < newX and self.board[i][newY]: left += 1 if i > newX and self.board[i][newY]: right += 1 if left < right: for i in range(0, newX): if self.board[i][newY]: stack.append(self.move_for_knight(i, newY, i, newY)) self.move_piece_serial(newX, newY, -1, newY) else: for i in range(newX+1, 8): if self.board[i][newY]: stack.append(self.move_for_knight(i, newY, i, newY)) self.move_piece_serial(newX, newY, 9, newY) while stack: temp = stack.pop() self.board[temp[0]][temp[1]] = self.board[temp[2]][temp[3]] self.move_piece_serial(temp[2], temp[3], temp[0], temp[1]) self.board[newX][newY] = 0 pass def move_for_knight(self, x, y, finalX, finalY): if(self.board[x][y] == 0): return (1, 2) piece = self.board[x][y] for i in range(-1, 2): for j in range(-1, 2): if(self.board[x + i][y + j] == 0 and (x + i != finalX or y + j != finalY)): self.move_piece_serial(x, y, x + i, y + j) self.board[x + i][y + j] = piece return (x, y, x + i, y + j) print("Currently can't make room for the knight") return() def printBoard(self): for i in range(0, 8): print "" for j in range(0, 8): if(self.board[j][7 - i] == 0): print("0"), else: print(self.board[j][7 - i].get_name()[0]),