def d(self): while logic.game_state(self.matrix) != 'lose': #for x in range(100000): mlist = ["w", "s", "a", "d"] dic = { 0: logic.up(self.matrix)[0], 1: logic.down(self.matrix)[0], 2: logic.left(self.matrix)[0], 3: logic.right(self.matrix)[0] } up = logic.up(self.matrix)[0] down = logic.down(self.matrix)[0] left = logic.left(self.matrix)[0] right = logic.right(self.matrix)[0] actt = [self.sx(up), self.sx(down), self.sx(left), self.sx(right)] max_val = max(actt) maxact = [i for i, x in enumerate(actt) if x == max_val] acttt = [] #time.sleep(1) for maxx in maxact: if logic.game_state(dic[maxx]) != 'lose': acttt.append(maxact.index(maxx)) #max_val = max(act) #actt = [i for i, x in enumerate(act) if x == max_val] if len(acttt) > 0: self.key_down(mlist[random.choice(acttt)]) elif len(actt) == 0: self.key_down(random.choice(mlist)) #time.sleep(.5) if logic.game_state(dic[0]) == 'lose' and logic.game_state( dic[1]) == 'lose' and logic.game_state( dic[2]) == 'lose' and logic.game_state(dic[3]) == 'lose': logic.new_game(4)
def init_matrix(self): box = messagebox.askquestion('Start a new game?', 'Sure?') if box == 'yes': self.matrix = l.new_game(c.GRID_LEN) self.matrix = l.gen(self.matrix) self.matrix = l.gen(self.matrix) else: with open('gamestate.text', 'r', encoding='utf-8') as f: t = f.read() if not t: self.matrix = l.new_game(c.GRID_LEN) self.matrix = l.gen(self.matrix) self.matrix = l.gen(self.matrix) else: self.matrix = json.loads(t)
def main(): for iteration in range(ITERATION): print("Iteration: " + str(iteration + 1)) start = time.time() step = 0 matrix = logic.new_game() matrix = logic.add_two(matrix) while True: matrix = logic.add_two(matrix) if logic.gameOver(matrix): break # print("given this board") # logic.printBoard(matrix) move = ExpectiMax.getMove(matrix, DEPTH) matrix = ExpectiMax.moveGrid(matrix, move) # print("expectimax recommends this move " + str(move)) # print("resulting in this board") # logic.printBoard(matrix) step += 1 print("Step= " + str(step)) print("Max= " + str(2**logic.getMax(matrix))) print("Score= " + str(logic.getScore(matrix))) print('Depth= ' + str(DEPTH)) print('Time= ' + str(time.time() - start)) print('')
def __init__(self): Frame.__init__(self) self.grid() self.master.title('2048 by Efti & Saufi') self.master.bind("<Key>", self.key_down) self.commands = { c.KEY_UP: logic.up, c.KEY_DOWN: logic.down, c.KEY_LEFT: logic.left, c.KEY_RIGHT: logic.right, c.KEY_UP_ALT: logic.up, c.KEY_DOWN_ALT: logic.down, c.KEY_LEFT_ALT: logic.left, c.KEY_RIGHT_ALT: logic.right, c.KEY_H: logic.left, c.KEY_L: logic.right, c.KEY_K: logic.up, c.KEY_J: logic.down } self.grid_cells = [] self.init_grid() self.matrix = logic.new_game(c.GRID_LEN) self.history_matrixs = [] self.update_grid_cells() self.mainloop()
def restart(self): cfg.currentScore = 0 RightView.setCurrentScore(cfg.wrapper.app_gui.right_view, cfg.currentScore) self.matrix = logic.new_game(c.GRID_LEN) self.history_matrixs = [] self.update_grid_cells()
def on_bPlay_clicked(self): self.gridBoard.blockSignals(False) self.init_grid() c.SCORE = 0 self.lScore.setText(str(c.SCORE)) self.matrix = logic.new_game(c.GRID_LEN) self.history_matrixs = [] self.update_grid_cells()
def eval_genome(genome, config): """ This function will be run in threads by ThreadedEvaluator. It takes two arguments (a single genome and the genome class configuration data) and should return one float (that genome's fitness). """ # Initialize game game_matrix = logic.new_game(4) game_matrix = logic.add_two(game_matrix) game_matrix = logic.add_two(game_matrix) # Flatten function flatten = lambda l: [item for sublist in l for item in sublist] net = neat.nn.FeedForwardNetwork.create(genome, config) # Action functions actions = [logic.up, logic.down, logic.left, logic.right] fitness = 0 for i in range(3): while logic.game_state(game_matrix) == 'not over': # Flatten game matrix flat_matrix = flatten(game_matrix) # Predict moves output = net.activate(flat_matrix) # Copy list and sort predictions from lowest to highest sorted_output = sorted(enumerate(output), key=lambda x: x[1]) # Get max index from output list and use assosiated function from actions max_index = sorted_output[-1][0] new_game_matrix = actions[max_index](game_matrix) # If move is not valid use different direction if not new_game_matrix[1]: # Get second max index from output list and use assosiated function from actions second_max_index = sorted_output[-2][0] # TODO if output has same values all directions are not checked new_game_matrix = actions[second_max_index](game_matrix) # If move is not valid use different direction if not new_game_matrix[1]: # Get third max index from output list and use assosiated function from actions third_max_index = sorted_output[-3][0] new_game_matrix = actions[third_max_index](game_matrix) # If move is not valid use different direction if not new_game_matrix[1]: # Get fourth max index from output list and use assosiated function from actions fourth_max_index = sorted_output[-4][0] new_game_matrix = actions[fourth_max_index](game_matrix) # Set game matrix to updated matrix from (game, true) tuple game_matrix = new_game_matrix[0] # Generate new tile if logic.game_state(game_matrix) == 'not over': game_matrix = logic.add_two(game_matrix) #print(game_matrix) # Fitness function is a summation of all values on game board fitness += sum(flatten(game_matrix)) return fitness / 3
def restoreGame(self): self.matrix = self.settings().value("gameState", logic.new_game(c.GRID_LEN)) maxNum = np.max(self.matrix) if logic.winNum < (maxNum): logic.winNum = maxNum * 2 print(logic.winNum) self.update_grid_cells() self.lScore.setText(self.settings().value("score", "0"))
def init_matrix(self): # 매트릭스 리스트 생성, 4를 전달 self.matrix = logic.new_game(c.GRID_LEN) # 히스토리 매트릭스 리스트 생성, 비어있음 self.history_matrixs = list() # 기본 시작 시의 2타일 2개 생성 '''self.matrix[0][3] = 4 self.matrix[2][3] = 4''' self.matrix = logic.create_tile(self.matrix) self.matrix = logic.create_tile(self.matrix)
def init_matrix(self): #TODO: IST DIE 90% 10% Wahrscheinlichkeit einer 4 nicht drinnen oder was? self.matrix = logic.new_game(4) self.history_matrixs = list() self.matrix = logic.add_two(self.matrix) self.matrix = logic.add_two(self.matrix) #TODO: Name anpassen zb. state_ self.matrix_old = self.matrix self.powers_of_two_matrix = np.zeros((4, 4))
def __init__(self, game=None): self.score = 0 self.true_score = 0 self.invalid_moves = 0 self.total_moves = 0 if game is not None: self.matrix = game else: self.matrix = logic.new_game(4) logic.add_two(self.matrix) logic.add_two(self.matrix)
def __init__(self, random = False): self.matrix = logic.new_game(4) self.matrix = logic.add_two(self.matrix) self.matrix = logic.add_two(self.matrix) if(random): self.create_random() self.state = 'not over' self.score = 0
def __init__(self): Frame.__init__(self) self.grid() self.master.title('2048') self.grid_cells = [] self.init_grid() self.matrix = logic.new_game(c.GRID_LEN) self.history_matrixs = [] self.total_score = 0 self.update_grid_cells()
def bNoClicked(self): if self.lWinLoose.text() == "ΚΕΡΔΙΣΑΤΕ ! ! !": logic.winNum = self.defVal print(self.defVal) self.parent.on_bPlay_clicked() self.dialogTypes("HIDE") elif self.lWinLoose.text() == "ΑΠΟΘΗΚΕΥΣΗ": self.parent.settings().setValue("gameState", logic.new_game(c.GRID_LEN)) self.parent.settings().setValue("score", "0") self.dialogTypes("HIDE") else: self.dialogTypes("HIDE")
def __init__(self, env_info=None): if env_info is None: env_info = {} self.action_space = gym.spaces.Discrete(4) self.observation_space = gym.spaces.Box(0, 1, shape=(11, 4, 4), dtype='uint8') self.random = env_info.get("random_movements", False) self.human = env_info.get("human", False) self.matrix = logic.new_game(c.GRID_LEN) self.commands = { '0': logic.up, '1': logic.down, '2': logic.left, '3': logic.right } self.score = 0 self.rew = 0 self.steps = 0
def init_matrix(self): self.matrix = logic.new_game(4) self.history_matrixs = list() self.matrix = logic.add_tile(self.matrix) self.matrix = logic.add_tile(self.matrix)
def __init__(self, parent=None): # Αρχικοποίηση του γραφικού περιβάλλοντος super(Game, self).__init__(parent) print(APP_FOLDER) self.setupUi(self) c.SCORE = self.settings().value("score", 0, type=int) # Μεταβλητές self.points = [] self.speed = 30 self.movie = None self.commands = { c.KEY_UP: logic.up, c.KEY_DOWN: logic.down, c.KEY_LEFT: logic.left, c.KEY_RIGHT: logic.right, c.KEY_UP_ALT: logic.up, c.KEY_DOWN_ALT: logic.down, c.KEY_LEFT_ALT: logic.left, c.KEY_RIGHT_ALT: logic.right, c.KEY_J: logic.left, c.KEY_L: logic.right, c.KEY_I: logic.up, c.KEY_K: logic.down } self.setWindowFlags(QtCore.Qt.CustomizeWindowHint | QtCore.Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground, True) self.center() self.settings() self.restoreStates() self.fontDatabase = QFontDatabase() self.fontDatabase.addApplicationFont( APP_FOLDER + "/resources/fonts/JackportCollegeNcv-1MZe.ttf") self.fontDatabase.addApplicationFont( APP_FOLDER + "/resources/fonts/Rosemary-Bold.ttf") self.lScore.setFont(QFont("JACKPORT COLLEGE NCV", 40)) self.lHiScore.setFont(QFont("JACKPORT COLLEGE NCV", 40)) self.bExit.setFont(QFont("JACKPORT COLLEGE NCV", 32)) self.lMediaSet.setFont(QFont("Rosemary", 38)) swipeCurImg = QPixmap(APP_FOLDER + "/resources/images/swipeCursor.png") handCurImg = QPixmap(APP_FOLDER + "/resources/images/handCursor.png") self.cursors = [handCurImg, swipeCurImg] self.centralwidget.setCursor(QCursor(self.cursors[0], 15, 2)) self.frame.setCursor(QCursor(self.cursors[1], 35, 35)) self.frame.setAttribute(Qt.WA_StyledBackground, (True)) self.animateBackground() self.musIcon() self.sndIcon() self.playMusic() self.init_grid() self.matrix = logic.new_game(c.GRID_LEN) self.history_matrixs = [] self.update_grid_cells() self.restoreGame() # Αντιστοίχιση ενεργειών κίνησης ποντικιού και κλικ self.bHelp.clicked.connect(self.bHelpClicked) self.bAnim.clicked.connect(self.animStartStop) self.sndslider.valueChanged.connect(self.sndslvalchanged) self.musslider.valueChanged.connect(self.musslvalchanged) self.frame.installEventFilter(self)
def init_matrix(self): self.matrix = logic.new_game(c.GRID_LEN) self.history_matrixs = list() self.matrix = logic.add_two(self.matrix) self.matrix = logic.add_two(self.matrix)
def newGame(): game = new_game(GAME_SIZE) game = add_two(game) game = add_two(game) return game
def init_matrix(self): self.matrix = logic.new_game(4) self.last_matrix = list() self.last_generated = list() self.generate_next() self.generate_next()
def key_down(self, event): print("KEY DOWN") with open('winner.pkl', 'rb') as filehandler: local_dir = os.path.dirname(__file__) config_path = os.path.join(local_dir, 'config-feedforward') config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path) winner = pickle.load(filehandler) net = neat.nn.FeedForwardNetwork.create(winner, config) # Initialize game game_matrix = logic.new_game(4) game_matrix = logic.add_two(game_matrix) game_matrix = logic.add_two(game_matrix) self.matrix = game_matrix self.update_grid_cells() # Flatten function flatten = lambda l: [item for sublist in l for item in sublist] # Action functions actions = [logic.up, logic.down, logic.left, logic.right] move_counter = 0 while logic.game_state(game_matrix) == 'not over': move_counter += 1 # Flatten game matrix flat_matrix = flatten(game_matrix) # Predict moves output = net.activate(flat_matrix) # Copy list and sort predictions from lowest to highest sorted_output = sorted(enumerate(output), key=lambda x: x[1]) # Get max index from output list and use assosiated function from actions max_index = sorted_output[-1][0] new_game_matrix = actions[max_index](game_matrix) # If move is not valid use different direction if not new_game_matrix[1]: # Get second max index from output list and use assosiated function from actions second_max_index = sorted_output[-2][0] new_game_matrix = actions[second_max_index](game_matrix) # If move is not valid use different direction if not new_game_matrix[1]: # Get third max index from output list and use assosiated function from actions third_max_index = sorted_output[-3][0] new_game_matrix = actions[third_max_index](game_matrix) # If move is not valid use different direction if not new_game_matrix[1]: # Get fourth max index from output list and use assosiated function from actions fourth_max_index = sorted_output[-4][0] new_game_matrix = actions[fourth_max_index](game_matrix) # Set game matrix to updated matrix from (game, true) tuple game_matrix = new_game_matrix[0] if logic.game_state(game_matrix) == 'not over': game_matrix = logic.add_two(game_matrix) self.matrix = game_matrix self.history_matrixs.append(self.matrix) self.update_grid_cells() # Generate new tile print(f"Number of moves was {move_counter}")
def new_game(self): self.game_matrix = logic.new_game(GRID_LEN) self.game_matrix = logic.add_tile(self.game_matrix) self.game_matrix = logic.add_tile(self.game_matrix) self.print_game()
def init_matrix(self): self.matrix = new_game(GRID_LEN) self.matrix = add_two_or_four(self.matrix) self.matrix = add_two_or_four(self.matrix)
def reset(self): self.matrix = logic.new_game(c.GRID_LEN) self.steps = 0 self.score = 0 self.rew = 0 return self.get_observation()
def init_matrix(self): self.matrix = logic.new_game(4) self.history_matrixs = list() self.matrix = logic.add_two(self.matrix) self.matrix = logic.add_two(self.matrix)
def __init__(self, strtg="1.4.1"): # prepare game 2048 self.commands = { c.KEY_UP: logic.up, c.KEY_DOWN: logic.down, c.KEY_LEFT: logic.left, c.KEY_RIGHT: logic.right } self.grid_cells = [] self.matrix = logic.new_game(c.GRID_LEN) self.history_matrixs = [] self.history_matrixs.append(self.matrix) self.history_matrixs.append(self.matrix) self.score = 0 # prepare game strategy strtg = strtg.split(".") for n, s in enumerate(strtg): strtg[n] = int(s) strtg.append(0) strtg.append(0) self.dir = [] self.dirs = [c.KEY_UP, c.KEY_LEFT, c.KEY_RIGHT, c.KEY_DOWN] self.all_dirs = [c.KEY_UP, c.KEY_LEFT, c.KEY_RIGHT, c.KEY_DOWN] self.history_dir = -1 self.line = 1 # for strategy1 direction-first if strtg[0] == 1: if strtg[1] == 1: # line self.set_dir([c.KEY_UP]) elif strtg[1] == 2: # corner self.set_dir([c.KEY_UP, c.KEY_LEFT]) elif strtg[1] == 4: # serpentine(snakelike) self.set_dir([c.KEY_UP, c.KEY_LEFT]) # play while True: if strtg[0] == 0: d = self.dirs[random.randint(0, len(self.dirs) - 1)] elif strtg[0] == 1: # for strategy1.4 serpentine(snakelike), when change direction if strtg[1] == 4 and self.matrix[0][ c.GRID_LEN - 1] != 0 and self.matrix[0][0] != 0: if strtg[2] == 0 and self.matrix[0][0] == 256: self.set_dir([c.KEY_UP, c.KEY_RIGHT]) if strtg[2] == 1: # main direction if self.matrix[0][c.GRID_LEN - 1] > 8: if self.matrix[0][0] == 128: self.set_dir([c.KEY_UP]) elif self.matrix[0][0] == 256: self.set_dir([c.KEY_UP, c.KEY_RIGHT]) elif self.matrix[0][0] == 512: self.set_dir([c.KEY_UP, c.KEY_RIGHT]) elif self.matrix[0][c.GRID_LEN - 1] < 4: self.set_dir([c.KEY_UP]) # consider more lines if self.matrix[0][0] < 256: self.line = 1 ##else: ##self.line = 2 # disoder for i in range(self.line): for j in range(c.GRID_LEN - 1): if self.matrix[i][j] < self.matrix[i][j + 1]: self.set_dir([c.KEY_UP, c.KEY_LEFT]) if c.KEY_RIGHT in self.dir and self.matrix[0][ c.GRID_LEN - 1] < self.matrix[1][c.GRID_LEN - 1]: self.set_dir([c.KEY_UP]) # triangle same numbers for i in range(c.GRID_LEN - 1): for j in range(c.GRID_LEN - 1): if self.matrix[i][j] == self.matrix[i][ j + 1] and (self.matrix[i][j] == self.matrix[i + 1][j] or self.matrix[i][j] == self.matrix[i + 1][j + 1]): if self.matrix[i][j] == 0: continue print("trangle", i, j) self.double_key_down(c.KEY_LEFT, c.KEY_UP) d = "continue" # for strategy1, when invalid direction d = self.dup() print("1", d, self.dir) if d == "continue": continue if d == "not dup": self.history_dir = -1 d = self.dir[random.randint(0, len(self.dir) - 1)] if d == c.KEY_RIGHT and d in self.dir: m, done, n, g = self.commands[d](self.matrix) if m[0][0] == 0: self.set_dir([c.KEY_UP]) continue elif strtg[0] == 2: d = self.more_merged(strtg[1]) if d == "not dup": d = self.dirs[random.randint(0, len(self.dirs) - 1)] # key down print("2", d) state = self.key_down(d) print(self.matrix) if state != 'not over': break # game over self.record(strtg) return
def new_game(self): self.matrix = logic.new_game(GRID_LEN) self.matrix = logic.add_tile(self.matrix) self.matrix = logic.add_tile(self.matrix)
def matrixInit(self): self.matrix = logic.new_game(4) self.history_matrixs = list() self.matrix = logic.add_two(self.matrix) self.matrix = logic.add_two(self.matrix)