Beispiel #1
0
    def setup_game(self):
        window = pygame.display.get_surface()
        window_width = window.get_width()
        window_height = window.get_height()

        buffer = 5 * self.block_size
        self.p1_starting_pos = (buffer, buffer)
        self.p2_starting_pos = (window_width - buffer, window_height - buffer)

        self.objects["p1"] = snake.Snake(self.p1_starting_pos, palette.GREEN,
                                         self.block_size)
        self.objects["p2"] = snake.Snake(self.p2_starting_pos, palette.BLUE,
                                         self.block_size)
        self.objects["food"] = self.spawn_food()

        self.objects["p1"].direction = pygame.K_DOWN
        self.objects["p2"].direction = pygame.K_UP

        self.p1_controls = [pygame.K_w, pygame.K_d, pygame.K_s, pygame.K_a]
        self.p2_controls = [
            pygame.K_UP, pygame.K_RIGHT, pygame.K_DOWN, pygame.K_LEFT
        ]

        self.p1_score = 0
        self.p2_score = 0
Beispiel #2
0
def build_snakes(data, me_id='0'):
    snakelist = []
    for snake in data['board']['snakes']:
        if snake['id'] != me_id:
            snakelist.append(snk.Snake(snake))

    return snakelist
Beispiel #3
0
    def processImageButtonClick(self):
        # Loads the desired image
        global filePath

        if (filePath == None):
            print("Select Image First")
            popup = Popup(title='Error',
                          content=Label(text='Image file not selected'),
                          size_hint=(None, None),
                          size=(400, 400))
            popup.open()
            return

        image = cv2.imread(filePath, cv2.IMREAD_COLOR)

        snake = s.Snake(image, closed=True)

        snake_window_name = "Snakes"
        cv2.namedWindow(snake_window_name)
        snake.set_alpha(self.root.get_screen('mainscreen').ids.alpha.value)
        snake.set_beta(self.root.get_screen('mainscreen').ids.beta.value)
        snake.set_delta(self.root.get_screen('mainscreen').ids.delta.value)
        snake.set_w_line(self.root.get_screen('mainscreen').ids.wline.value)
        snake.set_w_edge(self.root.get_screen('mainscreen').ids.wedge.value)
        snake.set_w_term(self.root.get_screen('mainscreen').ids.wterm.value)

        while (True):
            snakeImg = snake.visualize()
            cv2.imshow(snake_window_name, snakeImg)
            snake_changed = snake.step()
            k = cv2.waitKey(33)
            if k == 27:
                break

        cv2.destroyAllWindows()
Beispiel #4
0
def reset(badmove=False):
    # inicializacia hada
    global xyOfSnake, lenSnake, odmena, eaten, crashed, score, direction, steps, gameMap
    xyOfSnake = []
    lenSnake = 2
    if not badmove:
        odmena = 0

    steps = 0
    for i in range(0, lenSnake):
        xySnake = []
        xySnake.append(20)
        xySnake.append(20 + i * 10)
        # xySnake.append(gameDisplayWidth / 2)
        # xySnake.append((gameDisplayHeight - 30) / 2 + i * 10)
        xyOfSnake.append(xySnake)

    player = snake.Snake(gameDisplay)  # had
    #apple = food.Food(gameDisplay)  # jablko
    eaten = True
    crashed = False  # naburanie
    score = 0  # score
    direction = 0  # smer hada 0-hore 1-doprava 2-dole 3-dolava

    # pridame prveho jedla na mapu
    gameMap = gameScreen.mapUpdate(0, 0, xyOfSnake)
    apple.spawnNew(xyOfSnake, gameMap)
    gameMap = gameScreen.mapUpdate(apple.x, apple.y, xyOfSnake)
