def on_init(self): pygame.init() #Initiating pygame random.seed(a=None) #Possibility for random ints self._display_surf = pygame.display.set_mode(self.size) #Making screen surface pygame.display.set_caption("Snake Spel, av Aksel") #Window caption self._display_surf.fill(BACK_COLOR) # Filling the screen with color self.snake = Snake() # Making the snake self.speed = 150 # Speed of snake pygame.font.init() #Initiating possibility for text in pygame self.dir = "down" #This is the start position and is updated in game self.new_dir = None #A temporary direction used in on_event() self.difficulty = 2 #The difficulty sets startingspeed (and maybe snake size) self.points = len(self.snake.skeleton)-3 # The points are defined by size of snake #Making the points-text pygame.display.update() self.points_text,self.points_text_rect = self.text_format("Poeng: " + str(self.points), None, 30, JOINT_COLOR, BOARD_LENGTH/2*JOINT_LENGTH, JOINT_LENGTH) self._display_surf.blit(self.points_text, self.points_text_rect) # Making the first fruit on random position self.rand_x = random.randint(1,BOARD_LENGTH-1) self.rand_y = random.randint(1,BOARD_LENGTH-1) self.fruit = Joint(self.rand_x, self.rand_y)
def main(): width = 250 # width and height because of square game score = 0 pg.init() sound = pg.mixer.Sound('biteSound.wav') window = pg.display.set_mode((width, width)) # Set window size pg.display.set_caption("Snake") # Window Caption s = sn.Snake() a = sn.Box((0, 255, 0)) # initiate apple a.apple() # randomize the apple keys = pg.key.get_pressed() # set default key pres playing = True # bool to keep game running clock = pg.time.Clock() # controll fps while playing: pg.time.delay(100) # delay move by 100/1000 of a second clock.tick(10) # keeps it at 10fps for event in pg.event.get(): if event.type == pg.QUIT: # if user quits pg.quit() if event.type == pg.KEYDOWN: # if the user presses a key keys = pg.key.get_pressed() # set the key s.updateDir(keys, score) # update direction s.updatePos() # update the currentX and CurrentY based on direction s.newHead() # insert the new head if eat(s, a) == False: # check is snake is eating the apple s.deleteTail() # if it did not eat delete the tail else: pg.mixer.Sound.play(sound) score += 1 a.apple() # else rerandomize the apple refillAndUpdate(s, a, window) # replace and reprint game scrren playing = checkColisions(s) # check for collisions print("Your score is: {}".format(score))
def __init__(self, master=None, *args, **kwargs): tk.Frame.__init__(self, master) self.master = master self.grid = Grid(master=master, *args, **kwargs) self.snake = Snake(self.grid) self.bind_all("<KeyRelease>", self.key_release) self.snake.display()
def prepare_replay(self): try: self.scoreboard.setText("") with open("config.json", "r") as f: self.config = json.load(f) output = [] for k in self.config: output.append([k, self.config[k]]) output = [item for sublist in output for item in sublist] self.config_info.setText("".join(output)) tree = ET.parse("replay.xml") root = tree.getroot() game_history = [] rounds = [] for turn in root: for cells in turn: for row in cells: if cells.attrib["indexes"] == "19" and row.attrib[ "indexes"] == "77": game_history.append(row.text) copy_history = deepcopy(game_history) rounds.append(copy_history) game_history.clear() else: game_history.append(row.text) for round in rounds: round = np.reshape(round, (20, 78)) self.game.map = round Snake.get_hex(self.hex, self.game) self.initialize_map() self.update_map() myApp.processEvents() time.sleep(0.5) except: self.config_info.setText("Failed to load a replay!")
def SpawnSnakes(self, brains=None, firstSpawn=0): # Create snakes if brains == None: # first spawn for region in random.sample(self.world.regions, numberOfSnakes + self.isHumanPlayer): inNodes = numberOfBeams + numberOfFoodSenses + numberOfSnakeSenses * 2 + 1 outNodes = 2 brain = Genome(inNodes, outNodes) brain.FullyConnect(self.population.innovations) tempSnake = Snake(self, region.position[0] + region.position[2] / 2, region.position[1] + region.position[3] / 2, brain) self.snakes.append(tempSnake) self.snakeHistory.append(tempSnake) if self.isHumanPlayer: self.snakeHistory.pop(0) else: i = 0 for region in random.sample(self.world.regions, numberOfSnakes + firstSpawn): tempSnake = Snake(self, region.position[0] + region.position[2] / 2, region.position[1] + region.position[3] / 2, brains[i]) self.snakes.append(tempSnake) self.snakeHistory.append(tempSnake) i += 1
def interact(game): snake = getSnake(game) food = getFood(game) win = getWin(game) score = getScore(game) name = getName(game) key = win.getch() difficulty = game['difficulty'] win.timeout(200 - 30 * difficulty) # a ameliorer if key == 32: pause(win) try: newSnake = Snake.computeNextPos(key, snake, food, win) game = setSnake(newSnake, game) except ValueError: game = setHighScores(HighScores.log(score, name, difficulty), game) game = resetScore(game) game = setSnake(Snake.reset(), game) game = setState('menu', game) food = None if foodEaten(snake, food): game = setNewFood(game) game = addScore(1, game) return
def manual_action(snake: Snake, event: event) -> Action: """ A function that determines the action to be taken by the player's snake based on the button presses detected by the event variable :param snake: A reference to the user's snake :param event: Some kind of game event such as a button press. Used to identify if a button was pressed :return: Returns the action to be taken """ if snake.alive: # user's snake keys = pygame.key.get_pressed() # get the button press if snake.joints == []: # default action: keep snake moving forward defaultaction = snake.findDirection(snake.head, snake.end) else: defaultaction = snake.findDirection(snake.head, snake.joints[0]) action_taken = defaultaction user_permissible_actions = snake.permissible_actions() if event.type == pygame.KEYDOWN: # if a button was pressed, change the action to be taken if keys[pygame. K_RIGHT] and Action.RIGHT in user_permissible_actions: action_taken = Action.RIGHT elif keys[ pygame.K_LEFT] and Action.LEFT in user_permissible_actions: action_taken = Action.LEFT elif keys[pygame.K_UP] and Action.TOP in user_permissible_actions: action_taken = Action.TOP elif keys[ pygame.K_DOWN] and Action.DOWN in user_permissible_actions: action_taken = Action.DOWN else: action_taken = None # if the snake is dead, no action is taken return action_taken
class World: RED = 255, 0, 0 GREEN = 0, 255, 0 def __init__(self, loc, width, height): self.loc = loc # Location and size of the world self.width = width # Width of grid in cells self.height = height # Height of grid in cells self.cellWidth = 0 # Width of individual cell self.cellHeight = 0 # Height of individual cell self.updateSize() self.snake = Snake(self, World.RED, 1, 0, 0) self.blocks = [[None for x in range(width)] for y in range(height)] self.newFood() self.particles = [] def updateSize(self): self.cellWidth = round(self.loc.width / self.width) self.cellHeight = round(self.loc.height / self.height) def update(self): self.snake.update() def newFood(self): x = y = -1 while x < 0 or y < 0 or self.getBlock(x, y): x = randint(0, self.width - 1) y = randint(0, self.height - 1) self.setBlock(x, y, Food(self, World.GREEN)) def spawnParticles(self, n, gridX, gridY): for i in range(n): col = randint(0, 255), randint(0, 255), randint(0, 255) size = randint(1, 3) speed = random() * 4.0 + 1.0 angle = random() * 2.0 * pi self.particles.append(Particle([gridX * self.cellWidth + self.cellWidth // 2 + self.loc.x, gridY * self.cellHeight + self.cellHeight // 2 + self.loc.y], size, [speed * cos(angle), speed * sin(angle)], col)) def draw(self, surface): for y, row in enumerate(self.blocks): for x, block in enumerate(row): if block: drawRect = pygame.Rect(self.loc.x + x * self.cellWidth, self.loc.y + y * self.cellHeight, self.cellWidth, self.cellHeight) block.draw(surface, drawRect) # self.snake.draw(surface) def setBlock(self, x, y, block): self.blocks[y][x] = block; if block: block.x = x block.y = y def getBlock(self, x, y): return self.blocks[y][x]
def _answer(self, inp): words = [ re.sub('[%s]' % re.escape(string.punctuation), '', stemmer.stem(w.lower())) for w in nltk.word_tokenize(inp) ] input_array = [0 for _ in range(len(self.words))] for word in words: if self.words.count(word) > 0: input_array[self.words.index(word)] = 1 output = self.model.predict_proba([input_array]) #print(output) index = np.argmax(output[0]) if output[0][index] > 0.8: print("Bot: ", random.choice(self.responses[index])) if self.tags[index] == "Quit": return True if self.tags[index] == "Time": gettimenow() return False if self.tags[index] == "Weather": getweathertoday() return False if self.tags[index] == "Highway Rider": HighwayRider.main() return False if self.tags[index] == "Snake": Snake.main() return False if self.tags[index] == "Space Invaders": SpaceInvaders.main() return False if self.tags[index] == "Read Email": username = input("Enter your username: "******"Enter your password: "******"Word": os.startfile( r'C:\Program Files (x86)\Microsoft Office\root\Office16\WinWord.exe' ) return False if self.tags[index] == "Excel": os.startfile( r'C:\Program Files (x86)\Microsoft Office\root\Office16\Excel.exe' ) return False if self.tags[index] == "Powerpoint": os.startfile( r'C:\Program Files (x86)\Microsoft Office\root\Office16\POWERPNT.exe' ) return False if self.tags[index] == "Outlook": os.startfile( r'C:\Program Files (x86)\Microsoft Office\root\Office16\Outlook.exe' ) return False else: print("Bot: I don't understand") return False
def addSnake(self, snake_id, name, cell, direction): # add record of snake new_snake = Snake(cell=cell, direction=direction, name=name) self.id_snakes[snake_id] = new_snake # add snake to board if new_snake.isVulnerable(): for c in new_snake.getCells(): self.board.at(c, snake_id)
def start(): data = bottle.request.json Snake.__init__(data) return { 'taunt': 'battlesnake-python!' }
def foodEaten(snake, food): if food is None: return True if food[0] == Snake.getHeadX(snake) and food[1] == Snake.getHeadY(snake): logging.info('some food has been eaten') return True else: return False
def run_manual(): game_size = 50 dot_size = 10 delay = .1 distance_penalty = -1.5 food_reward = 10 snake = Snake(game_size, dot_size, delay, distance_penalty, food_reward) snake.run_snake() print("Score: " + str(snake.score))
def play(game_size=(30, 20), difficulty="medium"): difficulties = {"easy": 80, "medium": 70, "hard": 60, "insane": 40} test_snake = Snake(5, np.array([4, 0]), np.array([1, 0])) test_game = GameManager(game_size, test_snake) img = test_game.getFrame() cv2.imshow("SnakeGame", img) cv2.waitKey(0) while True: img = test_game.getFrame() cv2.imshow("SnakeGame", img) key = cv2.waitKey(difficulties[difficulty]) & 0xFF if key == 119 or key == 82: test_snake.onUpButtonPress() if key == 97 or key == 81: test_snake.onLeftButtonPress() if key == 115 or key == 84: test_snake.onDownButtonPress() if key == 100 or key == 83: test_snake.onRightButtonPress() if key == 27: break if test_game.snakeColiding(): break test_game.onFrameUpdate() cv2.destroyAllWindows() game_over = img font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText( game_over, 'Game Over', (int(game_over.shape[1] / 2) - 90, int(game_over.shape[0] / 2)), font, 1, (0, 0, 255), 2) cv2.putText(game_over, 'Score: ' + str(test_game.snake.length * 10), ((int(game_over.shape[1] / 2) - 88, int(game_over.shape[0] / 2) + 20)), font, .5, (0, 0, 255), 1) while True: cv2.imshow("Game Over", game_over) key = cv2.waitKey(1) & 0xFF if key == 27: break cv2.destroyAllWindows()
def died(): """ This happens if snake dies. """ Variables.is_dead = True Snake.Snake().direction = Variables.PAUSE Variables.points = Snake.Snake().points Variables.high_score.append(Variables.points) Variables.high_score = sorted(Variables.high_score, reverse=True)
def __init__(self): pygame.init() self.S = Snake() self.F = Food() # self.M = Menu() self.CLOCK = pygame.time.Clock() self.reset()
def test_remove(self) : for i in removeIndexes : x = Snake() if i>len(x.points) : self.assertRaises(IndexError,x.remove(i)) elif i<0 : self.assertRaises(IndexError,x.remove(i)) else : x.remove(i) self.assertEquals(i+1,len(x.points))
def tournament_refresh_check(self): while True: if self.tournament_refresh: self.tournament_refresh = False time.sleep(5) self.tournamentGame = self.tournamentGame + 1 self.setStyleSheet("background-color: rgba(255, 255, 255, 0)") self.winner = 0 # snakes self.snakes = [] self.scores = [0, 0, 0, 0] # kad se opkoli,za pozicije nove zmije self.new_snake = [] self.surpriseOn = False self.effectOn = False for position_number in range(4): self.new_snake.append([[3, 2 + 2 * position_number], [2, 2 + 2 * position_number]]) self.new_snake.append([[3, 37 - 2 * position_number], [2, 37 - 2 * position_number]]) self.new_snake.append([[56, 2 + 2 * position_number], [57, 2 + 2 * position_number]]) self.new_snake.append([[56, 37 - 2 * position_number], [57, 37 - 2 * position_number]]) self.all_pos = [] for position_number in range(4): self.all_pos.append([3, 2 + 2 * position_number]) self.all_pos.append([2, 2 + 2 * position_number]) self.all_pos.append([3, 37 - 2 * position_number]) self.all_pos.append([2, 37 - 2 * position_number]) self.all_pos.append([56, 2 + 2 * position_number]) self.all_pos.append([57, 2 + 2 * position_number]) self.all_pos.append([56, 37 - 2 * position_number]) self.all_pos.append([57, 37 - 2 * position_number]) # set Snakes for i in range(1): for j in range(self.NumPlayers): if j == 0: self.snakes.append( Snake.Snake([[3, 2 + 2 * i], [2, 2 + 2 * i]], 2, Board.WIDTHINBLOCKS, Board.HEIGHTINBLOCKS, j)) if j == 1: self.snakes.append( Snake.Snake([[3, 37 - 2 * i], [2, 37 - 2 * i]], 2, Board.WIDTHINBLOCKS, Board.HEIGHTINBLOCKS, j)) for i in range(self.NumPlayers): self.scores[i] = 0 self.TurnCounter = 0 self.turns = 0 self.GAME_OVER = False self.intervalTimer = IntervalTimer(20, self.timeout, self.msg2statusbar, self.NumPlayers, self.scores) self.intervalTimer.start()
def initAI(self): """ Initialize game with AI enemy """ if not self.done: for s in self.snake: if s.inGame: s.destroy(self.board) self.board.makeMap() self.board.makeApple() self.snake = [Snake(self.board, 1), Snake(self.board, 2)] self.runAI()
def init2P(self): """ Initialize 2 player game """ if not self.done: for s in self.snake: if s.inGame: s.destroy(self.board) self.board.makeMap() self.board.makeApple() self.snake = [Snake(self.board, 1), Snake(self.board, 2)] self.run(True)
def setup(self): self.scoreText=self.font_big.render("SCORE : 0",True,pygame.Color(0,255,0)) self.snake_head=Snake.Snake(150,150) self.snake_head.image.fill(pygame.Color(0,0,255)) self.spritesList.add(self.snake_head) for i in range(1,3): segment=Snake.Snake(150,150+i*10) self.snake_segs.append(segment) self.spritesList.add(segment) self.food=Food.Food() self.score=0
def show(game): win = getWin(game) food = getFood(game) level = getLevel(game) snake = getSnake(game) score = getScore(game) win.erase() Level.show(level, win) Snake.show(snake, win) showFood(food, win) showScore(score, win) return
def __init__(self): pygame.init() self.width = 500 self.height = 500 self.clock = pygame.time.Clock() pygame.display.set_caption("Snake") pygame.display.set_icon(pygame.image.load('images\icon.png')) self.font = pygame.font.SysFont('Comic Sans MS', 20) self.screen = pygame.display.set_mode([self.width, self.height]) self.snake = Snake(self.width, self.height) self.food = Food(self.width, self.height) self.fail_sounds = self.GetOggFiles("sounds\\fail")
def epoch(self, old_population): random.shuffle(old_population) competitors = old_population[0:int(TOURNAMENT_PERCENT * POP_SIZE)] old_population.sort() winners = [] losers = [] for i in range(0, len(competitors), 2): if competitors[i].get_fitness() > competitors[i + 1].get_fitness(): winners.append(competitors[i]) losers.append(competitors[i + 1]) else: winners.append(competitors[i + 1]) losers.append(competitors[i]) for i in tqdm(range(len(winners)), ascii=True, desc="BREEDING", leave=False): temp = self.crossover(winners[i], random.choice(winners)) if temp.get_fitness() > losers[i].get_fitness(): old_population[0] = temp old_population.sort() temp = self.mutate(winners[i]) if temp.get_fitness() > winners[i].get_fitness(): if winners[i] in old_population: index = old_population.index(winners[i]) old_population[index] = temp old_population.sort() self.total_fitness = 0 # Reset old total fitness # Identify current most fit individual and perform fitness calculations for genome in old_population: self.total_fitness += genome.get_fitness() if self.best_genome is None or genome.get_fitness( ) > self.best_genome.get_fitness(): fitness = genome.get_fitness() self.best_genome = genome.copy() self.best_genome.fitness = fitness if (SHOW_NEW_BEST): Snake.vectorFitness(self.best_genome, 0) displayGenome = self.best_genome.copy() Snake.vectorFitness(displayGenome, 0) # Record fitness value parameters self.avg_fitness = self.total_fitness / len(old_population) self.best_fitness = self.best_genome.get_fitness() return old_population
class Game(tk.Frame): def __init__(self, master=None, *args, **kwargs): tk.Frame.__init__(self, master) self.master = master self.grid = Grid(master=master, *args, **kwargs) self.snake = Snake(self.grid) self.bind_all("<KeyRelease>", self.key_release) self.snake.display() def run(self): if not self.snake.status[0] == 'stop': self.snake.move() if self.snake.gameover == True: #message = tkMessageBox.showinfo("Game Over", "your score: %d" % self.snake.score) # if message == 'ok': tk.sys.exit() self.after(self.snake.speed, self.run) def key_release(self, event): key = event.keysym key_dict = { "Up": "Down", "Down": "Up", "Left": "Right", "Right": "Left" } if key_dict.__contains__( key) and not key == key_dict[self.snake.direction]: self.snake.change_direction(key) self.snake.move() elif key == 'p': self.snake.status.reverse()
def game_loop(self): p1_can_play, p2_can_play = True, True client_1 = self.clients[0][1] client_2 = self.clients[1][1] if len(keys_2) > 0 and len(keys_1) > 0: while True: time.sleep(0.25) # pickle map and send it to the clients for i in self.clients: time.sleep(0.25) msg = [self.game_env.map, self.points1, self.points2] i[0].send(pickle.dumps(msg)) if p1_can_play: p1_can_play, spawn_f1 = Snake.move(self.game_env, animal1, keys_1[-1], self.hex) if p2_can_play: p2_can_play, spawn_f2 = Snake.move(self.game_env, animal2, keys_2[-1], self.hex) if spawn_f1 is not True: self.points1 = self.points1 + 10 self.spawn_fruit = False if self.spawn_fruit is False: while self.spawn_fruit is False: z = np.random.randint(0, len(self.hex)) self.spawn_fruit, _ = Snake.check_space(self.game_env.map, self.hex[z], 1, [0, 0, "#", "+"], 0) _ = fruit(self.hex[z], self.game_env.map, "@") elif spawn_f2 is not True: self.points2 = self.points2 + 10 self.spawn_fruit = False if self.spawn_fruit is False: while self.spawn_fruit is False: z = np.random.randint(0, len(self.hex)) self.spawn_fruit, _ = Snake.check_space(self.game_env.map, self.hex[z], 1, [0, 0, "#", "+"], 0) _ = fruit(self.hex[z], self.game_env.map, "@") # if all players cant play, send final message and break connection with clients if p1_can_play is False and p2_can_play is False: msg = ["end", str(client_1), str(client_2)] for i in self.clients: i[0].send(pickle.dumps(msg)) for i in self.clients: self.clients.remove(i) self.end_game = True if len(self.clients) > 2: break
def __init__(self, cellNumber): self.gameFont = pygame.font.Font('Font/PoetsenOne-Regular.ttf', 25) self.gameFontLarge = pygame.font.Font('Font/PoetsenOne-Regular.ttf', 120) self.gameFontMedium = pygame.font.Font('Font/PoetsenOne-Regular.ttf', 60) self.gameFontSmall = pygame.font.Font('Font/PoetsenOne-Regular.ttf', 25) self.apple = pygame.image.load('Graphics/apple.png').convert_alpha() self.cellNumber = cellNumber self.snake = Snake(False) self.snakeAI = Snake(True) self.fruit = Fruit(cellNumber) self.isGameOver = False
def PlayAutonomous(self, model, weights): logging.info("Starting autonomous play.") try: json_file = open(model, 'r') loaded_json_model = json_file.read() model = model_from_json(loaded_json_model) model.load_weights(weights) except Exception as e: print("Failed to load model.") logging.error("Failed to load model.") logging.error(repr(e)) return o_GenData = GenerateTrainingData() o_Game = Snake() training_data_y = [] # oGame.ResetGame() snake_pos = o_Game.snake_pos apple_pos = o_Game.apple_pos # distance = self.DistanceToApple(snake_pos, apple_pos) for step in range(200000): angle, normVector_apple, normVector_snake = o_GenData.angle_with_apple( snake_pos, apple_pos) isLeftBlocked, isFrontBlocked, isRightBlocked = o_GenData.GetBlockedPath( snake_pos) # button = o_GenData.GenerateRandomDirection(angle, snake_pos) # training_data_y, button = o_GenData.GenerateOutput([isLeftBlocked, isFrontBlocked, isRightBlocked, button, angle, snake_pos], training_data_y) predicted_direction = np.argmax(np.array(model.predict(np.array([isLeftBlocked, isFrontBlocked,\ isRightBlocked, normVector_apple[0], normVector_apple[1], normVector_snake[0], normVector_snake[1]])\ .reshape(-1, 7)))) new_direction = np.array(snake_pos[0]) - np.array(snake_pos[1]) if predicted_direction == 0: #Left new_direction = np.array([new_direction[1], -new_direction[0]]) elif predicted_direction == 1: # Continue new_direction = np.array(snake_pos[0]) - np.array(snake_pos[1]) elif predicted_direction == 2: # Right new_direction = np.array([-new_direction[1], new_direction[0]]) button = o_GenData.GenerateNextButton(new_direction) isBlocked = o_GenData.isNextBlocked(snake_pos, new_direction) if isBlocked: break snake_pos, apple_pos, _ = o_Game.TrainGame(button)
def loadPopulation(self, filename): """ Načíta populáciu hadov """ readsnakes = [] csv_file = open(filename, 'r') csv_reader = csv.reader(csv_file) line_count = 0 for row in csv_reader: line_count += 1 # Každý riadok reprezentuje hadov mozog if line_count % 2 == 1: tempsnake = Snake.snake() tempbrain = self.createNeural(row) tempsnake.brain = copy.deepcopy(tempbrain) readsnakes.append(tempsnake) del tempsnake del tempbrain del self.snakes self.snakes = copy.deepcopy(readsnakes) self.size = len(self.snakes)
def game_over_event_handeling(): global game_state, direction, snake, snake_list, x, y, apfel, apfel_x, apfel_y for event in pygame.event.get(): if event.type == QUIT: sys.exit() elif event.type == KEYDOWN: if event.key == K_SPACE: del snake snake_list = [[snake_x, snake_y], [snake_x - snake_width, snake_y], [snake_x - snake_width * 2, snake_y]] snake = Snake(snake_list, snake_width, snake_height, snake_color, snake_length) x = snake_list[-1][0] y = snake_list[-1][1] del apfel apfel_x, apfel_y = apfel_coords_generator( round(random.randint(0, 730) / 15) * 15, round(random.randint(0, 730) / 15) * 15) apfel = Apfel(apfel_x, apfel_y, apfel_width, apfel_height, apfel_color) direction = 2 game_state = 'start' elif event.key == K_ESCAPE: quit()
def move(): data = bottle.request.json return { 'move': Snake.move(data), 'taunt': 'battlesnake-python !' }
def main(): gui = GuiLogic.GuiLogic() snake = Snake.Snake(10, 10) snake.dir((-1, 0)) update_snake_time = 0 food = (randint(0, 15), randint(0, 15)) while not (gui.alive()): gui.eventHandler(snake) if (snake.eat(food)): food = (randint(0, 15), randint(0, 15)) dt = gui.CLOCK.tick(15) # Limit to 60 frames per second update_snake_time += dt # Calculate millis seconds passed since last loop if update_snake_time > 330: snake.update() update_snake_time = 0 currentSnake = snake.full() gui.draw(currentSnake, food) gui.update() # Call gui update gui.quit()
def __init__(self): # try: address = sys.argv[1] port = int(sys.argv[2]) self.event = KEY_RIGHT self.dir = "right" self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((address, port)) self.rdata = json.loads(str(self.sock.recv(2048))) self.id = self.rdata["id"] self.data = self.rdata["data"] self.totalSnakes = len(self.data["snakes"]) curses.initscr() self.score = 0 self.window = curses.newwin(HEIGHT, WIDTH, 0, 0) self.window.timeout(TIMEOUT) self.window.keypad(1) curses.noecho() curses.curs_set(0) self.window.border(0) self.snakes = [] for i in range(0, self.totalSnakes): self.snakes.append(Snake.Snake(self.window, self.data["snakes"][i])) self.food = Food.Food(self.window, self.data["food"][0], self.data["food"][1])
def __init__(self): try: address = sys.argv[1] port = int(sys.argv[2]) self.event = KEY_RIGHT self.dir = "right" self.totalSnakes = int(sys.argv[3]) self.connections = [] self.addresses = [] self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.bind((address, port)) self.sock.listen(1) self.snakes = [] self.data = { "win": 0, "dead": [], "snakes": [], "food": [], "scores": [], } for i in range(0, self.totalSnakes): self.snakes.append(Snake.Snake(i + i)) self.data["scores"].append(0) self.data["dead"].append(False) self.data["snakes"].append(self.snakes[i].getBody()) self.food = Food.Food() self.data["food"] = self.food.getCor() except Exception as e: print(e) self.sock.close() exit()
def __init__(self, loc, width, height): self.loc = loc # Location and size of the world self.width = width # Width of grid in cells self.height = height # Height of grid in cells self.cellWidth = 0 # Width of individual cell self.cellHeight = 0 # Height of individual cell self.updateSize() self.snake = Snake(self, World.RED, 1, 0, 0) self.blocks = [[None for x in range(width)] for y in range(height)] self.newFood() self.particles = []
def decode(self, encoded): self.board = Board(src=encoded["board"]) self.id_snakes = { sid: Snake(src=s) for sid, s in encoded["snakes"].items() } self.foods = {fcell: Food(fcell) for fcell in encoded["foods"]}
def test_snake_move(): size_x = 20 size_y = 20 lenght = 4 testmap = Map.Map_obj(size_x, size_y) mockparams = unittest.mock.MagicMock() testsnake = Snake.Snake(testmap, mockparams) mockparams = unittest.mock.MagicMock() testsnake.parameters_object.direction = "w" testsnake.move() assert testsnake.move_y == (size_y / 2) - 1 assert testsnake.del_y == (size_y / 2) + lenght - 1 testsnake.parameters_object.direction = "a" testsnake.move() assert testsnake.move_y == (size_y / 2) - 1 assert testsnake.move_x == (size_x / 2) - 1 assert testsnake.del_y == (size_y / 2) + lenght - 1 assert testsnake.del_x == (size_x / 2) - 1 testsnake.move() testsnake.parameters_object.direction = "s" testsnake.move() assert testsnake.move_y == (size_y / 2) assert testsnake.move_x == (size_x / 2) - 2 assert testsnake.del_y == (size_y / 2) + lenght assert testsnake.del_x == (size_x / 2) - 2 testsnake.parameters_object.direction = "d" testsnake.move() assert testsnake.move_y == (size_y / 2) assert testsnake.move_x == (size_x / 2) - 1 assert testsnake.del_y == (size_y / 2) + lenght assert testsnake.del_x == (size_x / 2) - 1
def init(): # on initialise la fenetre curses curses.initscr() win = curses.newwin(30, 80, 0, 0) curses.noecho() curses.curs_set(0) win.nodelay(1) logging.basicConfig(filename='snake.log', level=logging.INFO) # creation du niveau level = Level.create(1, 'levels.txt') # creation du snake snake = Snake.create(35, 15, 1, 2) # creation du food food = None # creation du menu menu = Menu.create( 'Change name', 'Change difficulty', 'Select level', 'Show HighScores', 'Play', 'Quit game' ) # definition de l'etat du programme state = 'menu' # definition du nom du joueur name = 'player1' # definition de la difficulte difficulty = 2 score = -1 HighScoreTable = HighScores.get() # creation de la variable de type game game = Game.create( menu, level, snake, food, win, state, name, difficulty, score, HighScoreTable ) return game
def __init__(self ,x,y,d,l,map,draw_area,query): self.draw_area = draw_area self.food_list = [] self.obst_list = [] self.snake = Snake(draw_area, x, y, d, l) self.add_to_obstacles(self.snake) self.x = x self.y = y self.d = d self.l = l self.score = 0 self.map = map self.query = query self.transistor = 2 self.counter = 0 self.trigger = 1
def __init__(self): """ Constructor method for PlayMap Transition: initialized into new game state input:none output:none """ self.height = 500 self.width = 550 self.snake = Snake() # starting coord of snake self.food = Food() self.powerUp = PowerUp() self.powerUpStatus = True self.gameStatsBar = pygame.Rect(0,0,550,20) self.powerUpIndicator = pygame.Rect(10,0,10,10) self.score = len(self.snake.points) self.diff = 0
def setUp(self) : global sConstructor global grownSnakes global changeDirVars global removeIndexes global grownSnakes sConstructor = Snake() changeDirVars = [-1,1,-2,2] ## UP = Snake() UP.changeDir(2) UP.move() UP.changeDir(1) DOWN = Snake() RIGHT = Snake() RIGHT.changeDir(2) LEFT = Snake() LEFT.changeDir(-2) directionSnakes = [DOWN,UP,LEFT,RIGHT] ## grownSnakes = [] for i in range(4) : directionSnakes[i].grow() grownSnakes.insert(i,directionSnakes[i]) removeIndexes = [30,5,10,15,-2] pass
unpause_text.set_colorkey(BLACK) game_over_text = pygame.image.load("assets/game_over.png").convert() pygame.display.set_caption("Snake!") # Loop until the user clicks the close button. done = False # start the game paused. paused = True first_time = True lost = False # Used to manage how fast the screen updates clock = pygame.time.Clock() snake = Snake(MAX_ROWS, MAX_COLS, GREEN, BOUNDARY_OFFSET, RECT_SIZE, DEFAULT_DIR) apple = Block(random.randrange(MAX_ROWS), random.randrange(MAX_COLS), RED, BOUNDARY_OFFSET, RECT_SIZE, DEFAULT_DIR) # -------- Main Program Loop ----------- while not done: # need to keep track if we've processed a key or not # lest the snake can enter inside itself with quick presses pressedArrowKey = False # --- Main event loop for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop if event.type == pygame.KEYDOWN and not pressedArrowKey: head = snake.parts[0] if event.key == pygame.K_UP and snake.parts[0].direction != "DOWN": head.direction = "UP" pressedArrowKey = True
class Player: def __init__(self ,x,y,d,l,map,draw_area,query): self.draw_area = draw_area self.food_list = [] self.obst_list = [] self.snake = Snake(draw_area, x, y, d, l) self.add_to_obstacles(self.snake) self.x = x self.y = y self.d = d self.l = l self.score = 0 self.map = map self.query = query self.transistor = 2 self.counter = 0 self.trigger = 1 #takes a list of keys #return newest revelant key as a direction def key_decode(self,keys): for key in reversed(keys): if key in self.map: return self.map[key] return "" def add_to_food(self,munchies): self.food_list.append(munchies) def add_to_obstacles(self,obst): self.obst_list.append(obst) def reset_snake(self): xposition = randrange(self.l ,self.draw_area.width -self.l) yposition = randrange(self.l ,self.draw_area.height -self.l) self.snake.reset(xposition,yposition , randrange(1,5), self.l) self.transistor = 0 self.score -= 1 def collision_detection(self): for snack in self.food_list: if self.snake.has_hit(snack): snack.teleport() self.snake.growth = True self.score += 1 for barrier in self.obst_list: if self.snake.has_hit(barrier): self.reset_snake() def draw(self): if self.transistor != 0: self.snake.draw() score_str = self.get_score_str() if self.query == True: self.draw_area.draw_str(1, self.draw_area.height -1, score_str) if self.query == False: self.draw_area.draw_str(self.draw_area.width -len(score_str) -1, self.draw_area.height -1, score_str) def get_score_str(self): if self.query == True: score_str = " Left Player = %i " % (self.score) if self.query == False: score_str = " Right Player = %i " % (self.score) if self.transistor == 0: blank_str = "" for x in range(len(score_str)): blank_str += " " score_str = blank_str return score_str def player_functions(self): self.trigger = 1 if self.transistor == 2: self.snake.move() self.collision_detection() self.draw() if self.transistor != 2: self.counter = self.counter + 1 if self.transistor == 0: self.draw() self.trigger = 0 self.transistor = 1 if self.trigger == 1: if self.transistor == 1: self.draw() self.transistor = 0 if self.counter == 10: self.counter = 0 self.transistor = 2
def GameLoop(screen,fpsSet): ## returns score ## screen size score = 0 # sets Snake and food size in constructor to be able to change it in Settings running = True # game running flag size = Settings.surfaceSize screen = pygame.display.set_mode(size,pygame.RESIZABLE| pygame.HWSURFACE|pygame.DOUBLEBUF) Settings.obsList += generateObstacles(Settings.numberObs, screen) ## Settings class keeps obstacle number Settings.obsDraw(screen) pygame.display.update() foodRadius = Settings.getFoodRadius() SnakeSize = Settings.getSnakeSize() food = Food(screen,foodRadius) snake = Snake(screen,SnakeSize) # sets Snake starting velocity event,Str = block() # blocks before game starts if Str == "quit": exit() elif Str == "mouse": return 0 ## score elif Str == "keydown": snake.event(event,True) while (snake.getVelocity() == (0,0)): event,Str = block() snake.event(event,True) elif Str == "resize": size = event.dict['size'] Settings.surfaceSize = size screen = pygame.display.set_mode(size,pygame.RESIZABLE| pygame.HWSURFACE|pygame.DOUBLEBUF) snake.set_surface(screen) food.set_surface(screen) food.redraw() snake.redraw() Settings.obsDraw(screen) while running: snake.move() snake.draw() # while loop allows for food to always be drawn in a single loop while True: coords = food.foodCoords() if not(coords in snake.getBody()): if checkObstacle(coords, Settings.obsList): food.draw() break; ## use screen.get_width and .get_height methods in case you need to resize running = checkObstacle(snake.getPos(),Settings.obsList) ## check if Snake hit any obstacle if snake.checkInvalidMove(): running = False snake.set_surface(screen) if Settings.getCollision(): #returns True if snake is set to collide with walls snake.checkBoundaries() if snake.getCrashState(): running = False else: x,y = snake.checkBoundaries() if snake.getCrashState(): snakeX,snakeY = snake.getPos() if snakeX > snake.surface.get_width(): snake.x = 0 elif snakeX < 0: snake.x = snake.surface.get_width() elif snakeY < 0: snake.y = snake.surface.get_height() elif snakeY > snake.surface.get_height(): snake.y = 0 if food.check(snake.x, snake.y): score += 1 snake.eat() food.erase() event, Str = nonBlock() if Str == "quit": exit() if Str == "none": a = None elif Str == "keydown": snake.event(event,True) elif Str == "mouse": snake.event(event,False) elif Str == "resize": size = event.dict['size'] Settings.surfaceSize = size screen = pygame.display.set_mode(size,screen.get_flags()) Settings.setSurface(screen) snake.set_surface(screen) food.set_surface(screen) food.redraw() snake.redraw() Settings.obsDraw(screen) pygame.display.update() clock.tick(fpsSet) ## fps set -> must be set in every loop of the game loop return score
def test_changeDirTests(self) : # i : directionSnakes, j : changeDirVars UP = Snake() UP.changeDir(2) UP.move() UP.changeDir(1) DOWN = Snake() RIGHT = Snake() RIGHT.changeDir(2) LEFT = Snake() LEFT.changeDir(-2) directionSnakes = [DOWN,UP,LEFT,RIGHT] for i in range(4) : for j in range(4) : UP2 = Snake() UP2.changeDir(2) UP2.move() UP2.changeDir(1) DOWN2 = Snake() RIGHT2 = Snake() RIGHT2.changeDir(2) LEFT2 = Snake() LEFT2.changeDir(-2) directionSnakes2 = [DOWN2,UP2,LEFT2,RIGHT2] directionSnakes2[i].changeDir(changeDirVars[j]) obj = directionSnakes2[i].direction if i<2 : if j<2 : self.assertEquals(directionSnakes[i].direction,obj) else : self.assertEquals(changeDirVars[j],obj) else : if j<2 : self.assertEquals(changeDirVars[j],obj) else : self.assertEquals(directionSnakes[i].direction,obj)
class PlayMap: """ PlayMap has state variables: height:integer width: integer snake: Snake object food: Food object powerUp: powerUp object powerUpStatus: boolean gameStatsBar: pygame.Rect object powerUpIndicator: pygame.Rect object score: integer assumptions: __init__ is executed first """ def __init__(self): """ Constructor method for PlayMap Transition: initialized into new game state input:none output:none """ self.height = 500 self.width = 550 self.snake = Snake() # starting coord of snake self.food = Food() self.powerUp = PowerUp() self.powerUpStatus = True self.gameStatsBar = pygame.Rect(0,0,550,20) self.powerUpIndicator = pygame.Rect(10,0,10,10) self.score = len(self.snake.points) self.diff = 0 def setDiff(self,difficulty) : """ function to set the base difficulty of the game (speed of snake) transition: updates the difficulty of the game input: integer to represent difficulty output: none """ self.diff=difficulty def updateState(self): """ function to update the current state of the game board aka what is the state one time unit in the future Transition: moves snake, grows, or dies based on situation input:none output:none """ self.snake.move() # deal with food head = self.snake.points[0] if head == self.food.position: self.snake.grow() self.food = Food() self.score += 1 def isSnakeDead(self): """ function to check if snake is dead Transition: checks whether snake violates any rules of life input:none output:Boolean value """ status = self.didSnakeHitBorder() or self.didSnakeHitSelf() return status def getCurrentState(self): """ function to return the current state of the game board to MainMenu.py Transition: returns current state of the board input:none output:an array of objects """ if self.isSnakeDead(): return -1 if self.powerUpStatus: return [self.snake.points, self.food.position, self.gameStatsBar, self.powerUpIndicator, self.powerUp.position] if self.powerUpStatus==False: return [self.snake.points, self.food.position, self.gameStatsBar, -1, -1] def didSnakeHitBorder(self): """ function to check whether snake hit edge of the window Transition: checks against position of the borders to determine if snake is hitting the border input:none output:Boolean value """ head = self.snake.points[0] if head.left < 0: return True if head.left >= self.width: return True if head.top-20 < 0: return True if head.top >= self.height: return True return False def didSnakeHitSelf(self): """ function to check whether snake hit itself Transition: checks against position of itself to determine if snake is hitting itself input:none output:Boolean value """ temp = len(self.snake.points) i = 1 while i < temp : if self.snake.points[0]==self.snake.points[i] : if self.powerUpStatus : self.powerUpStatus=False self.snake.remove(i) else : return True i+=1 temp = len(self.snake.points) return False
def test_grow(self) : UP = Snake() UP.changeDir(2) UP.move() UP.changeDir(1) DOWN = Snake() RIGHT = Snake() RIGHT.changeDir(2) LEFT = Snake() LEFT.changeDir(-2) directionSnakes = [DOWN,UP,LEFT,RIGHT] for i in range(4) : directionSnakes[i].grow() self.assertEquals(str(directionSnakes[i]),str(grownSnakes[i]))