def playAI(numGames, numSteps, model): sum = 0 highScore = 0 i = 1 for _ in range(numGames): game = SnakeGame() for _ in range(numSteps): angle, appleDV_Normalized, snakeDV_Normalized = angleSnakeApple( game.snake.positions, game.apple.position) currentDV, isFrontBlocked, isLeftBlocked, isRightBlocked = blockedDirectionsTrain( game.snake.positions, game.apple.position) X = [ isLeftBlocked, isFrontBlocked, isRightBlocked, appleDV_Normalized[0], snakeDV_Normalized[0], appleDV_Normalized[1], snakeDV_Normalized[1] ] # X = [isLeftBlocked, isFrontBlocked, isRightBlocked, angle] X = np.array(X).reshape(-1, len(X)) predicted_direction = np.argmax(np.array(model.predict(X))) - 1 # print(predicted_direction) updated_direction, button_direction = directionVector( game.snake.positions, angle, predicted_direction) if isBlocked(game.snake.positions, currentDV) == 1: # print(X) # print(predicted_direction) break _, _, _ = game.run_game(buttonDirection=button_direction) print("GAME " + str(i) + " SCORE = " + str(game.score)) sum += game.score i += 1 if (game.score > highScore): highScore = game.score return sum // numGames, highScore
def __init__(self, width: int = 20, height: int = 20, speed: int = 10) -> None: self.WINDOW_SIZE = 640 self.grid_width = width self.grid_height = height self.speed = speed self.screen = pygame.display.set_mode( (self.WINDOW_SIZE, self.WINDOW_SIZE)) self.game = SnakeGame(width, height) self.cell_width = 32
def main(): args = get_args() # Convert the walls from input format into coordinate tuples. walls = set() for i in range(0, len(args.walls) // 2, 2): walls.add((args.walls[i], args.walls[i + 1])) game = SnakeGame(board_size=tuple(args.board_size), walls=walls, random_seed=args.random_seed) GameIO(game=game, speed=args.speed, player_name=args.player_name, score_file=args.score_file)
#delete all frames from the previous training print("removing all frames from previous training") n_files = len([name for name in os.listdir(target_folder)]) cntr = 0 for i in glob.glob(f"{target_folder}/*jpg"): sys.stdout.write('\r') sp = cntr/((n_files-1)/100) tp = int(sp/4) sys.stdout.write("[%-25s] %d%%" % ('='*tp, sp)) #25s=25spaces sys.stdout.flush() os.remove(i) cntr += 1 print("removed") env = SnakeGame() agent = Agent(gamma = 0.99, epsilon = 1.0, batch_size = 64, n_actions = 4,eps_end = 0.01, input_dims = [16], lr = 0.003) scores, eps_history, avg_scores, frames = [] , [] , [] ,[] #frames will not be in use n_games = n_episodes for i in range(n_games): score = 0 step = 0 done = False observation = env.reset() # frames.append(env.animate(i,step,score)) snake_len = len(env.snake) frame = env.animate(i,step,score,snake_len) frame.save(f"{target_folder}/ep{i}step{step}.jpg","jpeg") while not done:
from game import SnakeGame if __name__ == "__main__": snake = SnakeGame() snake.main_loop()
len(mean_scores) + 1), mean_scores, '-o', alpha=0.8) plt.pause(0.1) if __name__ == '__main__': scores = [] mean_scores = [] total_score = 0 maximum_score = 11 screen = UI() game = SnakeGame(screen) screen.set_game(game) model = DQN(11, 256, 3) train = QTrain(model, lr=LR, gamma=GAMMA) model = train.load_checkpoint() agent = Agent(model, train, game) # training loop while True: current_state = agent.get_state() next_action = agent.get_action(current_state) game_over, score, reward = game.play_step(next_action) new_state = agent.get_state() agent.train_over_sample(current_state, next_action, reward, new_state,
""" Famous snake game """ from settings import * from game import SnakeGame if __name__ == "__main__": game = SnakeGame() game.run()
def play(): for i in range(100000): snake = SnakeGame()
def main(stdscr): """Entry point""" SnakeGame(stdscr).start()
self.sh = int(self.sh / 2) self.sw = int(self.sw / 2) self.drawer = curses.newwin(self.sh + 1, self.sw + 1, 0, 0) self.drawer.keypad(1) def start(self): self.game.init(self.sw, self.sh) self.drawer.timeout(100) self.run() def run(self): key = curses.KEY_RIGHT while True: next_key = self.drawer.getch() key = key if next_key == -1 else next_key self.game.move(key) if self.game.get_state(): self.game.draw() else: curses.endwin() quit() driver = Driver() driver.game = SnakeGame(driver.drawer) driver.game.food_len = 5 driver.game.number_of_snakes = 1 driver.start()
import pygame window_dimensions = (500, 500) pixel_mult = 6 pygame.init() screen = pygame.display.set_mode(window_dimensions) done = False clock = pygame.time.Clock() snake_color = (0, 250, 0) apple_color = (250, 0, 0) game = SnakeGame( (window_dimensions[0] / pixel_mult, window_dimensions[1] / pixel_mult)) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pressed = pygame.key.get_pressed() if pressed[pygame.K_q]: done = True if pressed[pygame.K_x]: game.cheat_eat_apple() heading = None
from game import SnakeGame GRID_SIZE = 20 game = SnakeGame.SnakeGame(GRID_SIZE) game.initialize() game.run()
if g.tick(): time.sleep(1 / ((int(g.score / 10 + 1)) * 10)) else: self.running = False def start_loop(self): t = threading.Thread(target=self._loop, args=(), daemon=True) t.start() return t if __name__ == '__main__': size = [800, 600] screen = pygame.display.set_mode(size) g = SnakeGame(size[1] // 10, size[0] // 10) rrunning = True while rrunning: g.initialize() g.place_food() game_surf = pygame.Surface(size) font = pygame.font.SysFont('roboto', 16) gt = BoardLogic(g) gt.start_loop() running = True while running: if not gt.running: running = False