示例#1
0
 def _apple_spawn_events(self):
     if random.random() < self.other_apple_spawn_rate:
         if random.random() < 0.1:
             self.other_apples.append(Apple(GOLDEN))
         else:
             self.other_apples.append(Apple(POISON))
         self.randomly_place_sprite(self.other_apples[-1])
     if random.random(
     ) < self.other_apple_despawn_rate and self.other_apples:
         apple_to_delete = random.choice(self.other_apples)
         self.other_apples.remove(apple_to_delete)
示例#2
0
    def setup(self):
        self.snake = Snake(c.MAP_SIZE, c.SNAKE_COLOR)
        self.apple = Apple(c.MAP_SIZE, c.APPLE_COLOR)
        pause_hint_text = Text(
            0,
            0,
            lambda: "Press p to pause/unpause after game started",
            self.font,
            True,
        )
        start_text = Text(0, 50, lambda: "Press space to start", self.font, True)
        score_text = Text(0, 0, lambda: f"Score: {len(self.snake)}", self.font)
        play_again_text = Text(
            0,
            0,
            lambda: f"You lose! Final Score: {len(self.snake)}. Press space to restart",
            self.font,
            True,
        )
        pause_text = Text(0, 0, lambda: "Game paused", self.font, True)

        self.objects[GameState.MAIN_MENU] = [pause_hint_text, start_text]
        self.objects[GameState.PAUSED] = [score_text, pause_text]
        self.objects[GameState.IN_PROGRESS] = [score_text]
        self.objects[GameState.END] = [play_again_text]
示例#3
0
def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    game_settings = Settings()
    screen = pygame.display.set_mode(game_settings.screen_set)
    pygame.display.set_caption("Gluttonous Snake")

    snakes = Group()
    for i in range(3):
        screen_rect = screen.get_rect()
        if (i == 0):
            snake = Snake(screen, game_settings, screen_rect.centerx - 9,
                          screen_rect.centery)
        else:
            snake = Snake(screen, game_settings, last_snake_x, last_snake_y,
                          last_snake_diretion)
        last_snake_diretion = snake.direction
        last_snake_x = snake.rect.x
        last_snake_y = snake.rect.y
        snakes.add(snake)
    play_button = Button(screen)
    sb = Scoreboard(screen)
    apple = Apple(screen, game_settings)

    # 开始游戏的主循环
    while True:
        cheak_events(play_button, game_settings, sb, apple, snakes, screen)
        if game_settings.game_active:
            update_snake(snakes, game_settings, screen)
            update_apple(snakes, apple, screen, game_settings, sb)
        update_screen(game_settings, snakes, apple, sb, play_button, screen)