Beispiel #5
0
    def active_contour(self):
        self.clear = False
        snake = sn.Snake( self.image_1, closed = True )
        
        while(True):
            snakeImg = snake.visuaize_Image()
            img = pg.ImageItem(snakeImg)
            self.ui.image_1.addItem(img)
            x = []
            y = []
            for i in range(len(snake.points)):
            	x.append(snake.points[i][0])
            	y.append(snake.points[i][1])
            area=0.5*np.sum(y[:-1]*np.diff(x) - x[:-1]*np.diff(y))
            area=np.abs(area)
            perimeter = snake.get_length()
            self.ui.textEdit.setPlaceholderText("{}".format(area/10000))
            self.ui.textEdit_2.setPlaceholderText("{}".format(perimeter/100))
            # self.ui.image_1.setTitle("area = {} , perimeter = {}".format(area, perimeter))
            snake_changed = snake.step()
            
            self.ui.slider_1.valueChanged[int].connect(snake.set_alpha)
            self.ui.slider_2.valueChanged[int].connect(snake.set_beta)
            self.ui.slider_3.valueChanged[int].connect(snake.set_gamma)

            k = cv2.waitKey(33)
            if self.clear == True:
                if k == 27:
                     break
                cv2.destroyAllWindows()
                break
    def __init__(self, app, width, height):
        SceneBase.__init__(self, app, width, height)

        #create snake and apple
        self.snake = snake.Snake(width, height, self.BOX_WIDTH)
        self.apples = apples.Apples(width, height, self.BOX_WIDTH)
        self.nukes = nukes.Nukes(width, height, self.BOX_WIDTH)

        #add specific amount of apples at beginning
        for i in range(6):
            self.apples.addApple()

        #add specific amount of nukes at beginning
        for i in range(12):
            self.nukes.addNuke()

        #init particles
        self.animationEat = eatAnimation.EatAnimation(self.BOX_WIDTH)
        self.animationNuke = eatAnimation.EatAnimation(self.BOX_WIDTH)
        self.animationNuke.setColor((248, 20, 25))

        #font needed for score overlay
        self.font = pygame.font.SysFont("comicsansms", 40)

        #load music
        pygame.mixer.music.load("music/music.mp3")
        pygame.mixer.music.play(-1)

        #add sounds
        self.explosionSound = pygame.mixer.Sound("music/explosion.wav")
Beispiel #7
0
 def draw(self):
     screen_size = (self.width, self.height)
     screen = pygame.display.set_mode(screen_size)
     grid_instance = grid.Grid(self.square_side, self.width, self.height,
                               self.grid_color)
     food_generator = food.Food(self.square_side, self.width, self.height,
                                self.food_color)
     snake_instance = snake.Snake(self.square_side, self.width, self.height,
                                  self.snake_color, self.snake_head_color)
     food_generator.create_food()
     gameFinished = False
     while 1:
         for event in pygame.event.get():
             if event.type == pygame.QUIT:
                 sys.exit()
             if event.type == pygame.KEYDOWN:
                 snake_instance.change_direction(event)
         if gameFinished:
             sleep(1)
             continue
         screen.fill(self.bg_color)
         success = snake_instance.move()
         if success == False:
             gameFinished = True
             continue
         if snake_instance.eat_food_if_exist(food_generator):
             food_generator.create_food()
         grid_instance.draw(screen)
         food_generator.draw(screen)
         snake_instance.draw(screen)
         pygame.display.flip()
         sleep(0.05)
Beispiel #8
0
def main():
    global s, snack
    #setting size of the frame
    frame = pygame.display.set_mode((width, width))
    #setting snake
    s = snake.Snake(con.red, (10, 10))
    snack = cube.Cube(generate_random_snack_pos(s), color=con.green)
    flag = True

    clock = pygame.time.Clock()

    while flag:
        #Чтобы движение происходило не очень быстро
        pygame.time.delay(50)
        #10fps
        clock.tick(10)
        events = s.move()
        get_new_snack()
        check_for_intersect()
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    menu.start_menu(frame, clock, result=len(s.body))
        drawFrame(frame)
    pass
