def newGameCount2(self, instance): self.playBar.text = "1" self.playBar.font_size = '40sp' self.event3 = Clock.schedule_once(self.newGameCount3, 1) del self.snake self.moveX = 0 self.moveY = 0 self.snake = Snake(intelligence=False) self.drawScreen(0)
def againButton(self, instance): self.event.cancel() del self.snake self.snake = Snake(intelligence=True, fieldSize=self.fieldSize - 2) self.snake.importBrain(rates=self.weights[self.indexWeight].copy(), noOfNeuron1=self.noOfNeuron1Layer, noOfNeuron2=self.noOfNeuron2Layer) self.event = Clock.schedule_interval(self.drawScreen, 1 / self.snakeSpeed)
def twoPointCrossover(self): if len(self.inSnakes) % 2 == 1: self.inSnakes.insert(0, self.inSnakes[0]) ratesOffspringList = [] inSnake = self.inSnakes.copy() while inSnake: index1 = np.random.randint(len(inSnake)) parent1 = inSnake[index1] inSnake.pop(index1) index2 = np.random.randint(len(inSnake)) parent2 = inSnake[index2] inSnake.pop(index2) rates1 = [] rates2 = [] ratesOffspring = [] rates1 = parent1.exportBrain() rates2 = parent2.exportBrain() randSpots = [np.random.randint(len(rates1)), np.random.randint(len(rates1)), np.random.randint(len(rates1))] randSpots.sort() ratesOffspring = rates1[:randSpots[0]] + rates2[randSpots[0]:randSpots[1]] + rates1[randSpots[1]:randSpots[2]] + rates2[randSpots[0]:] ratesOffspringList.append(ratesOffspring) numOffsprigns = int(self.noOutSnakes/len(ratesOffspringList)) offspringsList = [numOffsprigns] * len(ratesOffspringList) i = 0 while sum(offspringsList) < self.noOutSnakes: offspringsList[i] += 1 i += 1 for i in range(len(offspringsList)): for j in range(offspringsList[i] - 2): ratesOld = ratesOffspringList[i].copy() ratesNew = self.mutation(ratesOld) self.outSnakes.append(Snake(intelligence=True)) self.outSnakes[-1].importBrain(ratesNew, noOfNeuron1=self.noOfNeuron1Layer, noOfNeuron2=self.noOfNeuron2Layer) for i in range(len(self.inSnakes)): ratesOld = self.inSnakes[i].exportBrain() self.outSnakes.append(Snake(intelligence=True)) self.outSnakes[-1].importBrain(ratesOld, noOfNeuron1=self.noOfNeuron1Layer, noOfNeuron2=self.noOfNeuron2Layer) return self.outSnakes
def live(self, parents=[]): if not parents: for i in range(self.noOfSnakes): self.snakes.append(Snake(intelligence=True)) self.snakes[i].randomBrain(noOfNeuron1 = self.noOfNeuron1Layer, noOfNeuron2=self.noOfNeuron2Layer) else: cross = Crossover(inSnakes=parents.copy(), noOfOutSnakes=self.noOfSnakes, mutationRate=self.mutationRate, noNeuron1Layer=self.noOfNeuron1Layer, noNeuron2Layer=self.noOfNeuron2Layer) self.snakes = cross.onePointCrossover() del cross thrHandle = [] for i in range(self.noOfThreads): arg1 = i * int(self.noOfSnakes/self.noOfThreads) arg2 = arg1 + int(self.noOfSnakes/self.noOfThreads) if i == self.noOfThreads-1: thrHandle.append(threading.Thread(target=self.simulateSnakeThr, args=(arg1, self.noOfSnakes,), daemon=True)) else: thrHandle.append(threading.Thread(target=self.simulateSnakeThr, args=(arg1, arg2,), daemon=True)) for thr in thrHandle: thr.start() for thr in thrHandle: thr.join()
def simpleCrossover(self): numOffsprigns = int(self.noOutSnakes/len(self.inSnakes)) offspringsList = [numOffsprigns] * len(self.inSnakes) i = 0 while sum(offspringsList) < self.noOutSnakes: offspringsList[i] += 1 i += 1 for i in range(len(offspringsList)): for j in range(offspringsList[i]-1): ratesOld = self.inSnakes[i].exportBrain() ratesNew = self.mutation(ratesOld) self.outSnakes.append(Snake(intelligence=True)) self.outSnakes[-1].importBrain(ratesNew, noOfNeuron1=self.noOfNeuron1Layer, noOfNeuron2=self.noOfNeuron2Layer) ratesOld = self.inSnakes[i].exportBrain() self.outSnakes.append(Snake(intelligence=True)) self.outSnakes[-1].importBrain(ratesOld, noOfNeuron1=self.noOfNeuron1Layer, noOfNeuron2=self.noOfNeuron2Layer) return self.outSnakes
def __init__(self, **kwargs): super(PlayScreen, self).__init__(**kwargs) self.moveX = 0 self.moveY = 0 self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) self.cols = 1 ############################## FILL PLAY SCREEN ################################################ field = GridLayout( cols=globalVars.fieldSize, rows=globalVars.fieldSize, row_force_default=False, row_default_height=Window.size[0] / globalVars.fieldSize - 1, spacing=1) self.screenCell = [] for i in range(globalVars.fieldSize * globalVars.fieldSize): self.screenCell.append(LabelB(bcolor=(0, 0, 0, 1))) field.add_widget(self.screenCell[i]) self.add_widget(field) ############################## SPACING ################################################ self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) ############################## COUNTER LABEL 3 2 1 PLAY ################################################ self.playBar = Label(text="3", color=(0, 1, 0, 1), font_size='40sp') self.add_widget(self.playBar) scoreLine = GridLayout(cols=7, rows=1, row_force_default=True, row_default_height=40) self.scoreLabel = Label(text='1', font_size='20sp', size_hint_x=None, width=50) self.movesLabel = Label(text='0', font_size='20sp', size_hint_x=None, width=50) ############################## SCORE MOVES ################################################ scoreLine.add_widget(Label()) scoreLine.add_widget( Label(text='Score:', font_size='20sp', size_hint_x=None, width=100)) scoreLine.add_widget(self.scoreLabel) scoreLine.add_widget(Label()) scoreLine.add_widget( Label(text='Moves:', font_size='20sp', size_hint_x=None, width=100)) scoreLine.add_widget(self.movesLabel) scoreLine.add_widget(Label()) self.add_widget(scoreLine) ############################## LABELS INFO ################################################ foodLine = GridLayout(cols=7, rows=1, row_force_default=True, row_default_height=60) self.movesWithoutFoodLabel = Label(text='0', font_size='20sp', size_hint_x=None, width=50) self.foodMovesRatioLabel = Label(text='0', font_size='20sp', size_hint_x=None, width=50) foodLine.add_widget(Label()) foodLine.add_widget( Label(text=' Moves \nwithout food:', font_size='20sp', size_hint_x=None, width=100)) foodLine.add_widget(self.movesWithoutFoodLabel) foodLine.add_widget(Label()) foodLine.add_widget( Label(text='Moves to\nfood ratio:', font_size='20sp', size_hint_x=None, width=100)) foodLine.add_widget(self.foodMovesRatioLabel) foodLine.add_widget(Label()) self.add_widget(foodLine) ############################## BUTTONS ################################################ botLine = BoxLayout(orientation='horizontal', spacing=10) playAgainBut = Button(text="Play again", size_hint=(0.4, 0.8), font_size='20sp') playAgainBut.bind(on_press=self.playAgainButton) botLine.add_widget(Label(size_hint=(0.05, 0.7))) botLine.add_widget( ImageButton(source='Icons/down.png', size_hint=(0.1, 0.8))) botLine.add_widget(Label(size_hint=(0.1, 0.7))) botLine.add_widget(playAgainBut) botLine.add_widget(Label(size_hint=(0.25, 0.7))) self.add_widget(botLine) self.add_widget(Label()) self.snake = Snake() self.newGame()
class PlayScreen(GridLayout): def __init__(self, **kwargs): super(PlayScreen, self).__init__(**kwargs) self.moveX = 0 self.moveY = 0 self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) self.cols = 1 ############################## FILL PLAY SCREEN ################################################ field = GridLayout( cols=globalVars.fieldSize, rows=globalVars.fieldSize, row_force_default=False, row_default_height=Window.size[0] / globalVars.fieldSize - 1, spacing=1) self.screenCell = [] for i in range(globalVars.fieldSize * globalVars.fieldSize): self.screenCell.append(LabelB(bcolor=(0, 0, 0, 1))) field.add_widget(self.screenCell[i]) self.add_widget(field) ############################## SPACING ################################################ self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) ############################## COUNTER LABEL 3 2 1 PLAY ################################################ self.playBar = Label(text="3", color=(0, 1, 0, 1), font_size='40sp') self.add_widget(self.playBar) scoreLine = GridLayout(cols=7, rows=1, row_force_default=True, row_default_height=40) self.scoreLabel = Label(text='1', font_size='20sp', size_hint_x=None, width=50) self.movesLabel = Label(text='0', font_size='20sp', size_hint_x=None, width=50) ############################## SCORE MOVES ################################################ scoreLine.add_widget(Label()) scoreLine.add_widget( Label(text='Score:', font_size='20sp', size_hint_x=None, width=100)) scoreLine.add_widget(self.scoreLabel) scoreLine.add_widget(Label()) scoreLine.add_widget( Label(text='Moves:', font_size='20sp', size_hint_x=None, width=100)) scoreLine.add_widget(self.movesLabel) scoreLine.add_widget(Label()) self.add_widget(scoreLine) ############################## LABELS INFO ################################################ foodLine = GridLayout(cols=7, rows=1, row_force_default=True, row_default_height=60) self.movesWithoutFoodLabel = Label(text='0', font_size='20sp', size_hint_x=None, width=50) self.foodMovesRatioLabel = Label(text='0', font_size='20sp', size_hint_x=None, width=50) foodLine.add_widget(Label()) foodLine.add_widget( Label(text=' Moves \nwithout food:', font_size='20sp', size_hint_x=None, width=100)) foodLine.add_widget(self.movesWithoutFoodLabel) foodLine.add_widget(Label()) foodLine.add_widget( Label(text='Moves to\nfood ratio:', font_size='20sp', size_hint_x=None, width=100)) foodLine.add_widget(self.foodMovesRatioLabel) foodLine.add_widget(Label()) self.add_widget(foodLine) ############################## BUTTONS ################################################ botLine = BoxLayout(orientation='horizontal', spacing=10) playAgainBut = Button(text="Play again", size_hint=(0.4, 0.8), font_size='20sp') playAgainBut.bind(on_press=self.playAgainButton) botLine.add_widget(Label(size_hint=(0.05, 0.7))) botLine.add_widget( ImageButton(source='Icons/down.png', size_hint=(0.1, 0.8))) botLine.add_widget(Label(size_hint=(0.1, 0.7))) botLine.add_widget(playAgainBut) botLine.add_widget(Label(size_hint=(0.25, 0.7))) self.add_widget(botLine) self.add_widget(Label()) self.snake = Snake() self.newGame() def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'right': self.moveX = 1 self.moveY = 0 elif keycode[1] == 'left': self.moveX = -1 self.moveY = 0 elif keycode[1] == 'down': self.moveX = 0 self.moveY = 1 elif keycode[1] == 'up': self.moveX = 0 self.moveY = -1 return True def drawScreen(self, instance): if self.snake.snakeStep(Xdir=self.moveX, Ydir=self.moveY): self.screenCell = globalFcns.drawField(screenCell=self.screenCell, field=self.snake.field) else: if self.snake.win: self.screenCell = globalFcns.drawField( screenCell=self.screenCell, field=self.snake.field) self.event.cancel() self.screenCell = globalFcns.drawField( screenCell=self.screenCell, field=self.snake.field, opacity=0.5) self.moveX = 0 self.moveY = 0 self.playBar.text = "YOU WIN" self.playBar.font_size = '30sp' else: self.screenCell = globalFcns.drawField( screenCell=self.screenCell, field=self.snake.field) self.event.cancel() self.screenCell = globalFcns.drawField( screenCell=self.screenCell, field=self.snake.field, opacity=0.5) self.moveX = 0 self.moveY = 0 self.playBar.text = "GAME OVER" self.playBar.font_size = '30sp' self.scoreLabel.text = str(self.snake.score) self.movesLabel.text = str(self.snake.noOfMoves) self.movesWithoutFoodLabel.text = str(self.snake.noWithoutFood) self.foodMovesRatioLabel.text = str(round(self.snake.foodMovesRatio, 1)) def playAgainButton(self, instance): self.screenCell = globalFcns.drawField(screenCell=self.screenCell, field=self.snake.field, opacity=0.5) try: self.event.cancel() self.event1.cancel() self.event2.cancel() self.event3.cancel() except: pass self.moveX = 0 self.moveY = 0 self.newGame() def newGame(self): self.playBar.text = "3" self.playBar.font_size = '40sp' self.event1 = Clock.schedule_once(self.newGameCount1, 1) def newGameCount1(self, instance): self.playBar.text = "2" self.playBar.font_size = '40sp' self.event2 = Clock.schedule_once(self.newGameCount2, 1) def newGameCount2(self, instance): self.playBar.text = "1" self.playBar.font_size = '40sp' self.event3 = Clock.schedule_once(self.newGameCount3, 1) del self.snake self.moveX = 0 self.moveY = 0 self.snake = Snake(intelligence=False) self.drawScreen(0) def newGameCount3(self, instance): self.event = Clock.schedule_interval(self.drawScreen, 1 / globalVars.snakeSpeed) self.playBar.text = "PLAY" self.playBar.font_size = '30sp'
def __init__(self, **kwargs): super(SimulateScreen, self).__init__(**kwargs) Window.size = (450, 750) global fieldSize global snakeSpeed global fileName global indexWeight self.fieldSize = fieldSize self.snakeSpeed = snakeSpeed self.fileName = fileName self.indexWeight = indexWeight - 1 self.readWeightCsv(self.fileName) self.cols = 1 ########################### SIMULATION FIELD ############################################################# field = GridLayout(cols=self.fieldSize, rows=self.fieldSize, row_force_default=False, row_default_height=Window.size[0] / self.fieldSize - 1, spacing=1) self.screenCell = [] for i in range(self.fieldSize * self.fieldSize): self.screenCell.append(LabelB(bcolor=(0, 0, 0, 1))) field.add_widget(self.screenCell[i]) self.add_widget(field) ########################### SIMULATE AGAIN BUTTON ############################################################# self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) againLine = GridLayout(cols=3, row_force_default=True, row_default_height=50) againBut = Button( text='Again', size_hint_x=None, width=200, font_size='20sp', ) againBut.bind(on_press=self.againButton) againLine.add_widget(Label()) againLine.add_widget(againBut) againLine.add_widget(Label()) self.add_widget(againLine) ############################## SCORE MOVES ################################################ scoreLine = GridLayout(cols=7, rows=1, row_force_default=True, row_default_height=40) self.scoreLabel = Label(text='1', size_hint_x=None, width=50, font_size='20sp') self.movesLabel = Label(text='0', size_hint_x=None, width=50, font_size='20sp') scoreLine.add_widget(Label()) scoreLine.add_widget( Label(text='Score:', font_size='20sp', size_hint_x=None, width=100)) scoreLine.add_widget(self.scoreLabel) scoreLine.add_widget(Label()) scoreLine.add_widget( Label(text='Moves:', font_size='20sp', size_hint_x=None, width=100)) scoreLine.add_widget(self.movesLabel) scoreLine.add_widget(Label()) self.add_widget(scoreLine) ############################## LABELS INFO ################################################ foodLine = GridLayout(cols=7, rows=1, row_force_default=True, row_default_height=60) self.movesWithoutFoodLabel = Label(text='0', font_size='20sp', size_hint_x=None, width=50) self.foodMovesRatioLabel = Label(text='0', font_size='20sp', size_hint_x=None, width=50) foodLine.add_widget(Label()) foodLine.add_widget( Label(text=' Moves \nwithout food:', font_size='20sp', size_hint_x=None, width=100)) foodLine.add_widget(self.movesWithoutFoodLabel) foodLine.add_widget(Label()) foodLine.add_widget( Label(text='Moves to\nfood ratio:', font_size='20sp', size_hint_x=None, width=100)) foodLine.add_widget(self.foodMovesRatioLabel) foodLine.add_widget(Label()) self.add_widget(foodLine) self.snake = Snake(intelligence=True, fieldSize=self.fieldSize - 2) self.snake.importBrain(rates=self.weights[self.indexWeight].copy(), noOfNeuron1=self.noOfNeuron1Layer, noOfNeuron2=self.noOfNeuron2Layer) self.event = Clock.schedule_interval(self.drawScreen, 1 / self.snakeSpeed)
class SimulateScreen(GridLayout): def __init__(self, **kwargs): super(SimulateScreen, self).__init__(**kwargs) Window.size = (450, 750) global fieldSize global snakeSpeed global fileName global indexWeight self.fieldSize = fieldSize self.snakeSpeed = snakeSpeed self.fileName = fileName self.indexWeight = indexWeight - 1 self.readWeightCsv(self.fileName) self.cols = 1 ########################### SIMULATION FIELD ############################################################# field = GridLayout(cols=self.fieldSize, rows=self.fieldSize, row_force_default=False, row_default_height=Window.size[0] / self.fieldSize - 1, spacing=1) self.screenCell = [] for i in range(self.fieldSize * self.fieldSize): self.screenCell.append(LabelB(bcolor=(0, 0, 0, 1))) field.add_widget(self.screenCell[i]) self.add_widget(field) ########################### SIMULATE AGAIN BUTTON ############################################################# self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) self.add_widget(Label()) againLine = GridLayout(cols=3, row_force_default=True, row_default_height=50) againBut = Button( text='Again', size_hint_x=None, width=200, font_size='20sp', ) againBut.bind(on_press=self.againButton) againLine.add_widget(Label()) againLine.add_widget(againBut) againLine.add_widget(Label()) self.add_widget(againLine) ############################## SCORE MOVES ################################################ scoreLine = GridLayout(cols=7, rows=1, row_force_default=True, row_default_height=40) self.scoreLabel = Label(text='1', size_hint_x=None, width=50, font_size='20sp') self.movesLabel = Label(text='0', size_hint_x=None, width=50, font_size='20sp') scoreLine.add_widget(Label()) scoreLine.add_widget( Label(text='Score:', font_size='20sp', size_hint_x=None, width=100)) scoreLine.add_widget(self.scoreLabel) scoreLine.add_widget(Label()) scoreLine.add_widget( Label(text='Moves:', font_size='20sp', size_hint_x=None, width=100)) scoreLine.add_widget(self.movesLabel) scoreLine.add_widget(Label()) self.add_widget(scoreLine) ############################## LABELS INFO ################################################ foodLine = GridLayout(cols=7, rows=1, row_force_default=True, row_default_height=60) self.movesWithoutFoodLabel = Label(text='0', font_size='20sp', size_hint_x=None, width=50) self.foodMovesRatioLabel = Label(text='0', font_size='20sp', size_hint_x=None, width=50) foodLine.add_widget(Label()) foodLine.add_widget( Label(text=' Moves \nwithout food:', font_size='20sp', size_hint_x=None, width=100)) foodLine.add_widget(self.movesWithoutFoodLabel) foodLine.add_widget(Label()) foodLine.add_widget( Label(text='Moves to\nfood ratio:', font_size='20sp', size_hint_x=None, width=100)) foodLine.add_widget(self.foodMovesRatioLabel) foodLine.add_widget(Label()) self.add_widget(foodLine) self.snake = Snake(intelligence=True, fieldSize=self.fieldSize - 2) self.snake.importBrain(rates=self.weights[self.indexWeight].copy(), noOfNeuron1=self.noOfNeuron1Layer, noOfNeuron2=self.noOfNeuron2Layer) self.event = Clock.schedule_interval(self.drawScreen, 1 / self.snakeSpeed) def againButton(self, instance): self.event.cancel() del self.snake self.snake = Snake(intelligence=True, fieldSize=self.fieldSize - 2) self.snake.importBrain(rates=self.weights[self.indexWeight].copy(), noOfNeuron1=self.noOfNeuron1Layer, noOfNeuron2=self.noOfNeuron2Layer) self.event = Clock.schedule_interval(self.drawScreen, 1 / self.snakeSpeed) def drawScreen(self, instance): self.scoreLabel.text = str(self.snake.score) self.movesLabel.text = str(self.snake.noOfMoves) self.movesWithoutFoodLabel.text = str(self.snake.noWithoutFood) self.foodMovesRatioLabel.text = str(round(self.snake.foodMovesRatio, 1)) if self.snake.snakeStep(): self.screenCell = globalFcns.drawField(screenCell=self.screenCell, field=self.snake.field) else: if self.snake.win: self.screenCell = globalFcns.drawField( screenCell=self.screenCell, field=self.snake.field) self.event.cancel() self.screenCell = globalFcns.drawField( screenCell=self.screenCell, field=self.snake.field, opacity=0.5) else: self.screenCell = globalFcns.drawField( screenCell=self.screenCell, field=self.snake.field) self.event.cancel() self.screenCell = globalFcns.drawField( screenCell=self.screenCell, field=self.snake.field, opacity=0.5) def readWeightCsv(self, fileName): with open(fileName) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') self.weights = [] for row in csv_reader: if row[0] == 'noOfNeuron1Layer': self.noOfNeuron1Layer = int(row[1]) if row[0] == 'noOfNeuron2Layer': self.noOfNeuron2Layer = int(row[1]) if row[0] == 'weights': self.weights.append( list(map(float, row[1][1:-1].split(','))))