示例#4
0
    def __init__(self):
        self.title = "Snake"
        self.board_size = 600  # its always a square
        self.cell_size = 40
        self.board_color = Color.BLACK.value
        self.has_grid = True
        self.grid_color = Color.GRAY.value
        self.speed = 10
        self.pause = 2
        self.running = True
        # Score
        self.score = 0
        self.score_font = "bahnschrift"
        self.score_size = 30
        self.score_color = Color.GREEN.value
        self.score_position = (self.board_size - 4 * self.cell_size,
                               self.cell_size)
        self.score_text = 'Score: '
        # Game over
        self.game_over_font = "bahnschrift"
        self.game_over_size = 120
        self.game_over_color = Color.GREEN.value
        self.game_over_position = (self.board_size // 6, self.board_size // 4)
        self.game_over_text = 'Game Over'

        self.snake = Snake(self.board_size, self.cell_size)
        self.apple = Apple(self.board_size, self.cell_size)
        self.apple.random_position()
示例#5
0
    def Reset(self):
        del self.snake
        del self.apple
        self.snake = Snake()
        self.apple = Apple()

        return True
示例#6
0
文件: game.py 项目: grigoll/Pynake
    def setup(self):
        self.set_update_rate(1 / 8)  # fps

        self.game_started = False
        self.game_over = False
        self.score = 0

        self.snake = Snake(
            (self.width, self.height),
            self.tile_size
        )
        self.apple = Apple(
            (self.width, self.height),
            self.tile_size,
            self.snake.placement
        )

        # goes clockwise (top, right, bottom, left)
        self.borders = (
            int(self.height - self.tile_size / 2),
            int(self.width - self.tile_size / 2),
            int(0 + self.tile_size / 2),
            int(0 + self.tile_size / 2),
        )

        self.death_sound = arcade.Sound('assets/audio/death.mp3')

        return self
    def init_level(self, level):
        self.current_level = Level(level)
        #self.draw_level(self.current_level.get_matrix())

        #  mark game as not finished
        self.game_finished = False
        self.player_alive = True

        #  number of time steps elapsed in a level
        self.elapsed_time_step = 0

        #  initialize number of apples player collected so far in curret level
        self.collected_apple_count = 0

        #  create player object
        player_pos = self.current_level.get_player_pos()
        player_current_row = player_pos[0]
        player_current_col = player_pos[1]
        self.player = Player(player_current_row, player_current_col)

        #  create apples
        self.apples = []
        apple_positions = self.current_level.get_apple_positions()
        for pos in apple_positions:
            r = pos[0]
            c = pos[1]
            self.apples.append(Apple(r, c))

        #  count number of apples
        self.total_apple_count = len(self.apples)
示例#8
0
 def resetGame(self):
     #clears the board
     del self.snake
     del self.apple
     self.snake = Snake()
     self.apple = Apple()
     return True
示例#9
0
    def __init__(self, draw=True, fps=10, debug=False):
        if draw:
            pygame.init()
            pygame.display.set_caption('NN Snake')

            self.font_game_over = pygame.font.SysFont("ani", 72)

        self.fps = fps
        self.debug = debug
        self.draw = draw

        self.clock = pygame.time.Clock()
        self.time_elapsed_since_last_action = 0
        self.global_time = 0

        self.screen = pygame.display.set_mode(SCREEN_SIZE)

        self.snake = Snake(self.screen, WIDTH, HEIGHT, SNAKE_COLOR, SCALE)
        self.apple = Apple(self.screen, WIDTH, HEIGHT, APPPLE_COLOR, SCALE)

        # self.bird = Bird(self.screen, WIDTH, HEIGHT, BIRD_COLOR)
        # self.pipes = [Pipe(self.screen, WIDTH, HEIGHT, PIPE_COLOR, self.pipe_image, self.pipe_long_image)]

        self.reward = 0
        self.is_done = False
        self.printed_score = False
示例#10
0
    def __init__(self):
        super(PySnake, self).__init__(GAME_NAME, SCREEN_SIZE, FPS,
                                      "resources/Minecraft.ttf", 16,
                                      "resources/pysnake.png")
        self.background.fill(BACKGROUND_COLOR)
        for i in range(CELL_SIZE, SCREEN_WIDTH, CELL_SIZE):
            pygame.draw.line(self.background, GRID_COLOR, (i, 0),
                             (i, SCREEN_HEIGHT))
        for i in range(CELL_SIZE, SCREEN_HEIGHT, CELL_SIZE):
            pygame.draw.line(self.background, GRID_COLOR, (0, i),
                             (SCREEN_WIDTH, i))

        self.field = Field(self, COLUMNS, ROWS)
        self.apple_counter = 0
        self.apple = Apple(self)
        # self.snake = Snake(self)
        self.snake = Snake(self, SNAKE_DEFAULT_X, SNAKE_DEFAULT_Y,
                           SNAKE_DEFAULT_LENGTH, RIGHT, SNAKE_DEFAULT_SPEED,
                           SNAKE_COLOR_SKIN, SNAKE_COLOR_BODY,
                           SNAKE_COLOR_HEAD)

        # 控制按键设定
        self.key_bind(KEY_EXIT, self.quit)
        self.key_bind(KEY_UP, self.snake.turn, direction=UP)
        self.key_bind(KEY_DOWN, self.snake.turn, direction=DOWN)
        self.key_bind(KEY_LEFT, self.snake.turn, direction=LEFT)
        self.key_bind(KEY_RIGHT, self.snake.turn, direction=RIGHT)
        self.key_bind(pygame.K_EQUALS, self.snake.speed_up)
        self.key_bind(pygame.K_MINUS, self.snake.speed_down)
        self.key_bind(KEY_RESPAWN, self.restart)

        self.add_draw_action(self.show_score)
示例#11
0
    def on_loop(self):
        # does snake collide with itself?
        for i in range(2, len(self.player.snake_segments)):
            if (self.game.is_collision(self.player.snake_segments[0],
                                       self.player.snake_segments[i],
                                       self.player.size)):
                self.on_exit()

        # does snake collide with wall?
        if (self.game.is_wall_collision(self.player.snake_segments[0],
                                        self.size, self.window_width,
                                        self.window_height)):
            self.on_exit()

        # does snake eat apple?
        if (self.game.is_collision(self.apple, self.player.snake_segments[0],
                                   self.size)):

            self.player.add_segment(self.all_sprites_list)
            self.all_sprites_list.remove(self.apple)
            self.apple = Apple(
                randint(0, self.window_width / 10 - 1) *
                (self.size + self.margain),
                randint(0, self.window_height / 10 - 1) *
                (self.size + self.margain), self.size)
            self.all_sprites_list.add(self.apple)

        self.player.update(self.all_sprites_list)
    def add_apple(self, is_red: bool):
        xy = XYPoint(randrange(self.board_width), randrange(self.board_height))
        while (xy.x, xy.y) in self.apples:
            xy = XYPoint(randrange(self.board_width), randrange(self.board_height))

        apple = Apple(xy, 10, is_red)
        self.apples[(apple.xy.x, apple.xy.y)] = apple
示例#13
0
 def __init__(self):
     self._running = True
     self._display_surf = None
     self._image_surf = None
     self._apple_surf = None
     self.snake = Snake(3)
     self.apple = Apple(5,5)
示例#14
0
def game(screen):
    move = False
    score = 0
    running = True
    snake = Snake(screen)
    apple = Apple()
    bg = Background("images/bg.jpg", [0, 0])
    while running:
        clickedArrow = False
        ateApple = False
        screen.fill(bgcolor)
        #screen.blit(bg.image, bg.rect)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pause(screen)
                    continue
                if event.key == pygame.K_UP and snake.direction != 2 and not clickedArrow:
                    move = True
                    clickedArrow = True
                    snake.setDirection(0)
                if event.key == pygame.K_RIGHT and snake.direction != 3 and not clickedArrow:
                    move = True
                    clickedArrow = True
                    snake.setDirection(1)
                if event.key == pygame.K_DOWN and snake.direction != 0 and not clickedArrow:
                    move = True
                    clickedArrow = True
                    snake.setDirection(2)
                if event.key == pygame.K_LEFT and snake.direction != 1 and not clickedArrow:
                    move = True
                    clickedArrow = True
                    snake.setDirection(3)
                if event.key == pygame.K_1:
                    snake.makeBigger()
                    score += 1
                    ateApple = True
                if event.key == pygame.K_2:
                    snake.makeSmaller()
        if move:
            snake.move()
        if snake.pieces[0].x == apple.x and snake.pieces[0].y == apple.y:
            score += 1
            apple.changeCoords()
            snake.makeBigger()
            ateApple = True
        if snake.isDead() and not ateApple:
            gameOver(screen, score)
            running = False
        apple.draw(screen)
        if not ateApple:
            snake.draw()
        drawscore(screen, score)
        pygame.display.update()
        time.sleep(.25)
示例#15
0
    def resetGame(self):
        del self.snake
        del self.apple
        self.snake = Snake()
        self.apple = Apple()

        return True
示例#16
0
    def run(self, test=None):
        """ Initialises the Screen, calls Screen.display_score function and initialises a new snake and a new apple """

        Screen.start_screen()  # Start screen
        Screen.display_btm_info(self.score)  # Display score

        snake = Snake()  # Initialise new snake
        apple = Apple(snake.body)  # Initialise new apple

        ##### Game loop #####
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

                # Arrow controls direction, and checks to not go directly to direction it came from
                elif event.type == KEYDOWN:
                    if event.key == K_LEFT and snake.get_direction() != RIGHT:
                        snake.set_direction(LEFT)
                        break
                    elif event.key == K_RIGHT and snake.get_direction(
                    ) != LEFT:
                        snake.set_direction(RIGHT)
                        break
                    elif event.key == K_UP and snake.get_direction() != DOWN:
                        snake.set_direction(UP)
                        break
                    elif event.key == K_DOWN and snake.get_direction() != UP:
                        snake.set_direction(DOWN)
                        break

            if not snake.move(
            ):  # if snake can't move, call Game.gameover(), else move in current direction.
                Game.FPS = Game.starting_FPS  # reset game FPS
                Game.gameover()  # call Game.gameover() screen

            if snake.eating(apple.x, apple.y):
                apple = Apple(snake.body)
                self.score += 1
                Screen.draw_btm_bar()
                Screen.display_btm_info(self.score)
                snake.grow()
                Game.FPS += 1  # Speed up game after every apple eaten

            Screen.update()
            Game.fpsClock.tick(Game.FPS)
示例#17
0
文件: main.py 项目: EvgeneyZ/SnakeAI
def run_game():
    pygame.init()
    pygame.font.init()
    w = s.screen_width * s.cell_size + 1
    h = s.screen_height * s.cell_size + 1
    screen = pygame.display.set_mode((w, h))
    pygame.display.set_caption("Snake")

    myfont = pygame.font.SysFont('Arial', 40)

    clock = pygame.time.Clock()

    snake = Snake()
    apple = Apple(snake)
    snake.apple = apple
    ai = AI()

    while (True):

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    snake.direction = (-1, 0)
                elif event.key == pygame.K_RIGHT:
                    snake.direction = (1, 0)
                elif event.key == pygame.K_UP:
                    snake.direction = (0, -1)
                elif event.key == pygame.K_DOWN:
                    snake.direction = (0, 1)
                elif event.key == pygame.K_ESCAPE:
                    sys.exit()
                elif event.key == pygame.K_SPACE:
                    pause()

        if not snake.dead:
            ai.pass_through(snake.body[:], apple.position[:])
            snake.direction = ai.output()
            snake.move()
        screen.fill(s.bg_color)
        screen = draw_board(screen, snake, apple, ai.path, myfont)
        pygame.display.flip()

        if (snake.dead):
            print("Snake lost, size: ", len(snake))
            apple.randomize()
            snake = Snake()
            apple.snake = snake
            snake.apple = apple
            ai = AI()
        elif len(snake.body) == s.screen_width * s.screen_height:
            print("Snake won! Size: ", len(snake))
            return

        fps = s.FPS
        if ai.mode == "Tail":
            fps *= 2
        clock.tick(fps)
示例#18
0
 def __init__(self):
     self._running = True
     self._display_surf = None
     self._image_surf = None
     self._apple_surf = None
     self.game = Game()
     self.player = Player(3) 
     self.apple = Apple(5,5)
示例#19
0
 def __init__(self):
   pygame.init()
   self.screen = pygame.display.set_mode((Config.WINDOW_WIDTH, Config.WINDOW_HEIGHT))
   self.clock = pygame.time.Clock()
   self.BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
   pygame.display.set_caption('Wormy')
   self.apple = Apple()
   self.snake = Snake()
示例#20
0
 def __init__(self):
     self.sense = SenseHat()
     self.sense.clear()
     self.sense.low_light = True
     self.sensimate = SensiMate(self.sense)
     self.apple = Apple(self.sense, (200, 0, 0))
     self.snake = Snake(self.sense, (0, 133, 0), self.apple, 1)
     self.start()
示例#21
0
    def check_game_state(self):
        if self.snake[0].check_state(self.apple, self.snake, self):
            self.score += 1
            self.apple = Apple(self.window.display, self.snake)
            self.snake.append(Snake(self.window.display, self.snake[0].prev))
            self.graph.update(self.snake, self.apple)

            self.algorithm.get_path(
                self.snake[0].relative_pos, self.apple.relative_pos, self.graph)
示例#22
0
    def resetGame(self):

        self.lastScore = len(self.snake.wormCoords) - 3
        del self.snake
        del self.apple
        self.snake = Snake()
        self.apple = Apple()

        return True
示例#23
0
 def __init__(self):
     self._running = True
     self._screen = None
     self.all_sprites_list = pygame.sprite.Group()
     self.game = Game()
     self.player = Player(self.all_sprites_list, self.window_width / 2,
                          self.window_height / 2, self.size, self.margain)
     self.apple = Apple(self.window_width / 2, self.window_height / 2,
                        self.size)
示例#24
0
    def init(self, winWidth, winHeight):
        self.fieldWidth = winWidth // constants.FIELD_SIZE
        self.fieldHeight = winHeight // constants.FIELD_SIZE

        self.snake = Snake(self.fieldWidth // 2, self.fieldHeight // 2)
        self.apple = Apple(self.snake.getOccupiedCoords(), self.fieldWidth,
                           self.fieldHeight)
        self.currentTick = 0
        self.score = 0
示例#25
0
文件: app.py 项目: Bamagik/PyQSnake
 def __init__(self):
     self.running = True
     self._display_surf = None
     self._image_surf = None
     self.game = Game(self.window_width, self.window_height)
     self.player = Player(STARTING_LENGTH,
                          self.window_height * self.window_width)
     self.apple = Apple(randint(0, self.window_width // STEP - 1),
                        randint(0, self.window_height // STEP - 1))
示例#26
0
 def __init__(self):
     pygame.init()
     self.clock = pygame.time.Clock()
     self.screen = pygame.display.set_mode((Config.WINDOW_WIDTH,Config.WINDOW_HEIGHT))
     self.BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
     self.OVER = pygame.font.Font('freesansbold.ttf', 54)
     self.apple = Apple()
     self.snake = Snake()
     self.Check = "GameisON"
示例#27
0
def enter():
    global player
    global objectList
    global backGround
    global flag
    global enemyList
    global music

    music = load_music('sound\\stage.mp3')
    music.set_volume(60)
    music.repeat_play()

    backGround = BackGround(1)
    game_world.add_object(backGround, 0)
    for i in range(10):
        for k in range(20):
            if tile_type[i][k] is 3:
                crushBlockList.append(CrushBlock((mapFirst + image_sizeW * k, mapTop - i * image_sizeH)))
            elif tile_type[i][k] is 4:
                lebberList.append(Lebber((mapFirst + image_sizeW * k, mapTop - i * image_sizeH), tile_type[i][k]))
            elif tile_type[i][k] is 5:
                lebberList.append(Lebber((mapFirst + image_sizeW * k, mapTop - i * image_sizeH), tile_type[i][k]))
            elif tile_type[i][k] is 6:
                lebberList.append(Lebber((mapFirst + image_sizeW * k, mapTop - i * image_sizeH), tile_type[i][k]))
            elif tile_type[i][k] is 7:
                player = Ohdam((mapFirst + image_sizeW * k, mapTop - i * image_sizeH))
            elif tile_type[i][k] is 8:
                enemyList.append(Monster1((mapFirst + image_sizeW * k, mapTop - i * image_sizeH)))
            elif tile_type[i][k] is 9:
                flag = Flag((mapFirst + image_sizeW * k, mapTop - i * image_sizeH))
            elif tile_type[i][k] is 0:
                pass
            else:
                flourBlockList.append(
                    FlourBlock((mapFirst + image_sizeW * k, mapTop - i * image_sizeH), tile_type[i][k]))

    game_world.add_object(flag, 5)
    game_world.add_objects(lebberList, 1);
    game_world.add_objects(flourBlockList, 3);
    game_world.add_objects(crushBlockList, 4);
    game_world.add_objects(enemyList, 2);
    game_world.add_object(player, 6)

    for i in range(0, 3):
        objectList.append(Apple((32 + 64 * 6 + i * 64, 608)))
    for i in range(0, 3):
        objectList.append(Apple((32 + 64 * 6 + i * 64, 480)))
    for i in range(0, 3):
        objectList.append(Apple((32 + 64 * 6 + i * 64, 352)))
    for i in range(0, 3):
        objectList.append(Apple((32 + 64 * 13 + i * 64, 480)))
    for i in range(0, 3):
        objectList.append(Apple((32 + 64 * 13 + i * 64, 352)))
    for i in range(0, 3):
        objectList.append(Apple((32 + 64 * 14 + i * 64, 608)))
    for i in range(0, 15):
        objectList.append(Apple((32 + 64 * 4 + i * 64, 160)))
    game_world.add_objects(objectList, 7);
    pass
示例#28
0
def move_rect():

    global dir

    cur_y = snakeHead.y
    cur_x = snakeHead.x

    if (cur_y >= settings[1] - snakeHead.height) or (cur_y <= 0) or (cur_x >= settings[0] - snakeHead.width) or (cur_x <= 0):
        pygame.quit()
    if dir == DOWN:
        cur_y += 10
    if dir == UP:
        cur_y -= 10
    if dir == LEFT:
        cur_x -= 10
    if dir == RIGHT:
        cur_x += 10

    prev_x = snakeHead.x
    prev_y = snakeHead.y
    snakeHead.y = cur_y
    snakeHead.x = cur_x
    headSprite = SnakePart(head_img, snakeHead)
    pygame.draw.rect(scene, BLACK, snakeHead)
    scene.blit(head_img, snakeHead)
    headSprite.update()

    if len(snake)>1:
        isTail = True
        for j in range(len(snake)-1, 0, -1):
            if (j == 1):
                snake[j].y = prev_y
                snake[j].x = prev_x
            else:
                snake[j].y = snake[j-1].y
                snake[j].x = snake[j-1].x
            pygame.draw.rect(scene, BLACK, snake[j])
            if (isTail == True):
                scene.blit(tail_img, snake[j])
                isTail = False
            else:
                scene.blit(body_img, snake[j])

    appleSprite = Apple(apple_img, apple)

    #if (snakeHead.x == apple.x and snakeHead.y == apple.y):
    if (pygame.sprite.collide_rect(headSprite, appleSprite)):
        snake.append(pygame.Rect(prev_x, prev_y, 10, 10))
        apple.x = randint(3, 87) * 10
        apple.y = randint(3, 47) * 10

    pygame.draw.rect(scene, BLACK, apple)
    scene.blit(apple_img, apple)
    appleSprite.update()

    pygame.display.update()
示例#29
0
 def __init__(self, ga, width, height):
     self.ga = ga
     self.width = width
     self.height = height
     self.sc = pygame.display.set_mode([width + 1, height + 1])
     self.clock = pygame.time.Clock()
     self.snake = Snake(self.sc, self)
     self.apple = Apple(self.sc, self)
     self.death_stats = [0] * 3
     pygame.init()
示例#30
0
 def __init__(self, settings):
     self.width = settings.board_width
     self.height = settings.board_height
     self.board = self.make_board()
     self.snake = Snake(settings)
     self.apple = Apple(settings, self.snake)
     self.score = 0
     self.playtime_started = time.time()
     self.playtime_ended = 0
     self.settings = settings