Beispiel #9
0
    def __init__(self, bran, grid=None):
        if grid is None:
            grid = snake.Grid()
        self.snake = snake.Snake(grid)
        self.brain = bran

        self.dead = False
Beispiel #10
0
 def __init__(self, y_size, x_size, step_map):
     self.x_size = x_size
     self.y_size = y_size
     
     self.s = snake.Snake(y_size-3, x_size-3, step_map)
     self.food = self._gen_food()
     self.score = 0
def main():
    global width, height, rows, s, snack
    width = 500
    height = 500
    rows = 20
    win = pygame.display.set_mode((width, height))
    pygame.display.set_caption("Snake game by Villy")
    pear = pygame.image.load('pear.png')
    apple = pygame.image.load('apple.png')  #TO DO - add lives
    s = snake.Snake((255, 0, 0), (10, 10))
    snack = edibles.Fruit(randomSnack(rows, s), pear)
    flag = True

    clock = pygame.time.Clock()

    while flag:
        pygame.time.delay(50)
        clock.tick(10)
        s.move()
        if s.body[0].pos == snack.pos:
            s.addCube()
            snack = edibles.Fruit(randomSnack(rows, s), pear)

        for x in range(len(s.body)):
            if s.body[x].pos in list(map(lambda z: z.pos, s.body[x + 1:])):
                message_box('You lost', 'Your score: ' + str(len(s.body)))
                message_box("You lost!", "Play again...")
                s.reset((10, 10))
                snack = edibles.Fruit(randomSnack(rows, s), pear)
                break

        redrawWindow(win)
    pass
Beispiel #12
0
def collision(player1, all_gamestations, screen, WIDTH, HEIGHT, clock, timer1):
    hit = pygame.sprite.spritecollide(player1, all_gamestations, True)
    global gamesplayed
    global gamechoice
    gamesplayed = 0
    if hit:
        if gamechoice == 0:
            fallingobjectsgame.falling(screen,
                WIDTH, HEIGHT, clock, 6, timer1, False)
        elif gamechoice == 1:
            dodge.falling(screen, WIDTH, HEIGHT, clock, 3, timer1, False)
        elif gamechoice == 2:
            snake.Snake(screen, WIDTH, HEIGHT, clock, timer1, False)
        elif gamechoice == 3:
            difficulty = 15
            pop.falling(screen, WIDTH, HEIGHT,
                clock, difficulty, timer1, False)
        elif gamechoice == 4:
            catch.catch(screen, WIDTH, HEIGHT, clock, timer1, False)
        elif gamechoice == 5:
            sidescroll.side(screen, WIDTH, HEIGHT, clock, timer1, False)
        gamesplayed += 1
        gamechoice += 1
        player1.score += 1  # player score to send to arduino
        return gamesplayed
Beispiel #13
0
def game_loop(main_display):
    player = snake.Snake(Position(SQUARE_SIZE, SQUARE_SIZE))
    clock = pygame.time.Clock()
    continue_game = True
    draw_next_player_position(main_display, player)
    apple_x, apple_y = get_random_location()

    while continue_game and player.is_alive:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                continue_game = False

            if event.type == pygame.KEYDOWN:
                player.update_direction(event.key)
                break

        if player.is_colliding(apple_x, apple_y):
            apple_x, apple_y = get_random_location()

        main_display.fill(BACKGROUND_COLOR)
        pygame.draw.rect(main_display, APPLE_COLOR,
                         [apple_x, apple_y, SQUARE_SIZE, SQUARE_SIZE])
        player.move()
        draw_next_player_position(main_display, player)
        pygame.display.update()
        clock.tick(FPS)

    pygame.quit()

    print("Score: {}".format(len(player.positions)))
