Exemplo n.º 1
0
    def join_player(self, player):
        """
        Join a player to the game.
        @player: A Player instance.
        """
        playerCount = len(self.world.players)
        # build up a snake
        snakeData = self.snakeDatas[playerCount]
        snake = Snake(self.world, player)
        snake.gen_body(*snakeData)
        player.snake = snake
        # let the snake's name same as the player's name
        snake.name = player.name
        # add snake and player to the world
        self.world.snakes.append(snake)
        self.world.players.append(player)
        # emit a SNAKE_BORN event
        self.eventMgr.emit(events.SnakeBorn(snake))
        # bind gameevent handlers
        def handler(event):
            snake = event.snake
            food = event.food
            if snake is player.snake:
                snake.player.score += food.score

        self.eventMgr.bind(EventTypes.SNAKE_EAT, handler)
        return player
Exemplo n.º 2
0
 def move(self):
     if self.travel_points:
         self.x, self.y = self.travel_points.pop(0)
     Snake.move(self, by_dir=False)
     #apple location moved, recalculate path to it
     if self.apple.pos != self.apple_loc:
         self.generate_path()
         self.apple_loc = self.apple.pos
Exemplo n.º 3
0
 def __init__(self, width, height):
     Snake.__init__(self, width, height - 5)
     self.travel_points = []
     self.apple_loc = self.apple.pos
     #DEBUG
     #self.f = open('log.out', 'w')
     self.generate_path()
     self.quit = False
     self.start = False
