def game_step(self, chosen_action): """ Исполняет один шаг игры - сдвигает змейку, проверяет ее на возможное столкновение и поедание приза,\ при необходимости отрисовывает новый кадр ( отрисовку можно отключить установив поле graphic\ класса Environment на False) :rtype: tuple :param chosen_action: Выбранное нейросетью действие для данного шага игры :return: Резульат функции get_data() """ self.reward = -1 if chosen_action == 1 and snake.orientation != 'right': snake.orientation = 'left' elif chosen_action == 1 and snake.orientation == 'right': self.reward += Game_Parameters.incorrect_step_reward elif chosen_action == 3 and snake.orientation != 'left': snake.orientation = 'right' elif chosen_action == 3 and snake.orientation == 'left': self.reward += Game_Parameters.incorrect_step_reward elif chosen_action == 2 and snake.orientation != 'down': snake.orientation = 'up' elif chosen_action == 2 and snake.orientation == 'down': self.reward += Game_Parameters.incorrect_step_reward elif chosen_action == 4 and snake.orientation != 'up': snake.orientation = 'down' elif chosen_action == 4 and snake.orientation == 'up': self.reward += Game_Parameters.incorrect_step_reward snake.move(self.snakes) self.last_x = self.snakes[len(self.snakes) - 1].get_snake_element_x() self.last_y = self.snakes[len(self.snakes) - 1].get_snake_element_y() if self.crash(): self.game_running = False self.reward += Game_Parameters.crash_reward if self.eat_prize(): self.upgrade() self.reward += Game_Parameters.eating_reward if self.graphic: # Update self.all_sprites.update() # Render self.screen.fill(Game_Parameters.black) self.all_sprites.draw(self.screen) pygame.display.flip() value = self.get_data() return value
def main(): pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode((screen_width, screen_height), 0, 32) surface = pygame.Surface(screen.get_size()) surface = surface.convert() drawGrid(surface) snake = Snake() food = Food() myfont = pygame.font.SysFont("impact", 16) run = True #main game loop that runs until the snake dies while (run): clock.tick(10) snake.movement() drawGrid(surface) snake.move() if snake.headPos() == food.pos: snake.lengthBody += 1 snake.gameScore += 1 food.randomPos() snake.draw(surface) food.draw(surface) screen.blit(surface, (0, 0)) textScore = myfont.render("Score {0}".format(snake.gameScore), 1, (0, 0, 0)) screen.blit(textScore, (5, 10)) if snake.death == True: myfont = pygame.font.SysFont("impact", 28) run = False screen.fill((0, 0, 0)) textDead = myfont.render( "Your Final Score is {0}".format(snake.gameScore), 1, (255, 255, 255)) screen.blit(textDead, ((screen_width // 2) - 200, (screen_height // 2) - 50)) textRestart = myfont.render("Press Spacebar to Restart!", 1, (255, 255, 255)) screen.blit(textRestart, ((screen_width // 2) - 210, (screen_height // 2) - 25)) pygame.display.update() while run == False: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: snake.reset() run = True main() pygame.display.update()
def start_game(self): # Game cycle while self.game_running: # Time control self.clock.tick(Game_Parameters.fps) # Checking for events for event in pygame.event.get(): if event.type == pygame.QUIT: self.game_running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and snake.orientation != 'right': snake.orientation = 'left' break elif event.key == pygame.K_UP and snake.orientation != 'down': snake.orientation = 'up' break elif event.key == pygame.K_DOWN and snake.orientation != 'up': snake.orientation = 'down' break elif event.key == pygame.K_RIGHT and snake.orientation != 'left': snake.orientation = 'right' break snake.move(self.snakes) if self.crash(): self.game_running = False self.last_x = self.snakes[len(self.snakes) - 1].get_snake_element_x() self.last_y = self.snakes[len(self.snakes) - 1].get_snake_element_y() if self.eat_prize(): self.upgrade() # Update self.all_sprites.update() # Render self.screen.fill(Game_Parameters.black) self.all_sprites.draw(self.screen) pygame.display.flip() print(self.score)
def move(): state = flask.request.json print('request', state) board = state['board'] convert = converter(board['width'], board['height']) game_state = game( id=state['you']['id'], width=board['width'], height=board['height'], food=[convert(f['x'], f['y']) for f in board['food']], snakes={ s['id']: [ convert(f['x'], f['y']) for f in s['body'] ] for s in board['snakes'] }, health=state['you']['health'], friendlies={ s['id']: s['name'].startswith('coldog-') for s in board['snakes'] }, ) direction = snake.move(**game_state) return json.dumps({'move': direction})
def game() -> None: curses.curs_set(0) # hide cursor screen.nodelay(True) # Don't block I/O calls settings.reset_dynamic_settings() boundaries = Boundaries() # boundaries, within which snakes can move snake_ = snake.initialize(boundaries, settings.init_snake_size) # initialize snake food_ = food.create(boundaries, snake_) # initial food display = Display(boundaries, screen) # initialize display directions = { curses.KEY_UP: (-1, 0), curses.KEY_DOWN: (1, 0), curses.KEY_LEFT: (0, -2), # hori need to scale up to match vert curses.KEY_RIGHT: (0, 2), } direction = directions[curses.KEY_RIGHT] # default direction while True: # game loop screen.erase() # check whether snake has eaten the food eaten = snake.eat_food(snake_, food_) if eaten: food_ = food.create(boundaries, snake_) settings.snake_size_up() settings.lvl_up() # get direction from user arrow key input direction = directions.get(screen.getch(), direction) # move snake accordingly snake_ = snake.move(snake_, direction, eaten) # display game elements display.boundaries() display.food(food_) display.snake(snake_) display.score(f"Current score: {settings.score()}") if settings.high_score: display.high_score(f"Highest score: {settings.high_score}") screen.refresh() if game_over.check(snake_, boundaries): settings.update_high_score() display.game_over("Game Over. Press 'p' to play again or 'q' to quit.") screen.refresh() if game_over.restart(screen): game() # restart game break # speed of snake time.sleep(0.1 / settings.speed)
def move(game: Game, direction: Direction) -> Game: if direction.is_opposit(game.direction): direction = game.direction snake_ = snake.move(game.snake, direction, game.grow) if not pos_utils.within(*snake_[-1], *(0, 0), *game.size): raise SnakeOutOfGameError() food = game.food if food in snake_: grow = True food = pos_utils.rand(*(0, 0), *game.size) else: grow = False food = game.food return Game(game.size, snake_, grow, direction, food)
def dispose(snake, operation): #pygame在作祟 不加下面两行会卡死 event = pygame.event.get() pygame.event.clear() ''' if event.type == KEYDOWN: if event.key==K_w and new_snake.direction !=snake.H_DOWN: new_snake.direction=snake.H_UP elif event.key==K_s and new_snake.direction !=snake.H_UP: new_snake.direction=snake.H_DOWN elif event.key==K_a and new_snake.direction !=snake.H_RIGHT: new_snake.direction=snake.H_LEFT elif event.key==K_d and new_snake.direction !=snake.H_LEFT: new_snake.direction=snake.H_RIGHT ''' snake.set_direction(operation.pop(0)) ret = snake.move() #print(ret) return ret
def test_move_down(self): self.assertEqual(move([5, 5], 'D'), [5, 6])
def test_move_up(self): self.assertEqual(move([5, 5], 'U'), [5, 4])
def test_move_right(self): self.assertEqual(move([5, 5], 'R'), [6, 5])
def test_move_left(self): self.assertEqual(move([5, 5], 'L'), [4, 5])
elif event.key == pygame.K_ESCAPE: sys.exit() if event.type == SNAKEMOVE and gameEnded == False: nextSquare = findNextSquare() if nextSquare == None or nextSquare.type == enums.SquareType.BODY: resultText = font.render("LOST", 1, white) gameEnded = True break if nextSquare.type == enums.SquareType.FRUIT: map.randomFruit() scoreText = font.render("Score: " + str(snake.score), 1, white) if (snake.score % 5 == 0): newSpeed = int(300 - snake.score / 5 * 2) pygame.time.set_timer(SNAKEMOVE, newSpeed) speedText = font.render("Speed: " + str(newSpeed), 1, white) if (snake.score == enums.mapSize * enums.mapSize): resultText = font.render("WIN!", 1, white) gameEnded = True snake.move(nextSquare) screen.fill(black) for square in map.squares.values(): screen.blit(square.img, square.pos) screen.blit(scoreText, (25 * 20 + 20, 0)) screen.blit(speedText, (25 * 20 + 20, 30)) if gameEnded: screen.blit(resultText, (25 * 20 + 20, 60)) pygame.display.flip()
text_wWin=font2.render('worm is winner!',1,(255,0,40)) #******************************************************************# #Ejraye bazi : #******************************************************************# while running1 and running2 : screen.blit(text_Score1, (22, 35)) screen.blit(text_Life1, (22,60)) screen.blit(text_snake, (22, 20)) screen.blit(text_worm, (300,20)) screen.blit(text_Score2, (300,35)) screen.blit(text_Life2, (300,60)) worm.move() worm.draw() snake.move() snake.draw() emtiaz3.erase(75,40) emtiaz3.draw(75,40,(255,255,255),score1) joon3.erase(75,65) joon3.draw(75,65,(0,128,0),5*joon1) emtiaz4.erase(350,40) emtiaz4.draw(350,40,(255,255,255),score2) joon4.erase(350,65) joon4.draw(350,65,(0,128,0),5*joon2) food.draw() bomb.draw() ghaza.draw() mane1.draw(52) mane2.draw(104) mane3.draw(0)
print(f"new apple at ({appX} {appY})".format()) while True: screen.fill(0) print(f"{snake.length}".format(), end='\r') for _event in pygame.event.get(): if _event.type == pygame.QUIT: pygame.quit() sys.exit() snake.draw_self(screen, TILE_SIZE) pygame.draw.rect( screen, pygame.Color("yellow"), (appX * TILE_SIZE, appY * TILE_SIZE, TILE_SIZE, TILE_SIZE)) if snake.get_head()[0] == appX and snake.get_head()[1] == appY: snake.eat_apple() appX = randrange(0, WIDTH // TILE_SIZE, 1) appY = randrange(0, HEIGHT // TILE_SIZE, 1) #destroy condition if snake.get_head()[0] < 0 or snake.get_head()[0] >= 20 or snake.get_head( )[1] < 0 or snake.get_head()[1] >= 20: sys.exit() snake.move() snake.process_keys(keys=pygame.key.get_pressed()) clock.tick(FPS) pygame.display.flip()
from collections import namedtuple from snake import move from move import move Point = namedtuple('P', 'x y') Snake = namedtuple('S', 'head body') def mksnake(*body): return Snake(body[0], body) print move(mksnake((0, 0)), mksnake((1, 0)), (4, 0), None, 10, 10)
if dirKey[pygame.K_RIGHT]: snake.setDirection((1, 0)) if dirKey[pygame.K_LEFT]: snake.setDirection((-1, 0)) if dirKey[pygame.K_UP]: snake.setDirection((0, -1)) if dirKey[pygame.K_DOWN]: snake.setDirection((0, 1)) if timer >= timeStep: timer = 0 if snake.move(gb) == -1: active = False # Draw game: window.fill(black) for x in range(mapSize[0]): for y in range(mapSize[1]): cv = gb.getCellVal(x, y) if cv == 1: drawSquare((x, y), ppc, white) elif cv == 2: drawSquare((x, y), ppc, red) pygame.display.update() pygame.quit()
snake.direction = 'u' if event.key == pygame.K_DOWN and snake.direction != 'u': snake.direction = 'd' if event.key == pygame.K_RIGHT and snake.direction != 'l': snake.direction = 'r' if event.key == pygame.K_LEFT and snake.direction != 'r': snake.direction = 'l' # IF GAME IS WORKING if GAME: if food.check_ate(snake): draw_food(food) snake.add_case() last_case = snake.move() # try to update the board try: board.update(snake, last_case, food) # if we can't, he is in the wall except IndexError: print("[GAME OVER]") GAME = False # he loses continue # to not exec next lines # draw snake, refresh display draw_snake(snake, last_case) pygame.display.update() # CLOCK clock.tick(ticks)
def process_frame(self): self.replay_snapshot() if self.p1_score >= 3 or self.p2_score >= 3: return self.match() if self.countdown: back = ("snake_double", SnakeDouble, self.data, True) self.countdown = False return ("countdown", Countdown, (self.surface_snapshot(), self.countdown_text, self.countdown_length, back)) window = pygame.display.get_surface() window_width = window.get_width() window_height = window.get_height() p1 = self.objects["p1"] p2 = self.objects["p2"] food = self.objects["food"] for event in pygame.event.get(): self.check_quit(event) snakes = [p1, p2] controls = [self.p1_controls, self.p2_controls] key_list = pygame.key.get_pressed() for i, (snake, controls) in enumerate(zip(snakes, controls)): other_snake = not i for rect in snake.tail_rects: if snakes[other_snake].head_rect.colliderect(rect): return self.win(i) x = snake.pos[0] y = snake.pos[1] if x > window_width or x < 0 or y > window_height or y < 0: return self.win(other_snake) if snake.head_rect.colliderect(food.rect): grow = True self.objects["food"] = self.spawn_food() else: grow = False if key_list[controls[0]]: if snake.direction != pygame.K_DOWN: snake.direction = pygame.K_UP elif key_list[controls[1]]: if snake.direction != pygame.K_LEFT: snake.direction = pygame.K_RIGHT elif key_list[controls[2]]: if snake.direction != pygame.K_UP: snake.direction = pygame.K_DOWN elif key_list[controls[3]]: if snake.direction != pygame.K_RIGHT: snake.direction = pygame.K_LEFT snake.move(grow)