Beispiel #14
0
def main():
    width = 800
    height = 600
    gridColor = (43, 43, 43)
    frameRate = 10
    gridSize = 20
    gameOver = False
    score = 0

    window = pygame.display.set_mode((width, height))
    clock = pygame.time.Clock()

    ggrid = grid.Grid(gridSize, gridColor, width, height)
    folder = path.dirname(__file__)
    img_path = path.join(folder, 'assets/snake_sprite.png')
    spritesheet = sprites.SpriteSheet(img_path)
    my_snake = snake.Snake(3, (400, 300), gridSize, spritesheet)
    snack = food.Food(width, height, gridSize, spritesheet, (200, 300))

    while not gameOver:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    my_snake.move_left()

                elif event.key == pygame.K_RIGHT:
                    my_snake.move_right()

                elif event.key == pygame.K_UP:
                    my_snake.move_up()

                elif event.key == pygame.K_DOWN:
                    my_snake.move_down()

        # check for game over

        if my_snake.has_hit_wall(width, height):
            gameOver = True

        # check collision between cube and snack
        if hit_food(my_snake, snack):
            snack.move_random()
            my_snake.eat()
            score += 1

        window.fill((0, 0, 0))
        my_snake.move()
        ggrid.draw(window)
        snack.draw(window)
        my_snake.draw(window)
        displayScore(score, window)

        pygame.display.update()
        clock.tick(frameRate)
Beispiel #15
0
def gameScene(state, screen, frameTime, gameClock, diff):
    """this is called when it's time to play the game,
returns the new screen state"""
    # set up player and the game map
    mapRect = pygame.rect.Rect(50, 50, 700, 500)
    player = snake.Snake()
    fruit = food.Food(player.bodyList)
    if diff == 0:
        cooldown = 100
    elif diff == 1:
        cooldown = 75
    elif diff == 2:
        cooldown = 50
    else:
        print("Difficulty selection failed, check the code")
    growSnake = False

    # initialises the score, as well as the font and the rect
    # which is used to define position and size of text (required for drawing)
    score = 0
    scoreText = text.Text("Score: " + str(score), color=(100, 0, 100))

    framesPerSec = text.Text()
    framesPerSec.rect.bottomleft = (0, 600)

    # main game loop of the game, only quits at change of game scene state
    while state == 1:

        frameTime += gameClock.tick(60)

        # logic updates
        if fruit.eaten(player):
            fruit.spawnFood()

            score += 10
            scoreText.text = "Score: " + str(score)

            growSnake = True

        # will only displace the snake if the cooldown is over
        if frameTime >= cooldown:
            growSnake, state = player.update(growSnake, state, mapRect)
            frameTime = 0

        framesPerSec.text = str(gameClock.get_fps())[:6]

        # drawing to the screen
        screen.fill((0, 150, 255))

        pygame.draw.rect(screen, (0, 0, 0), mapRect, 3)

        player.draw(screen)
        fruit.draw(screen)
        scoreText.draw(screen)
        framesPerSec.draw(screen)

        pygame.display.flip()

    return state, score