Exemplo n.º 4
0
class Engine(object):

    def __init__(self, world_size=WORLD_SIZE):
        self.world_center = Point((world_size // 2, world_size // 2))
        self.world_size = world_size
        self.snake = Snake(start=self.world_center, start_length=SNAKE_START_LENGTH, growth_pending = GROWTH_PENDING)
        self.level = Level(size=self.world_size, snake=self.snake)
        self.score = 0
        self.controller = Controller(self.level.level_render)

    def reset(self):
        """Start a new game."""
        self.playing = True
        self.score = 0
        self.snake = Snake(start=self.world_center,
                           start_length=SNAKE_START_LENGTH)
        self.level = Level(size=self.world_size, snake=self.snake)
        self.play()

    def update(self, dt):
        """Update the game by dt seconds."""

        self.check_input()
        # time.sleep(dt)
        if self.snake.update():
            self.level.update_level()
            self.level.level_render.draw_text(
                Point((0, 0)), 'Score {}'.format(self.score))
            self.level.show_level()
            head = self.snake.get_head()
            # If snake hits a food block, then consume the food, add new
            # food and grow the snake.
            if head in self.level.food:
                self.eat(head)
            if self.snake.self_intersecting():
                raise GameOver('snake intersecting')
            if head in self.level.blocks:
                raise GameOver('snake try eat block')
        time.sleep(dt)

    def eat(self, head=None):
        print('mmm, tasty')
        self.level.food.remove(head)
        self.snake.grow()
        self.score += len(self.snake) * SEGMENT_SCORE

    def play(self):
        """Play game until the QUIT event is received."""
        while True:
            try:
                self.update(TIME_DELTA)
            except GameOver, err:
                print(str(err))
                print('You score {}'.format(self.score))
                time.sleep(3)
                self.reset()
Exemplo n.º 5
0
def exportSplineImage(size=500, cps=4):
	from snake import Snake
	size = 500
	rnd = lambda: np.random.randint(0, size)
	image = vigra.RGBImage((size, size), value=4.0)
	snake = Snake(image=image)
	snake.addControlPoints(*[(rnd(), rnd()) for i in range(cps)])
	gs = contourCurvatureGradient(snake.contour, snake.controlpoints, snake.crv_energies)
	for i in range(len(gs)):
		image[snake.contour[i][0]][snake.contour[i][1]] = [125*gs[i], 255 - (125*gs[i]), 0]
	vigra.impex.writeImage(image, '/home/max/Desktop/spline_colours.png')
Exemplo n.º 6
0
def main():
  s = Snake()
  clock = pygame.time.Clock()
  signal = [SIG_NOOP] # it's an array to make sure Snake.run() actually modifies THIS, instead of making a copy and discarding it when it goes out of scope
  while 1:
    WINDOW.fill(s.background_color)
    s.run(signal)
    if signal[0]: break
    pygame.display.update()
    clock.tick(FPS)
  if signal[0] == SIG_QUIT:
    pygame.quit()
    exit()
  elif signal[0] == SIG_RESTART:
    main()
Exemplo n.º 7
0
 def __init__(self, world_size=WORLD_SIZE):
     self.world_center = Point((world_size // 2, world_size // 2))
     self.world_size = world_size
     self.snake = Snake(start=self.world_center, start_length=SNAKE_START_LENGTH, growth_pending = GROWTH_PENDING)
     self.level = Level(size=self.world_size, snake=self.snake)
     self.score = 0
     self.controller = Controller(self.level.level_render)
Exemplo n.º 8
0
    def __init__(self):
        secure_screen_size()
        pg.init()               # initialize pygame module

        pg.display.set_caption('PySnake Game')

        # height of upper bound line of the drawing frame
        self._snake_width = FRAME_SIZE/FRAME_WIDTH_TO_SNAKE_WIDTH
        # make main screen surface a little bit higher (for score text)
        self._screen = pg.display.set_mode((FRAME_SIZE, FRAME_SIZE + self._snake_width * 2))

        # make a subsurface from screen surface. It will be rectangle where snake will move
        self._frame = self._screen.subsurface([0, self._snake_width*2, FRAME_SIZE, FRAME_SIZE])

        # set of all grid fields: range for x and y go from 0 to SCREEN_WIDTH_TO_SNAKE_WIDTH - 1
        # it will be used to pick a place for draw mouse for snake to chase
        self._grid_field_list = [(x, y) for x in xrange(FRAME_WIDTH_TO_SNAKE_WIDTH) for y in xrange(FRAME_WIDTH_TO_SNAKE_WIDTH)]
        self._grid_field_size = self._screen.get_width() / FRAME_WIDTH_TO_SNAKE_WIDTH   # in pixels

        # initialize font
        self._font = pg.font.SysFont("monospace", self._snake_width*2 - 3)

        # create snake
        self._snake = Snake(self._frame, self._snake_width)

        # Clock object is used to slow down and main loop, it ensures the FPS
        self._clock = pg.time.Clock()

        # default speed of the game
        self._speed = 10
        # default speed increment when snake catches mouse
        self._speed_inc = 3
        # increment score when snake catches the mouse
        self._score = 0
Exemplo n.º 9
0
class Game(object):

    _gamespeed = 0.6
    _snake = None
    _gameboard = None
    _screen = None

    def __init__(self):
        # Create the screen object
        curses.initscr()
        self._screen = curses.newwin(20, 20, 0, 0) #curses.initscr()
        self._screen.keypad(1)
        self._screen.nodelay(1)
        self._screen.timeout(150)
        self._screen.border(1)


        curses.noecho()
        curses.cbreak()

        self._gameboard = Gameboard((20, 20), self._screen)
        self._snake = Snake(self._gameboard)

    def run(self):
        key = KEY_RIGHT
        try:
            while 1:
                event = self._screen.getch()
                key = key if event == -1 else event
                s = None

                if key == KEY_UP:
                    s = SnakeMoveDirection.up
                elif key == KEY_DOWN:
                    s = SnakeMoveDirection.down
                elif  key == KEY_LEFT:
                    s = SnakeMoveDirection.left
                elif key == KEY_RIGHT:
                    s = SnakeMoveDirection.right

                self._snake.move(s)
                self._gameboard.draw()
        finally:
            curses.echo()
            curses.nocbreak()
            curses.endwin()
Exemplo n.º 10
0
    def load_from_json(self,string):
        """FIXME: this happens for all maps on startup"""
        struct = json.loads(string)

        ## load min_moves
        if "min_moves" in struct.keys():
            self.min_moves = struct["min_moves"]
        else:
            self.min_moves = -1

        self.map = Map(coordinates=struct['map'])
        self.snakes = []
        for sj in struct['snakes']:
            snake = Snake(self.map, sj['color'], None)
            snake.elements = Snake.make_elements(sj['elements'],snake)
            snake.assign_to_tiles()
            self.snakes.append(snake)
 def __init__(self, gridWidth, gridHeight):
     self.gridWidth = gridWidth
     self.gridHeight = gridHeight
     self.food = Space(randint(0, gridWidth - 1), randint(0, gridHeight - 1))
     self.traindata = []
     self.state = None
     self.alive = True
     self.snake = Snake(self)
Exemplo n.º 12
0
 def __init__(self, parent):
     super(SnakeWidget, self).__init__(parent)
     self.snake = Snake()
     self.newGame()
     self.colors = [QtGui.QColor(255, 0, 0, 255),
                    QtGui.QColor(255, 255, 0, 255),
                    QtGui.QColor(0, 0, 255, 255),
                    QtGui.QColor(0, 255, 0, 255)]
Exemplo n.º 13
0
class World():

    def __init__(self):
        self.mc = minecraft.Minecraft.create()
        self.apple = None
        self.snake = Snake(self.mc)

    def get_player_pos(self):
        return self.mc.player.getTilePos()

    def get_apple_pos(self):
        return self.apple

    def place_apple(self, x, z):
        self.remove_apple()
        y = self.mc.getHeight(x,z)
        self.mc.setBlock(x, y, z, 35, 14)
        self.apple = Vec3(x,y,z)

    def remove_apple(self):
        if self.apple is None:
            return

        self.mc.setBlock(self.apple.x, self.apple.y, self.apple.z, 0)
        self.apple = None

    def check_collision(self):
        pos = [floor(axis) for axis in self.get_player_pos()]
        center = Vec3(pos[0], pos[1], pos[2])
        for offset in shell:
            block = center + offset
            if (block.x, block.y, block.z) in list(self.snake.body)[3:]:
                return True
        return False

    def move_snake(self):
        new_pos = self.get_player_pos()
        new_pos = tuple([floor(i) for i in new_pos])
        self.snake.update(new_pos)

    def extend_snake(self):
        self.snake.extend()

    def post(self, message):
        self.mc.postToChat(message)
        print(message)
Exemplo n.º 14
0
 def reset(self):
     """Start a new game."""
     self.playing = True
     self.score = 0
     self.snake = Snake(start=self.world_center,
                        start_length=SNAKE_START_LENGTH)
     self.level = Level(size=self.world_size, snake=self.snake)
     self.play()
class Snakegame:
    def __init__(self, gridWidth, gridHeight):
        self.gridWidth = gridWidth
        self.gridHeight = gridHeight
        self.food = Space(randint(0, gridWidth - 1), randint(0, gridHeight - 1))
        self.traindata = []
        self.state = None
        self.alive = True
        self.snake = Snake(self)
    
    def step1(self):
        square = self.snake.step1()
    
    def step2(self, gridWidth, gridHeight):
        self.snake.step2()
        if self.snake.hitFood(self.food):
            self.food = Space(randint(0, self.gridWidth - 1), randint(0, self.gridHeight - 1))
            self.snake.fat(3)
        if self.snake.isDead(gridWidth, gridHeight):
            self.alive = False
    
    def draw(self, screen, squareSize):
        for space in self.snake.spaces:
            pygame.draw.rect(screen, Color.YELLOW, (space.x * squareSize, space.y * squareSize, squareSize, squareSize))
        pygame.draw.rect(screen, Color.RED, (self.food.x * squareSize, self.food.y * squareSize, squareSize, squareSize))
Exemplo n.º 16
0
def main():
    # ---Initialize Screen---
    screen = pygame.display.set_mode((300, 275), 0, 32)
    pygame.display.set_caption('Snake')

    mainMenu = ('Play Game', 'High Scores', 'Settings', 'Quit')
    backgroundColor = (255, 255, 255)

    settings = {'snakeLength':5, 'fontName':'inconsolata.otf',
                'foodColor':(255,0,0)}

    #List of tuples formatted (user, score)
    highScoreList = []

    readScoresFromFile(highScoreList)
    sortScores(highScoreList)
    mainMenu = SingleColumnMenu(screen, mainMenu, fontName = settings['fontName'])
    while(True):
        choice = mainMenu.run()
        if choice == 'Play Game':
            #Create instance of Snake.py
            snake = Snake(screen)

            displayCountdown(screen, backgroundColor)

            #Runs game and returns player score
            newScore = snake.gameLoop()

            #Prompts user for name
            userName = getUsername(screen, backgroundColor, settings)

            #Adds to high Scores
            highScoreList.append((userName, newScore))
            sortScores(highScoreList)

        elif choice == 'High Scores':
            highScores = ScoreDisplay(screen, highScoreList,
                            fontName = settings['fontName'])
            #highScores.setFont(settings['fontName'])
            highScores.run()
        elif choice == 'Quit':
            break
        choice == ""
    saveScoresToFile(highScoreList)
Exemplo n.º 17
0
 def reset(self):
     ''' Start a new game
     '''
     self.playing = True
     self.next_direction = DIRECTION_UP
     self.score = 0
     self.snake = Snake(self.world.center, SNAKE_START_LENGTH)
     self.food = set()
     self.add_food()
     return
Exemplo n.º 18
0
Arquivo: game.py Projeto: Dront/snake
    def __init__(self):
        self.state = State.RUN

        self.player = Snake()
        self.run_snake_timer()

        self.map = Map(filename=params["DEFAULT_MAP"])

        self.fruit = pygame.sprite.GroupSingle()
        self.fruit.add(self.create_fruit())
Exemplo n.º 19
0
def move():
    data = bottle.request.json
    #print "Received move ..." #request:{}".format(data)
    
    my_id = data["you"]
    board_width = data['width']
    board_height = data['height']
    snakes = data["snakes"]
    snake = "yo"
    for snake in snakes:
        if snake["id"] == my_id:
            our_snake = snake

    me = Snake(my_id, board_height, board_width)

    #print "Created snake with id = ", my_id 

    #blockades =  map(lambda x: extend_head(x,me), data["snakes"])
    blockades = []
    for snake in data["snakes"]:
        temp = extend_head(snake, me)
        print "Snake coords: {}".format(temp)
        blockades.extend(temp)

    print "No go before: {}".format(blockades)
    #blockades = blockades[0]
    print "No go areas: {}".format(blockades)
    
    #TODO limit based to first N food or based on threshold
    food = map(tuple, data["food"])
    #print "Food @ {}".format(food)
    #food.sort(lambda xy: abs(xy[0] - me.head[0]) + abs(xy[1] - me.head[1])) 
    food.sort(key=lambda xy: abs(xy[0] - me.head[0]) + abs(xy[1] - me.head[1])) 
    food = food[:3]
    #print "Food @ {}".format(food)

    
    move = me.gather_food(food, blockades)

    return {
        'move': move, #random.choice(directions),
        'taunt': random.choice(taunts)
    }
Exemplo n.º 20
0
    def __init__(self):
        """Constructor"""
        self.speed = START_SPEED

        # will increase game speed every 10 times we eat
        self.eaten = 0

        # defining the outer wall blocks
        self.wallblock = pygame.Surface((
            BLOCK_SIZE,
            BLOCK_SIZE,
        ))
        self.wallblock.set_alpha(255)
        self.wallblock.fill(BLUE)

        self.wallblockdark = pygame.Surface((
            BLOCK_SIZE_INNER,
            BLOCK_SIZE_INNER,
        ))
        self.wallblockdark.set_alpha(255)
        self.wallblockdark.fill(BLUE_DARK)

        # initialize pygame, clock for game speed and screen to draw
        pygame.init()

        # initializing mixer, sounds, clock and screen
        pygame.mixer.init()
        self.eatsound = pygame.mixer.Sound("snakeeat.wav")
        self.crashsound = pygame.mixer.Sound("snakecrash.wav")
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((
            (WIDTH + 2) * BLOCK_SIZE,
            (HEIGHT + 2) * BLOCK_SIZE,
        ))
        pygame.display.set_caption("snake")
        font = pygame.font.SysFont(pygame.font.get_default_font(), 40)
        self.gameovertext = font.render("GAME OVER", 1, WHITE)
        self.starttext = font.render("PRESS ANY KEY TO START", 1, WHITE)
        self.screen.fill(BLACK)

        # we need a snake and something to eat
        self.snake = Snake(self.screen, WIDTH // 2, HEIGHT // 2)
        self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1)

        # food should not appear where the snake is
        while self.food.get_pos() in self.snake.pos_list:
            self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1)

        # only queue quit and and keydown events
        # pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN])
        pygame.event.set_blocked([
            pygame.MOUSEMOTION,
            pygame.MOUSEBUTTONUP,
            pygame.MOUSEBUTTONDOWN,
        ])
Exemplo n.º 21
0
 def __init__(self, tk, speed):
     self.food = (randint(0, 20), randint(0, 20))
     self.speed = speed
     self.snake = Snake()
     self.tk = tk
     self.button = Button(tk, text="start game!", command=self.run)
     self.canvas = Canvas(tk, width=410, height=410, bg="black")
     self.button.pack()
     self.canvas.pack()
     self.tk.bind("<KeyPress-Up>", self.up_event)
     self.tk.bind("<KeyPress-Down>", self.down_event)
     self.tk.bind("<KeyPress-Right>", self.right_event)
     self.tk.bind("<KeyPress-Left>", self.left_event)
Exemplo n.º 22
0
 def start(self):
     self.snek = Snake(
         self.screen,
         6,
         self.calc_start_loc()
     )
     self.snek.render()
     while self.RUNNING:
         try:
             time.sleep(self.speed)
             self.tick()
         except KeyboardInterrupt:
             self.RUNNING = False
Exemplo n.º 23
0
class SnakeTkinterGame:

    def __init__(self):
	cols = 50
	rows = 50
	side = 10

	self.snake = Snake()

	self.game = Game(cols, rows)
	self.game.add_snake(self.snake)
	self.game.start()

	self.w = Tkinter.Tk()
	self.c = Tkinter.Canvas(self.w,
				width=side*cols,
				height=side*rows,
				background='black')
	self.c.pack()

	self.view = SnakeTkinterView(self.c, side, self.game)
	self.view.add_action_listener(self)

	for key in ["<Left>", "<Right>", "<Up>", "<Down>"]:
	    self.w.bind(key, self.view.got_key)

    def turn_action(self, direction):
	self.snake.turn(direction)

    def tick(self):
	self.game.tick()
	self.view.draw()
	self.c.after(100, self.tick) # keep going

    def run(self):
	self.view.draw()
	self.c.after(100, self.tick)
	self.c.mainloop()
Exemplo n.º 24
0
 def __init__(self, screen):
     Screen.__init__(self, screen)
     
     self.snake = Snake()
     self.snake_dir = Directions.RIGHT
     self.inPause = False
     self.pauseImg = pygame.image.load('assets/img/pause.png').convert();
     self.pauseImg.set_colorkey(Defines.COLORKEY)
     self.apple = (20,20)
     self.score = 0;
     self.font = pygame.font.Font("assets/fonts/blogger-sans.ttf", 24)
     self.fontL = pygame.font.Font("assets/fonts/blogger-sans.ttf", 48)
     self.scoretxt = self.font.render("score %d" % self.score, True, (0, 0, 0))
     self.txtloose = self.fontL.render("You Loose", True, (0, 0, 0))
Exemplo n.º 25
0
def run_game(game_display):
    """Game loop."""

    game = Game(game_display)

    # Create snake
    player = Snake('s1', display.GREEN, game.get_random_location())
    game.snakes.append(player)

    while game.active:

        # Draw all objects
        game.draw_all()

        # Move snake
        for snake in game.snakes:
            snake.move()

        # Check if the game ended for one of the snakes
        for snake in game.snakes:
            if game.boundariesCollision(snake):
                snake.alive = False

        for event in pygame.event.get():

            # Check if user wants to quit the game
            if events.check_quit(event):
                sys.exit(pygame.quit)

            # Change snake direction if key event occurred
            player.direction = events.change_snake_direction(event, player)

        # Checks if the game ended
        if game.ended():
            game.active = False
            game.showStats()
Exemplo n.º 26
0
    def __init__(self):
        # Create the screen object
        curses.initscr()
        self._screen = curses.newwin(20, 20, 0, 0) #curses.initscr()
        self._screen.keypad(1)
        self._screen.nodelay(1)
        self._screen.timeout(150)
        self._screen.border(1)


        curses.noecho()
        curses.cbreak()

        self._gameboard = Gameboard((20, 20), self._screen)
        self._snake = Snake(self._gameboard)
Exemplo n.º 27
0
 def test_set_x_y(self):
     """Test that snake x and y coordinates correctly updated."""
     snake = Snake([0, 0])
     # Check that x and y coordinate changes are correct
     x, y = 0, 0
     snake.direction = 'U'
     x, y = snake.set_x_y()
     self.assertEqual(x, 0)
     self.assertEqual(y, -1)
     snake.direction = 'D'
     x, y = snake.set_x_y()
     self.assertEqual(x, 0)
     self.assertEqual(y, 1)
     snake.direction = 'R'
     x, y = snake.set_x_y()
     self.assertEqual(x, 1)
     self.assertEqual(y, 0)
     snake.direction = 'L'
     x, y = snake.set_x_y()
     self.assertEqual(x, -1)
     self.assertEqual(y, 0)
Exemplo n.º 28
0
 def _restart(self):
     self.pause = True
     for b in self._bricks:
         b.remove_node()
     self._snake = Snake(
         body=_make_default_body(),
         vector=settings.POS_X,
         dot=complex()
     )
     self._snake.gen_dot()
     self._bricks = deque()
     self._update_dot()
     self._draw_snake()
     taskMgr.remove("GameLoop")
     self._game_task = taskMgr.add(self._game_loop, "GameLoop")
     self._game_task.last = 0
Exemplo n.º 29
0
 def __init__(self, game, config):
     self.game = game
     self.pid = config['id']
     self.color = config['color']
     self.snake = Snake(game, game.get_spawnpoint(),
                        config['tex'], self.pid, self.snake_killed)
     self._lifes = INIT_LIFES
     self.points = 0
     self._boost = INIT_BOOST
     self.boosting = False
     self.weapons = deque((
         Weapon(self.game, self, STD_MG),
         Weapon(self.game, self, H_GUN),
         Weapon(self.game, self, PLASMA_GUN)))
     self.pwrup_targets = {'points': 'points', 'grow': 'snake.grow',
                           'speed': 'snake.speed', 'boost': 'boost',
                           'lifes': 'lifes', 'hp': 'snake.hitpoints'}
Exemplo n.º 30
0
    def __init__(self, mlhost, mlport):
        """
        Create a screen and define some game specific things.
        """
        pymlgame.init()
        self.screen = pymlgame.Screen(mlhost, mlport, 40, 16)
        self.clock = pymlgame.Clock(15)

        part = (int(self.screen.width / 2), int(self.screen.height / 2))
        self.snake = Snake([(part[0] - 2, part[1]), (part[0] - 1, part[1]),
                            part], RIGHT, (self.screen.width, self.screen.height))
        self.gameover = False
        self.apple = self.generate_apple()
        self.apple_surface = pymlgame.Surface(1, 1)
        self.apple_surface.draw_dot((0, 0), GREEN)
        self.oldapple = self.apple
        self.score = 0
        self.highscore = self.get_highscore()
Exemplo n.º 31
0
 def new_snake(self, game_settings, world, color):
     self.snake = Snake(game_settings, world, color)
Exemplo n.º 32
0
def play():
    pygame.init()  # инициализируем библиотеку pygame
    window = pygame.display.set_mode((441, 480))  # создание окна c размером
    pygame.display.set_caption("Змейка")  # задаём название окна
    control = Control()
    snake = Snake()
    bot = Bot()
    #is_basic True -- запуск обычный, False -- запуск рандомной карты из файлов
    gui = Gui(is_basic=False)
    food = Food()
    gui.init_field()
    food.get_food_position(gui, snake.body, bot.body)
    var_speed = 0  # переменная для регулировки скорости выполнения программы

    #gui.create_image()

    while control.flag_game:
        gui.check_win_lose(snake.body)
        control.control()
        window.fill(pygame.Color(
            "Black"))  # закрашивание предыдущего квадрата чёрным цветом
        if gui.game == "GAME":  # если флаг равен "GAME"
            snake.draw_snake(
                window)  # то вызываем метод отрисовки змеи на экране
            bot.draw_snake(window)  #отрисовка бота-змеи
            if (food.timer <= 0):  # проверка на жизнь еды
                food.get_food_position(gui, snake.body, bot.body)
            food.draw_food(window)  # и метод отрисовки еды
        elif gui.game == "WIN":  # если флаг равен "WIN"
            if (bot.points <=
                    snake.points):  #проверка очков, кто больше набрал
                gui.draw_win(window)
            else:
                gui.draw_lose(window)
        elif gui.game == "LOSE":  # если флаг равен "LOSE"
            gui.draw_lose(window)  # то отрисовываем избражение поражения
        gui.draw_indicator(window)
        gui.draw_level(window)
        if var_speed % 50 == 0 and control.flag_pause:  # если делится без остатка, то производим изменение координаты квадрата and реакция на паузу
            snake.moove(control.flag_direction)
            snake.check_barrier(gui)

            mv = ""  #проверка бота, все ли работает правильно (можно убрать, но так спокойнее)
            try:
                mv = bot.move(food.food_position, gui.level)
            except:
                mv = bot.move(food.food_position, gui.level)
            #print(mv)
            bot.moove(mv)
            #не трубуется, тк бот никогда к ним не подлезет bot.check_barrier(gui)
            #проверка на съедение и генерация новой еды вне тела змеи
            if snake.eat(food, gui) or bot.eat(food, gui):
                food.get_food_position(gui, snake.body, bot.body)

            bot.check_end_window()
            snake.check_end_window()
            bot.animation()
            snake.animation()
        var_speed += 1
        pygame.display.flip()  # метод отображения окна
Exemplo n.º 33
0
pygame.init()

RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

fps = 3
fpsClock = pygame.time.Clock()

WIDTH, HEIGHT = 720, 720
screen = pygame.display.set_mode((WIDTH, HEIGHT))

#  create snake and game instances
_snake = Snake((90, 90, 90))
game = Game(WIDTH, HEIGHT, 20, _snake, screen)

while game.run:
    moved = False
    for event in pygame.event.get():
        # print(event)
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.KEYDOWN:
            if event.key == K_UP:
                print('UP')
                _snake.move('UP')
            if event.key == K_DOWN:
Exemplo n.º 34
0
from snake import Snake
from food import Food
from scoreboard import Scoreboard

# CONSTANTS
SPEED = 0.07

# set up screen
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)

# initialize snake
snake = Snake()

# initialize food
food = Food()

# initialize scoreboard
scoreboard = Scoreboard()


def main():
    screen.listen()

    # listen to keys. Turn snake
    screen.onkey(snake.up, "Up")
    screen.onkey(snake.down, "Down")
    screen.onkey(snake.left, "Left")
Exemplo n.º 35
0
import sys
from snake import Snake
from background import Background
from food import Food

pygame.init()
screen_width = 1000
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
white = (255, 255, 255)
background = Background(surface=screen,
                        screen_width=screen_width,
                        screen_height=screen_height)
snake = Snake(surface=screen,
              screen_width=screen_width,
              screen_height=screen_height,
              bg_rect_height=background.rect_height)
food = Food(surface=screen,
            screen_width=screen_width,
            screen_height=screen_height,
            bg_rect_height=background.rect_height)

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

    keys = pygame.key.get_pressed()

    snake.get_direction(keys=keys)
Exemplo n.º 36
0
class Game:
    def __init__(self, height, width, board_symbol, snake_symbol):
        self.height = height
        self.width = width
        self.board = []
        self.apple = Apple(width, height)
        self.score = 0
        self.boarddimesionarray = []
        self.boarddimesionarray.append(self.width)
        self.boarddimesionarray.append(self.height)

        # Generate board
        i = 0
        while i < self.width:
            l = [board_symbol] * self.height
            self.board.append(l)
            i += 1

        self.snake = Snake(snake_symbol, self.boarddimesionarray)

    def render(self):
        # Snake growth

        #subprocess.call("clear")
        #os.system("cls")
        os.system('cls' if os.name == 'nt' else 'clear')
        print("Current score: " + str(self.score))
        i = 0
        print(" -" * (len(self.board) - 3))
        while i < len(self.board):
            print("| ", end='')

            if self.snake.snake_position_height() == i:
                snakeOnThisLine = True
            else:
                snakeOnThisLine = False

            if self.apple.apple_position_height() == i:
                appleOnThisLine = True
            else:
                appleOnThisLine = False

            # Inner list
            subCounter = 0
            for subList in self.board[i]:
                for char in subList:
                    if snakeOnThisLine:
                        #for snakepositions in self.snake.positionUpdated:
                        # if self.snake.positionUpdated[0][1] == subCounter:
                        #     print(subCounter)
                        #     self.snake.print()
                        #     snakeOnThisLine = False
                        #     continue

                        if self.snake.snake_position_width() == subCounter:
                            self.snake.print()
                            snakeOnThisLine = False
                            continue
                    if appleOnThisLine:
                        if self.apple.apple_position_width() == subCounter:
                            self.apple.print()
                            snakeOnThisLine = False
                            continue
                    print(char, end='')

                subCounter += 1

            print(" |")
            i += 1
        print(" -" * (len(self.board) - 3))

        if self.apple.position[0] == self.snake.position[
                0] and self.apple.position[1] == self.snake.position[1]:
            self.apple.update_apple_position()
            self.score += 1
            print("SCORE!")

    def update_snake_position(self, move):
        self.snake.update_position(move)
Exemplo n.º 37
0
from food import Food
from level import Level
from arrow import Arrow
from random import randint

# Code For Screen

screen = Screen()
screen.screensize(400, 400)
screen.bgcolor('black')
screen.tracer(0)
screen.listen()
screen.title("Welcome To Snake Vs Hunters")

# Setup for Snake
obj_snake = Snake()
my_snake = obj_snake.snake

# Setup for Food
food = Food()

# Setup Level Board
level = Level()

# Setup and move Arrow
arrows = []


def move_arrows():
    for arrow in arrows:
        arrow.forward(10)
Exemplo n.º 38
0
    def run(self):

        # Setting the Keybindings
        self.setMainKeybindings()

        # Main Run Loop
        while True:

            # Updating Screen
            self.window.update()

            # Showing predicted Path
            if self.showingPath and self.path:
                self.show.clear()
                self.show.pu()
                self.show.goto(self.path[0])
                self.show.pd()
                for node in self.path:
                    self.show.goto(node)

            # Pausing and Playing
            if self.play: continue

            # Speed loop
            for _ in range(self.playSpeed):

                # Frame Counting
                self.frame += 1
                self.runFrame += 1

                # Frame Rate Calculator
                self.currentTime = time.time()
                if self.currentTime - self.startTime >= 1:
                    if self.gettingFrameRate:
                        print(f'FPS: {self.runFrame}')
                    self.runFrame = 0
                    self.startTime = time.time()
                    self.gettingFrameRate = False

                # Algorithms

                # self.path = self.snake.getPathFromAstar()
                # self.path = self.snake.pathShortcutHamilton()
                self.path = self.snake.shortcutHamilton()

                # Updating and Showing Snake
                self.snake.run()

                # Resetting Snake
                if self.snake.dead:
                    self.snake = Snake(self.grid)

                # Updating Score in Title
                self.window.title(
                    f"Snake Game Algorithm  -  Score: {self.snake.drawnLength}"
                )

                # Manually Playing
                # self.manualGameplay()

        # Ending Program
        self.window.mainloop()
Exemplo n.º 39
0
import pygame
from snake import Snake
from cube import Cube
from randomSnack import randomSnack
from drawGrid import drawGrid
from snakeSense import *

pygame.init()
fps = 10
clock = pygame.time.Clock()
rows = 15
width = 510
height = 510
player = Snake([69, 35], (255, 255, 255), width // rows)
snack = Cube(randomSnack(rows, player, width // rows),
             0,
             0,
             width // rows - 1,
             color=(255, 0, 0))
screen = pygame.display.set_mode((width, height))
#senses = snakeSenses(player, snack, width, width // rows, screen)

running = True
while running:

    screen.fill((0, 0, 0))
    if player.body[0].pos == snack.pos:
        player.addCube()
        snack = Cube(randomSnack(rows, player, width // rows),
                     0,
                     0,
Exemplo n.º 40
0
from turtle import Screen
from snake import Snake
import time
from food import Food
from score import ScoreBoard
screen = Screen()
screen.tracer(0)
screen.setup(width=600, height=600)
screen.bgcolor("black")
is_game_on = True

snake = Snake()
food = Food()
score = ScoreBoard()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.right, "Right")
screen.onkey(snake.left, "Left")

while is_game_on:
    screen.update()
    time.sleep(0.1)
    snake.move_forward()

    if snake.head.distance(food) < 15:
        food.refresh()
        score.score_refresh()
        snake.extend()

    if snake.head.xcor() > 290 or snake.head.ycor() > 290 or snake.head.xcor(
Exemplo n.º 41
0
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)

snake = Snake()
food = Food()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_over = False
while not game_over:
    screen.update()
    time.sleep(0.1)
    snake.move()

    # Detect collision with wall
    if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor(
    ) > 280 or snake.head.ycor() < -280:
Exemplo n.º 42
0
size = [800, 600]
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Snake Game')

# Frame
clock = pygame.time.Clock()
Frame = 30  # 30 frames per second

# game parameters / create token and snake
init_length = 5
width = 10
end = False
done = False
token_num = 5
tokens = MyTokens(size[0], size[1], width, token_num)
snake = Snake((size[0] / 2), (size[1] / 2), 1, 'N', init_length, width)

# Font create
score_font = pygame.font.SysFont('Comic Sans MS', 20)
score_surface = score_font.render('Score: {}'.format(snake.score), False,
                                  (255, 255, 255))
end_font = pygame.font.SysFont('Comic Sans MS', 50)
end_surface = end_font.render('GAME OVER', False, (255, 255, 255))
ask_font = pygame.font.SysFont('Comic Sans MS', 20)
ask_surface = ask_font.render('Restart (r) or Quit (esc)', False,
                              (255, 255, 255))

# Entire game window
while not end:
    # One game
    while not done:
Exemplo n.º 43
0
    '..................................................',
    '.#################################################',
    '.............................x..x.................',
    '#################################################.',
    '.....................x...........................x',
    '#################################################.',
    '............x.....................................',
    '#################################################.',
    '..................................................',
    '.#################################################',
    '..0...............................................',
    '#################################################.'
]
level_hoogte = 12
level_breedte = 50
snakes = [Snake([(2, 10)])]
speler_nummer = 0
aantal_spelers = 1
aantal_voedsel = 5
voedsel_posities = [(29, 2), (32, 2), (21, 4), (49, 4), (12, 6)]

#We kennen een waarde toe aan alle muren
#Deze moet overgezet worden in het bestand waarin het gebruikt wordt.
wall_value = 1000

#Algemene flow van het programma zoals het nu gevormd is:
#1: mapLevel(). Vanaf het hoofd van onze slang worden de afstanden naar alle vakjes en bijbehorende paden berekend.
#2: mapFood(). Eerst wordt een lijst gecre\"eerd van alle hoofden naar al het voedsel,
#   daarna wordt uit die lijsten gekeken waar wij het dichtst bij zijn.
#   Return is de locaties van voedsel waar wij het dichtst bij zijn, en hoe veel verder de eerstvolgende is.
#3: mapHeat(). We cre\"eren een heatmap waarin de muren en slangen allemaal bronnen zijn.
Exemplo n.º 44
0
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Score
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.title("Snake Game")
screen.bgcolor("black")
screen.tracer(0)

snake = Snake()
food = Food()
score = Score()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_is_on = True

while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    # detect collision with food and updating score
Exemplo n.º 45
0
from config import DISPLAY_SIZE, MAP_SIZE, INITIAL_LENGTH, FPS

INITIAL_LENGTH = 4
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

# Basic setup
pygame.init()
screen = pygame.display.set_mode(DISPLAY_SIZE)
pygame.display.set_caption('Snake')
clock = pygame.time.Clock()

background = pygame.Surface(screen.get_size()).convert()

snake = Snake(background)

# Main loop
while snake.alive:
    # Reset screen
    background.fill(BLACK)

    for event in pygame.event.get():
        if event.type == QUIT or \
                (event.type == KEYDOWN and event.key == K_ESCAPE):
            snake.alive = False

        elif event.type == KEYDOWN and event.key in snake.key_to_direction:
            direction = snake.key_to_direction[event.key]
            if direction is not snake.invalid_direction:
                snake.direction = direction
Exemplo n.º 46
0
class Game:

    # Initializing Variables
    def __init__(self):

        # Screen Sizes
        self.scl = 40  # Scale
        self.rows = 20  # Width
        self.cols = 30  # Height
        self.bord = 5  # Fold

        # Screen Sizes
        self.width = self.cols * self.scl
        self.height = self.rows * self.scl
        self.sclh = self.scl / 2

        # Initializing Start Variables
        self.playSpeed = 1
        self.frame = 0
        self.runFrame = 0
        self.startTime = time.time()

        # Showing Screen Variables
        self.gettingFrameRate = False
        self.showingPath = False
        self.showingHCycle = False
        self.play = False

        # Calculated Algorithm Path
        self.path = []

        # Main Screen Setup
        self.window = turtle.Screen()
        self.window.setup(self.width + 50, self.height + 50)
        self.window.title("Snake Game Algorithme")
        self.window.bgcolor('#141414')
        self.window.tracer(0)

        # Registering Scaled Square Shape
        self.window.register_shape(
            'scaled-square',
            ((-self.sclh + self.bord, self.sclh - self.bord),
             (self.sclh - self.bord, self.sclh - self.bord),
             (self.sclh - self.bord, -self.sclh + self.bord),
             (-self.sclh + self.bord, -self.sclh + self.bord)))

        # Generating Arena Grid Map
        self.grid = Grid(self.cols, self.rows, self.scl)
        self.cells = self.grid.createGrid()
        self.grid.drawBorder('red')

        # Generating Hamiltonian Cycle
        self.hc = HamiltonianCycle(self.grid)
        self.hCycle = self.hc.generateHamiltonianCycle()
        self.grid.hCycle = self.hCycle
        self.grid.bord = self.bord

        # Creating Main Snake Object
        self.snake = Snake(self.grid)

        # Showing Algorithm Path Pen
        self.show = turtle.Turtle()
        self.show.pu()
        self.show.ht()
        self.show.color('blue')
        self.show.width(4)

    # Speeding Up Run
    def speedUp(self):
        self.playSpeed = 10

    # Slowing Down Run
    def slowDown(self):
        self.playSpeed = 1

    # Showing Predicted Path
    def showPath(self):
        self.showingPath = not self.showingPath
        self.show.clear()

    # Pausing and Playing
    def pausePlay(self):
        self.play = not self.play

    # Showing and Hiding HamiltonianCycle
    def showHCycle(self):
        self.showingHCycle = not self.showingHCycle
        if self.showingHCycle:
            self.hc.show(False, True, False)
        else:
            self.hc.clear()

    # Manual Gameplay Keybindings
    def manualGameplay(self):
        self.clearManualMovement()
        self.window.listen()
        self.window.onkey(self.snake.up, "Up")
        self.window.onkey(self.snake.down, "Down")
        self.window.onkey(self.snake.left, "Left")
        self.window.onkey(self.snake.right, "Right")
        time.sleep(0.05)

    # Clearing mutiple movements per Frame
    def clearManualMovement(self):
        self.window.onkey(None, "Up")
        self.window.onkey(None, "Down")
        self.window.onkey(None, "Left")
        self.window.onkey(None, "Right")

    # Getting Frame Rate
    def frameRate(self):
        self.gettingFrameRate = not self.gettingFrameRate

    # Main Simulation Keybindings
    def setMainKeybindings(self):
        self.window.listen()
        self.window.onkeypress(self.speedUp, 'space')
        self.window.onkeyrelease(self.slowDown, 'space')
        self.window.onkey(self.showPath, 'p')
        self.window.onkey(self.pausePlay, 's')
        self.window.onkey(self.frameRate, 'f')
        self.window.onkey(self.showHCycle, 'h')

    # Main Compiling Run Function
    def run(self):

        # Setting the Keybindings
        self.setMainKeybindings()

        # Main Run Loop
        while True:

            # Updating Screen
            self.window.update()

            # Showing predicted Path
            if self.showingPath and self.path:
                self.show.clear()
                self.show.pu()
                self.show.goto(self.path[0])
                self.show.pd()
                for node in self.path:
                    self.show.goto(node)

            # Pausing and Playing
            if self.play: continue

            # Speed loop
            for _ in range(self.playSpeed):

                # Frame Counting
                self.frame += 1
                self.runFrame += 1

                # Frame Rate Calculator
                self.currentTime = time.time()
                if self.currentTime - self.startTime >= 1:
                    if self.gettingFrameRate:
                        print(f'FPS: {self.runFrame}')
                    self.runFrame = 0
                    self.startTime = time.time()
                    self.gettingFrameRate = False

                # Algorithms

                # self.path = self.snake.getPathFromAstar()
                # self.path = self.snake.pathShortcutHamilton()
                self.path = self.snake.shortcutHamilton()

                # Updating and Showing Snake
                self.snake.run()

                # Resetting Snake
                if self.snake.dead:
                    self.snake = Snake(self.grid)

                # Updating Score in Title
                self.window.title(
                    f"Snake Game Algorithm  -  Score: {self.snake.drawnLength}"
                )

                # Manually Playing
                # self.manualGameplay()

        # Ending Program
        self.window.mainloop()
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)

snake = Snake()
food = Food()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    # Detect collision with food.
    if snake.head.distance(food) < 15:
        food.refresh()
Exemplo n.º 48
0
    def __init__(self):

        # Screen Sizes
        self.scl = 40  # Scale
        self.rows = 20  # Width
        self.cols = 30  # Height
        self.bord = 5  # Fold

        # Screen Sizes
        self.width = self.cols * self.scl
        self.height = self.rows * self.scl
        self.sclh = self.scl / 2

        # Initializing Start Variables
        self.playSpeed = 1
        self.frame = 0
        self.runFrame = 0
        self.startTime = time.time()

        # Showing Screen Variables
        self.gettingFrameRate = False
        self.showingPath = False
        self.showingHCycle = False
        self.play = False

        # Calculated Algorithm Path
        self.path = []

        # Main Screen Setup
        self.window = turtle.Screen()
        self.window.setup(self.width + 50, self.height + 50)
        self.window.title("Snake Game Algorithme")
        self.window.bgcolor('#141414')
        self.window.tracer(0)

        # Registering Scaled Square Shape
        self.window.register_shape(
            'scaled-square',
            ((-self.sclh + self.bord, self.sclh - self.bord),
             (self.sclh - self.bord, self.sclh - self.bord),
             (self.sclh - self.bord, -self.sclh + self.bord),
             (-self.sclh + self.bord, -self.sclh + self.bord)))

        # Generating Arena Grid Map
        self.grid = Grid(self.cols, self.rows, self.scl)
        self.cells = self.grid.createGrid()
        self.grid.drawBorder('red')

        # Generating Hamiltonian Cycle
        self.hc = HamiltonianCycle(self.grid)
        self.hCycle = self.hc.generateHamiltonianCycle()
        self.grid.hCycle = self.hCycle
        self.grid.bord = self.bord

        # Creating Main Snake Object
        self.snake = Snake(self.grid)

        # Showing Algorithm Path Pen
        self.show = turtle.Turtle()
        self.show.pu()
        self.show.ht()
        self.show.color('blue')
        self.show.width(4)
Exemplo n.º 49
0
class SnakeGame:
    """"Class to manage game assets and behaviour"""
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.game_active = False
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Snake")
        self.grid = self.create_grid()
        self.snake = Snake(self)
        self.stats = GameStatistics(self)
        self.bg_color = self.settings.bg_color
        food_start = self.create_food()
        self.food = FoodSprite(self, self.snake, food_start)
        self.clock = pygame.time.Clock()
        self.play_button = Button(self, "Play")

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self.clock.tick(10)
            self._check_events()
            self._loss_condition()
            self._update_screen()

    def _check_events(self):
        # Watch for keyboard and mouse events.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif self.game_active and event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT and self.snake.direction != (
                        -10, 0):
                    # Move snake to the right
                    self.snake.direction = (10, 0)
                elif event.key == pygame.K_LEFT and self.snake.direction != (
                        10, 0):
                    #Move snake to the left
                    self.snake.direction = (-10, 0)
                elif event.key == pygame.K_UP and self.snake.direction != (0,
                                                                           10):
                    #Move snake up
                    self.snake.direction = (0, -10)
                elif event.key == pygame.K_DOWN and self.snake.direction != (
                        0, -10):
                    #Move snake down
                    self.snake.direction = (0, 10)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _update_screen(self):
        # Redraw the screen during each pass through the loop

        self.screen.fill(self.settings.bg_color)

        self.update_food()
        self.snake.update()

        if not self.game_active:
            self.play_button.draw_button()

        # Make the most recently drawn screen visible
        pygame.display.flip()

    def create_grid(self):
        grid = {}
        for i in range(0, self.settings.screen_width, 10):
            for j in range(0, self.settings.screen_height, 10):
                grid[(i, j)] = False

        return grid

    def update_food(self):
        collisions = pygame.sprite.collide_rect(self.snake.head, self.food)
        if collisions:
            new_pos = self.create_food()
            self.food.update(new_pos)
            self.snake.grow_snake()

        self.food.draw_food()

    def create_food(self):
        return (random.randrange(0, self.settings.screen_width - 1, 10),
                random.randrange(0, self.settings.screen_height - 1, 10))

    def _check_play_button(self, mouse_pos):
        if self.play_button.rect.collidepoint(
                mouse_pos) and not self.game_active:
            self.game_active = True
            pygame.mouse.set_visible(False)

    def _loss_condition(self):
        self_collision = pygame.sprite.spritecollide(self.snake.head,
                                                     self.snake.body, False)
        out_of_bounds = self.check_limits()

        if self_collision or out_of_bounds:
            self.reset_game()

    def check_limits(self):
        head_x = self.snake.head.rect.x
        head_y = self.snake.head.rect.y

        return (not 0 < head_x < self.settings.screen_width
                or not 0 < head_y < self.settings.screen_height)

    def reset_game(self):
        self.game_active = False
        self.snake.direction = None
        pygame.mouse.set_visible(True)
        self.snake.positions = [self.settings.screen_cent]
        self.snake.body.empty()
Exemplo n.º 50
0
    genomes_old = np.load('./difficulty/snake_200.npy', allow_pickle=True)
    genomes = genomes_old
    best_genomes = deepcopy(genomes[0])
if dif == 3:
    genomes_old = np.load('./difficulty/snake_400.npy', allow_pickle=True)
    genomes = genomes_old
    best_genomes = deepcopy(genomes[0])

n_gen = 0
while True:
    n_gen += 1
    # for z in genomes:
    #     print(z.__init__)

    for i, genome in enumerate(genomes):
        snake = Snake(s, genome=genome)
        fitness, score = snake.run()

        genome.fitness = fitness
        genome.score = score

        # print('Generation #%s, Genome #%s, Fitness: %s, Score: %s' %
        #       (n_gen, i, fitness, score))

    if best_genomes is not None:
        # genomes.extend(best_genomes)
        temp2 = np.append(genomes, best_genomes)
        genomes = deepcopy(temp2)

        # np.concatenate((genomes, best_genomes), axis=0)
        # np.vstack((genomes, best_genomes))
Exemplo n.º 51
0
import pygame
from consts import *
from snake import Snake, Food

pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()

snake = Snake()
food = Food()
myfont = pygame.font.SysFont("monospace", 16)


def drawGrid():
    for y in range(0, int(grid_height)):
        for x in range(0, int(grid_width)):
            if (x + y) % 2 == 0:
                box = pygame.Rect(x * gridsize, y * gridsize, gridsize,
                                  gridsize)
                pygame.draw.rect(screen, blue, box)


def drawSnake():
    for pos in snake.positions:
        box = pygame.Rect((pos[0], pos[1]), (gridsize, gridsize))
        pygame.draw.rect(screen, snake.color, box)
        pygame.draw.rect(screen, (93, 216, 228), box, 1)


def drawFood():
    box = pygame.Rect((food.position[0], food.position[1]),
Exemplo n.º 52
0
 def pressforkey(self):
     self.Check = "GameisON"
     del self.snake
     del self.apple
     self.snake = Snake()
     self.apple = Apple()
Exemplo n.º 53
0
def main():
    class Info:
        ''' This class holds information that the thread can access. '''
        pass

    Info.ongoing = True  # Whether we should continue sending moves.
    Info.snake = Snake(10, 10)  # Snake game

    Info.score = 0

    def makeMove():
        '''  Thread that sends a move to the snake game '''
        while Info.ongoing:
            if Info.snake.ongoing:
                # If there are no moves queued, the snake game
                # is at the most updated state
                time.sleep(1 / 10.)  # For some reason, sleeping it makes
                # the gui run faster
                action = astar()
                reward = Info.snake.submitMove(action)
                # sys.stdout.write('%s   \r' % (action))
                # sys.stdout.flush()
                # Info.score += reward
            else:
                # The game is over. Wait some time and then
                # reset the game
                time.sleep(1)
                Info.snake.submitMove(Snake.NOOP)
                Info.score = 0

    def trainQL():
        ''' Thread that learns '''
        ql = QLearner(Info.snake)
        for i in xrange(1000):
            ql.trainStep()
        runQL()

    def runQL():
        pass

    def chooseMove():
        ''' Chooses a move. Naively heads to the horizontal coordinate,
        then the vertical coordinate. '''
        head = Info.snake.head()
        apple = Info.snake.apple
        if head[0] > apple[0]:
            return Snake.LEFT
        elif head[0] < apple[0]:
            return Snake.RIGHT
        else:
            if head[1] > apple[1]:
                return Snake.UP
            else:
                return Snake.DOWN

        return Snake.randomAction()

    def gbf():
        ''' Greedy Best First Search '''
        def dist((x1, y1), (x2, y2)):
            return abs(x1 - x2) + abs(y1 - y2)

        start = Info.snake.head()
        goal = Info.snake.apple
        best = (999999, None)
        for action in Snake.ACTIONS:
            neighbor = Info.snake.pollAction(start, action)
            if Info.snake.isEmpty(neighbor):
                best = min(best, (dist(neighbor, goal), action))

        if best[1] == None:
            return Snake.randomAction()

        return best[1]
Exemplo n.º 54
0
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
from collision_detection import collision_wall, collision_body
import time

SCREEN_BG_COLOR = 'black'
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor(SCREEN_BG_COLOR)
screen.tracer(0)
screen.listen()

snake = Snake()
food = Food()
scoreboard = Scoreboard()

screen.onkey(snake.move_up, 'Up')
screen.onkey(snake.move_left, 'Left')
screen.onkey(snake.move_right, 'Right')
screen.onkey(snake.move_down, 'Down')

game_running = True
while game_running:
    time.sleep(0.15)
    screen.update()
    snake.move()
    if snake.snake_head.distance(food) < 10:
        food.update_spot()
        snake.snake_body_update()
Exemplo n.º 55
0
import pygame
from snake import Snake

pygame.init()

# Create a Screen
width = 800
height = 600

# Create snake
length = 10
color = (255, 255, 255)
snake = Snake(length, color)
snake_speed = snake.get_snake_speed()
x_speed = snake_speed
y_speed = 0

screen = pygame.display.set_mode([width, height])
clock = pygame.time.Clock()

# done
done = False

while not done:
    # events --> tracks keyboard, mouse clicks
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        # snake --> up, down, left, right
        if event.type == pygame.KEYDOWN:
Exemplo n.º 56
0
from snake import Snake
from pprint import pprint

# paint(number_page)

main_page_content = Snake().main_page_content()
menu_urls = Snake().get_urls_main_menu(main_page_content)
all_content = {}

for url in menu_urls.keys():
    print("urls", menu_urls.get(url))
    print("url_key", url.title())
    u = menu_urls.get(url)
    if u.startswith("http"):
        u = menu_urls.get(url)
    else:
        u = f"https://www.khanoumi.com{menu_urls.get(url)}"

    all_content[f"{url.title()}_first_page"] = Snake().page_content_to_soup(u)

    # for num in range(2, number_page + 1):
    #     print(num)
    #     all_content[f"product_page_newproducts_{num}"] = Snake().page_content_to_soup(
    #         Snake.base_url + "newproducts" + f"#paging_{num}/")
    # ges = all_content["product_page_newproducts_1"].find("div", {"id": "bdyno12_pages"})
    # number_page = pages.find_all("a")
    # pr
Exemplo n.º 57
0
INNER_BOUNDARY = 345

screen = Screen()

# Set up the screen dimensions
screen.setup(width=700, height=700)

# Change the screen background color
screen.bgcolor("floral white")

# Stops updating screen automatically
screen.tracer(0)

# Create the snake instance
snake = Snake("maroon")

# Create the food instance
food = Food()

def quit_game():
    global is_game_on
    is_game_on = False
    screen.bye()

# Onscreen Key listeners to move the snake
screen.listen()
screen.onkey(snake.move_left, "Left")
screen.onkey(snake.move_right, "Right")
screen.onkey(snake.move_up, "Up")
screen.onkey(snake.move_down, "Down")
Exemplo n.º 58
0
class SnakeGame:
    def __init__(self):
        pygame.init()
        self.GAMESTATE = 'playing'
        self.size = USIZE * COLUMNS + 300, USIZE * ROWS
        self.score = 0
        self.isFruitShowing = False
        self.isLocked = False # 加锁,防止一个时间周期内改变两次方向,碰到蛇身第二节。
        self.isFullScreen = False
        self.fruitPos = None
        self.snake = Snake()
        self.speed = INITSPEED # FPS
        self.fpsClock = pygame.time.Clock()
#
        self.fontObj = pygame.font.SysFont('楷体', 20)
        self.scoreFont = pygame.font.SysFont('楷体', 32)

        self.screen = self.newScreen(self.size)
        pygame.display.set_caption('mysnake 1.0')

    def start(self):
        self.redraw()
        snake = self.snake

        while True:
            if self.isLocked:
                self.isLocked = False
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        sys.exit()
                    if event.key == K_f:
                        self.screen = self.newScreen(self.size, full=not self.isFullScreen)

                    if self.GAMESTATE == 'over' and event.key == K_RETURN:
                        print('Return press')
                        initGame()
                    if event.key == K_SPACE:
                        if self.GAMESTATE == 'playing':
                            self.GAMESTATE = 'pausing'
                            pygame.mixer.music.pause()
                        elif self.GAMESTATE == 'pausing':
                            self.GAMESTATE = 'playing'
                            pygame.mixer.music.unpause()
                    if self.GAMESTATE == 'playing' and not self.isLocked:
                        self.newDirection = ''
                        if event.key in (K_DOWN, K_s):
                            self.newDirection = 'down'
                        elif event.key in (K_UP, K_w):
                            self.newDirection = 'up'
                        elif event.key in (K_LEFT, K_a):
                            self.newDirection = 'left'
                        elif event.key in (K_RIGHT, K_d):
                            self.newDirection = 'right'
                        if snake.isValidDirection(self.newDirection):
                            snake.changeDirection(self.newDirection)
                            self.isLocked = True
                if event.type == QUIT:
                    #  pygame.quit()
                    sys.exit()
            if self.GAMESTATE == 'playing':
                result = self.checkCollision()
                if result == 0:
                    snake.moveForward()
                elif result == 1:
                    snake.moveForward(True)
                    self.score += 1
                    self.isFruitShowing = False
                    if self.speed < 15:
                        self.speed *= 1.1
                    if self.score in (30, 50, 65, 75) or\
                        (self.score > 75 and (self.score - 80) % 5 == 0):
                        sound_manager.play_cheer_sound()
                elif result == -1:
                    self.GAMESTATE = 'over'
                    sound_manager.play_fail_sound()
                    self.drawFinal()
                self.redraw()
            elif GAMESTATE == 'over':
                pygame.mixer.music.pause()
                self.drawFinal()
            pygame.display.update()
            self.fpsClock.tick(self.speed)

    def newScreen(self, size, full=False):
        screen = None
        if full:
            self.isFullScreen = True
            screen = pygame.display.set_mode(size, FULLSCREEN)
        else:
            self.isFullScreen = False
            screen = pygame.display.set_mode(size)
        return screen

    # 辅助函数
    def initGame(self):
        """重新开始游戏时,对游戏初始化"""
        self.score = 0
        self.GAMESTATE = 'playing'
        self.isFruitShowing = False
        self.fruitPos = None
        self.speed = INITSPEED
        self.snake = Snake()
        pygame.mixer.music.rewind()
        pygame.mixer.music.unpause()

    def drawFinal(self):
        screen = self.screen
        pygame.draw.rect(screen, RED, \
                (200, 120, 400, 300))
        pygame.draw.rect(screen, BLACK, \
                (210, 130, 380, 280))
        overText = self.scoreFont.render('GAME OVER!',\
                True, WHITE)
        scoreText = self.coreFont.render(u'最终得分: ' + str(self.score),\
                True, WHITE)
        promptText = self.fontObj.render(u'按 "回车键" 再玩一次',
                True, WHITE)
        self.screen.blit(overText, (300, 200))
        self.screen.blit(scoreText, (300, 240))
        self.screen.blit(promptText, (300, 290))


    def drawFruit(self):
        """生成并绘制食物"""
        if not self.isFruitShowing:
            tempPos = None
            while not tempPos or tempPos in self.snake.bodyList:
                fX = random.randint(0, ROWS-1)
                fY = random.randint(0, ROWS-1)
                tempPos = (fX, fY)
            self.fruitPos = tempPos
        pygame.draw.rect(self.screen, RED, \
                (self.fruitPos[0]*USIZE, self.fruitPos[1]*USIZE, USIZE, USIZE))
        self.isFruitShowing = True


    def redraw(self):
        self.screen.fill(GREEN)
        # 分割线
        pygame.draw.line(self.screen, RED, (502, 0), (502, 500), 3)
        promptText = self.fontObj.render(u'按 "空格键" 开始/暂停', True, WHITE)
        #  promptText2 = fontObj.render(u'开始/暂停', True, WHITE)
        scoreText = self.scoreFont.render(u'得分: ' + str(self.score), True, WHITE)
        self.screen.blit(promptText, (550, 100))
        #  screen.blit(promptText2, (560, 120))
        self.screen.blit(scoreText, (570, 220))
        # drawSnake()
        self.snake.draw_self(self.screen)
        self.drawFruit()


    def checkCollision(self):
        snake = self.snake
        # 吃到食物
        if tuple(snake.headPos) == self.fruitPos:
            sound_manager.play_eat_sound()
            return 1
        # 碰到自己身体
        if tuple(snake.headPos) in snake.bodyList[1:]:
            return -1
        return 0
Exemplo n.º 59
0
    def play(self):
        """
        method for main game progression
        """
        pygame.init()  # initialize pygame

        # instantiate snake object
        snake = Snake(self.constant['win_width'] / 2,
                      self.constant['win_height'] / 2)

        # instantiate food object
        food = Food(self.constant['win_width'], self.constant['win_height'],
                    self.constant['snake_block'])
        clock = pygame.time.Clock()

        game_over = False
        snake_speed = self.constant['snake_speed']

        # loop game
        while not game_over:

            # all event used for the game
            for event in pygame.event.get():
                if event.type == QUIT:
                    game_over = True
                if event.type == pygame.KEYDOWN:
                    if event.key == K_ESCAPE:
                        game_over = True
                    elif event.key == K_LEFT:
                        snake.move_to('left')
                    elif event.key == K_RIGHT:
                        snake.move_to('right')
                    elif event.key == K_UP:
                        snake.move_to('up')
                    elif event.key == K_DOWN:
                        snake.move_to('down')

            # update snake position
            snake.update_position()

            # set blue background
            self.window.fill(self.color_tuple(self.constant['blue']))

            # display food element
            pygame.draw.rect(
                self.window, self.color_tuple(self.constant['green']), [
                    food.position_x(),
                    food.position_y(), self.constant['snake_block'],
                    self.constant['snake_block']
                ])

            # game over is the snake is out of the window limit
            if snake.is_out_of_window(self.constant['win_width'],
                                      self.constant['win_height']):
                game_over = True

            # game over if the snake eat himself
            elif snake.eat_himself():
                game_over = True

            # snake grow up when eating food
            elif food.is_ate(snake.position_x(), snake.position_y()):
                food = Food(self.constant['win_width'],
                            self.constant['win_height'],
                            self.constant['snake_block'])
                snake.grow_up()
                snake_speed += 1

            # update snake displaying
            for x in snake.list():
                pygame.draw.rect(self.window, self.constant['black'], [
                    x[0], x[1], self.constant['snake_block'],
                    self.constant['snake_block']
                ])

            self.score(snake.get_score())

            # game updated
            pygame.display.update()

            # game speed
            clock.tick(snake_speed)

        pygame.quit()
        quit()
Exemplo n.º 60
0
class Game():
    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"


    def drawlines(self):
        for x in range(0,Config.WINDOW_WIDTH,Config.CELLSIZE):
            pygame.draw.line(self.screen,Config.DARKGRAY,(x,0),(x,Config.WINDOW_HEIGHT))
        for y in range(0,Config.WINDOW_HEIGHT,Config.CELLSIZE):
            pygame.draw.line(self.screen,Config.DARKGRAY,(0,y),(Config.WINDOW_WIDTH,y))

    def run(self):
        self.StartString()
        while True:
            if self.Check == "GameisOFF":
                self.pressforkey()
            for e in pygame.event.get():
                if e.type == pygame.QUIT:
                    pygame.quit()
                if e.type == pygame.KEYDOWN:
                    self.draw()
                    pygame.display.update()
                    self.loop()


    def drawApple(self):
        x = self.apple.x * Config.CELLSIZE
        y = self.apple.y * Config.CELLSIZE
        applerect = pygame.Rect(x,y,Config.CELLSIZE,Config.CELLSIZE)
        pygame.draw.rect(self.screen,Config.RED, applerect)

    def drawScore(self,score):
        scoreSurf = self.BASICFONT.render('Score: %s' % (score), True, Config.WHITE)
        scoreRect = scoreSurf.get_rect()
        scoreRect.topleft = (Config.WINDOW_WIDTH -120, 10)
        self.screen.blit(scoreSurf,scoreRect)


    def drawSnake(self):
        for a in self.snake.wormCoords:
            x= a['x'] * Config.CELLSIZE
            y = a['y'] * Config.CELLSIZE
            snakerect = pygame.Rect(x,y,Config.CELLSIZE,Config.CELLSIZE)
            pygame.draw.rect(self.screen,Config.DARKGREEN,snakerect)
            Innersnakerect = pygame.Rect(x+4,y+4,Config.CELLSIZE-8,Config.CELLSIZE-8)
            pygame.draw.rect(self.screen,Config.GREEN,Innersnakerect)

    def String(self):
        Strin = self.OVER.render('Game Over' , True, Config.WHITE)
        self.screen.blit(Strin,(200,200))

    def StartString(self):
        Strin1 = self.OVER.render('To Start the Game' , True, Config.WHITE)
        self.screen.blit(Strin1,(100,200))
    # To Rotate the String    rotatedSurf2 = pygame.transform.rotate(Strin1,10-degres)
        Strin2 = self.BASICFONT.render('"Press Any Key"' , True, Config.WHITE)
        self.screen.blit(Strin2,(250,280))
        pygame.display.update()


    def gameover(self):

        if (self.snake.wormCoords[0]['x'] >= Config.CELLWIDTH or
            self.snake.wormCoords[0]['x'] <= -1 or
            self.snake.wormCoords[0]['y'] <= -1 or
            self.snake.wormCoords[0]['y'] >= Config.CELLHEIGHT ):
            self.screen.fill(Config.BG_COLOR)
            self.String()
            self.Check = "GameisOFF"

        for worm in self.snake.wormCoords[1:]:
            if (worm['x'] == self.snake.wormCoords[0]['x'] and worm['y'] == self.snake.wormCoords[0]['y']):
               self.screen.fill(Config.BG_COLOR)
               self.String()
               self.Check = "GameisOFF"




    def pressforkey(self):
        self.Check = "GameisON"
        del self.snake
        del self.apple
        self.snake = Snake()
        self.apple = Apple()


    def handleevents(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and self.snake.direction != self.snake.RIGHT:
                    self.snake.direction = self.snake.LEFT

                if event.key == pygame.K_RIGHT and self.snake.direction != self.snake.LEFT:
                    self.snake.direction = self.snake.RIGHT

                if event.key == pygame.K_UP and self.snake.direction != self.snake.DOWN:
                    self.snake.direction = self.snake.UP

                if event.key == pygame.K_DOWN and self.snake.direction != self.snake.UP:
                    self.snake.direction = self.snake.DOWN
    def draw(self):
        self.drawlines()
        self.drawSnake()
        self.drawApple()
        self.drawScore(len(self.snake.wormCoords) - 3)

    def loop(self):
        while True:
            self.handleevents()
            self.snake.update(self.apple)
            self.clock.tick(Config.FPS)
            self.screen.fill(Config.BG_COLOR)
            self.draw()
            self.gameover()
            pygame.display.update()

            if self.Check == "GameisOFF" :
                break