Beispiel #16
0
def gameRunning():

    running = True
    gameOver = False

    x = width / 2
    y = height / 2
    xspeed = 0
    yspeed = 0

    body = []
    total = 1

    Snake = snake.Snake(height, width, scale)
    Food = food.Food(xspeed, yspeed, scale, width, height)

    while running:

        clock.tick(15)
        surface.fill(black)

        if gameOver:
            surface.fill(black)
            message("OOPS, YOU LOST! Press SPACE-Restart or ESC-Exit", red,
                    blue, surface)
            score(total - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False
                    if event.key == pygame.K_SPACE:
                        gameRunning()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            xspeed, yspeed = Snake.direction(speed, event, xspeed, yspeed)

        gameOver = Snake.checkBoundaries(x, gameOver, y)

        x += xspeed
        y += yspeed

        Food.makeFood(red, surface)

        head = []
        body, head = Snake.createSnake(x, y, head, body, total, white, surface)
        gameOver = Snake.checkSelf(gameOver, head, body)
        score(total - 1)

        pygame.display.update()

        total = Food.isEaten(x, y, total)
        Food.makeFood(green, surface)

    pygame.quit()
    quit()
Beispiel #17
0
def main():
    pygame.init()
    screen_dim = (1360, 768)
    display = pygame.display.set_mode(
        screen_dim,
        FULLSCREEN | HWSURFACE if not sys.gettrace() else HWSURFACE)
    pygame.mouse.set_cursor((8, 8), (0, 0), (0, 0, 0, 0, 0, 0, 0, 0),
                            (0, 0, 0, 0, 0, 0, 0, 0))
    uc = snake.Snake(screen_dim[0] / 3, screen_dim[1] / 2, screen_dim[0],
                     screen_dim[1])
    clock = pygame.time.Clock()
    scene = sky.Sky(screen_dim)
    p1 = player.Player()
    paused = False

    while True:
        paused = listen_keys(p1, paused)
        if paused:
            continue

        if len(scene.enemies) < 50 and random.randint(0, 160) == 0:
            scene.inc_enemies()

        if len(scene.bubbles) == 0 and random.randint(0, 160) == 0:
            scene.inc_bubbles()

        surface = pygame.Surface(screen_dim)

        if p1.turning_left():
            uc.go_left()
        if p1.turning_right():
            uc.go_right()
        if p1.firing():
            uc.fire()
        else:
            uc.stop_firing()

        scene.update(uc.x, uc.y)

        if scene.check_hit(uc):
            uc.hit()

        if scene.check_fed(uc):
            uc.fed()

        scene.draw_background(surface)

        if p1.firing():
            line_start, line_end = uc.draw(surface)
            scene.check_targets(line_start, line_end)
        else:
            uc.draw(surface)

        scene.draw_foreground(surface)

        display.blit(surface, (0, 0))
        pygame.display.flip()

        clock.tick(100)
Beispiel #18
0
    def __init__(self,
                 dim,
                 this_snake=None,
                 foods=None,
                 obstacles=None,
                 should_render=False):
        """
        Initialize the World and a Snake to wander it.

        dim (int, int): Dimension tuple defining the size of the world.
        this_snake (Snake): Snake to wander the World.
        foods: List of coordinate tuples, corresponding to food items
            positioned in the world, which the snake can eat.
        obstacles: List of coordinate tuples, corresponding to
            obstacles in the world, which kill the snake if it
            moves into these.

            ---  NOT IMPLEMENTED YET!  ----

        should_render (bool): Whether the world should be rendered
            using external module (via pygame).
        """
        # define the world
        self.dim = dim
        height, width = self.dim

        # define string representation of the world
        self.EMPTY = ' '
        self.FOOD = 'x'
        self.OBSTACLE = '='

        # define rewards to be given for the snake's actions
        # -> it must be worth getting food across the entire world
        self.FOOD_SCORE = sum(self.dim)
        # -> death must be the least optimal solution
        self.OBSTACLE_SCORE = -self.FOOD_SCORE
        # -> penalize not reaching food
        # -> include both dimensions?
        self.EMPTY_SCORE = -dim[0] / 2
        self.WIN_SCORE = 1000

        # fill the world with content
        self.snake = this_snake
        self.foods = foods
        self.obstacles = obstacles

        if not self.snake:
            self.snake = snake.Snake(self.one_empty_field())
        if self.foods is None:
            self.foods = [self.one_empty_field()]
            #self.foods = []
        if self.obstacles is None:
            self.obstacles = []

        # check whether the world should be rendered using pygame
        self.paused = True
        self.should_render = should_render
        self.vis = visworld.Vis(self.should_render, self.dim)
        self.visualize(verbose=False)
Beispiel #19
0
 def spawn_snake_at(self, positions):
     """
     :param positions: list of (row, col) tuples
     """
     if self.player_snake is not None:
         self.player_snake.remove_from_board()
     self.player_snake = snake.Snake(self)
     self.player_snake.spawn_at(positions)
Beispiel #20
0
 def __init__(self, screen):
     self.score = 0
     self.screen = screen
     self.snake = snake.Snake(self.screen)
     self.food = None
     self.wall_list = None
     self.game_runs = True
     self.start_game()
Beispiel #21
0
 def _init_creatures(self):
     num_enemies = self.level.depth
     for e in range(0, num_enemies):
         position = self._drop_enemy()
         if position is None:
             print("lvl-%d Unable to find open spot for (enemy)." %
                   self.level.depth)
         else:
             enemy = snake.Snake(self.level.creature_map, position)
Beispiel #22
0
    def createObjects(self):
        ''' Cria os objetos da aplicação '''
        return {
            # Objeto da snake
            'snake': snake.Snake(),

            # Fábrica de maçãs
            'apple': apple.Apple(),
        }
 def __init__(self, level):
     self.grid = Grid()
     self.env = np.copy(self.grid.load_level(level))
     self.snake = snake.Snake(self.grid.find_init_snake_head(),
                              self.grid.find_init_snake_tail())
     self.food = Food(self.grid.find_init_food(),
                      self.grid.get_cell_shape())
     self.grid.create_grid()
     self.counter = 0
Beispiel #24
0
def reinitialize():
    global snake_obj
    global food_obj
    global state
    state = Game_state.PLAYING
    snake_obj = snake.Snake()
    food_obj = food.Food(snake_obj)
    score_obj.reset()
    hs_obj.reset()
Beispiel #25
0
    def __init__(self):

        #dimensions
        self.width = 7
        self.height = 7

        #actors
        self.snakeIsdead = False
        self.snake = snake.Snake()
        self.food = food.Food(self.width, self.height)
Beispiel #26
0
    def __init__(self, WIDTH, HEIGHT, x, y):
        self.WIDTH = WIDTH
        self.HEIGHT = HEIGHT
        self.apple_eaten = True
        self.apple_pos = (20, 20)
        self.s = snake.Snake(WIDTH, HEIGHT)

        self.get_food_position(x, y)

        self.apple = pygame.image.load("res\images\_apple.png")
Beispiel #27
0
 def __init__(self,mapSize,tileSize,window,mapColor,snakeColor):
     self._color=mapColor
     self._snakeColor=snakeColor
     self._mapArray=self.Create_map(mapSize,window,tileSize)
     self._snake=snake.Snake(snakeColor,tileSize,window,self._mapArray)
     print(self._mapArray)
     for i in self._mapArray:
         for j in i:
           print(j.Get_pos())
         print("new lists")
Beispiel #28
0
    def setup_game(self):
        # reset
        window = pygame.display.get_surface()
        window_width = window.get_width()
        window_height = window.get_height()

        self.objects["snake"] = snake.Snake(
            [window_width // 2, window_height // 2], palette.GREEN,
            self.block_size)
        self.objects["food"] = self.spawn_food()
        self.score = 0
Beispiel #29
0
 def __init__(self, screen, difficulty, player_name=""):
     super(Default_Game, self).__init__(screen, difficulty)
     self.game_snake = snake.Snake(5, SNAKE_SIZE, 0, 0)
     self.food = snake_food.SnakeFood(SNAKE_SIZE, self.game_snake,
                                      self.tile_height, self.tile_width)
     self.player_name = player_name
     self.passthrough = True
     self.direction_lock = False
     self.score_multiplier = 1
     self.restart()
     self.multiplier_animation_life = 0
     self.start()
Beispiel #30
0
    def __init__(self, board_size):
        self.game_over = False
        self.board_size = board_size

        self.board = bd.Board(board_size)
        self.snake = sn.Snake(board_size)
        self.cookie = ck.Cookie(board_size)

        self.board.add_snake(self.snake.get_snake_head())
        self.generate_cookie()
        self.board.add_cookie(self.cookie.get_cookie())

        self.board.show_board()