Ejemplo n.º 1
0
class Game:
    def __init__(self, gameWindow, mainBatch, backgroundGroup, middlegroundGroup, foregroundGroup):
        self.mainBatch = mainBatch
        self.backgroundGroup = backgroundGroup
        self.middlegroundGroup = middlegroundGroup
        self.foregroundGroup = foregroundGroup
        #背景图与方框
        self.background = pyglet.sprite.Sprite(img=Resources.background_image,x=0,y=0,batch=mainBatch,group=backgroundGroup)
        x1 = GameConfig.basePoint[0]
        y1 = GameConfig.basePoint[1]
        ww = GameConfig.maxX * GameConfig.defaultImageWidth
        hh = GameConfig.maxY * GameConfig.defaultImageHeight
        self.rect_vertex_list = mainBatch.add(4, pyglet.gl.GL_LINE_LOOP, middlegroundGroup,
            ('v2f', (x1,y1,x1+ww,y1,x1+ww,y1+hh,x1,y1+hh)), ('c3B', GameConfig.rectColor*4))
        #整体文本信息
        self.msg_label = pyglet.text.Label(text="Welcome!", 
            x=GameConfig.msg1_x, y=GameConfig.msg1_y,
            batch=mainBatch, group=middlegroundGroup,
            color=GameConfig.textColor, font_size=GameConfig.textSize)
        #初始食物
        self.bread = GameObject.Bread(GameConfig.firstFood, self.mainBatch, middlegroundGroup)
        #障碍物们
        self.walls = Walls(mainBatch, middlegroundGroup)
        self.walls.newWalls(GameConfig.logicMap)
        #蛇
        self.snake = Snake(mainBatch,middlegroundGroup)
        self.snake.newSnake(GameConfig.startPoint, GameConfig.startDirection)
        gameWindow.push_handlers(self.snake)
        #飘过的云
        self.clouds = Clouds(mainBatch, foregroundGroup)
    
    def update(self, dt):
        self.snake.update(dt, self.walls, self.bread)
        self.clouds.update(dt)
Ejemplo n.º 2
0
class GUI:
    DEFAULT_REFRESH_TIMER = 30
    def __init__(self):
        self.fenetre = Tk()
        self.fenetre.geometry('480x480')
        self.canvas = Canvas(self.fenetre, bg='black', highlightthickness=0)
        self.canvas.pack(fill='both', expand=1)
        self.timer = GUI.DEFAULT_REFRESH_TIMER
        self.snake = Snake(self.canvas, randint(0, 480),
                           randint(0, 480), random()*2*pi)
        self.refresh()
        self.canvas.focus_set()
        self.canvas.bind('<Key>', self.keyPressed)
    
    def refresh(self):
        self.snake.move()
        self.current_loop = self.fenetre.after(self.timer, self.refresh)
    
    def keyPressed(self, e):
        touche = e.keysym
        if touche in ('Right', 'Left'):
            self.snake.angle += 0.15 * {'Right': 1, 'Left': -1}[touche]
        elif touche == 'q':
            self.fenetre.after_cancel(self.current_loop)
    
    def start(self):
        self.fenetre.mainloop()
Ejemplo n.º 3
0
def move():
    snakeObj = Snake() 
    data = bottle.request.json
    mapObj.setData(data)
    # pprint(data)
    # True/False for every spot on the board for visited nodes in BFS
    if (len(originalDictionary) < 1):
        generateDictionaryTF(mapObj, originalDictionary)
    turnDictionary = originalDictionary.copy()
    # Remove spots that are completely unavailable
    # Makes list for other snakes by looking at all snakes with name != ours
    for snake in data['snakes']['data']:
        if snake['id'] == data['you']['id']:
            ourSnake = snake
            snakeObj.ourSnake = ourSnake
            snakeObj.headOfOurSnake = ourSnake['body']['data'][0]
            snakeObj.ourSnake['health'] = ourSnake['health']
            snakeObj.ourSnake['length'] = len(ourSnake['body']['data'])
        else:
            snakeObj.otherSnakes.append(snake)

        # If it's the first few turns we want to not remove the tail from nodes that can be removed from the list
        # as the snake extends out in the first 3 turns
        coordsToIterateThrough = snake['body']['data'][:-1]
        if data['turn'] < 2:
            coordsToIterateThrough = snake['body']['data']

        # removes all snake bodies/tail (not head) from list of
        # possible co-ordinates
        for coord in coordsToIterateThrough:
            x = coord['x']
            y = coord['y']
            # removes move directions that are directly onto enemy snakes
            if not turnDictionary.get((x, y), None) is None:
                del turnDictionary[(x, y)]
            
    # dictionary of all 4 directions
    t = (snakeObj.headOfOurSnake['x'], snakeObj.headOfOurSnake['y'])
    directionsCanGo = getDirectionsCanGo(t,
            turnDictionary)
    # dictionary holding all possible directions in form:
    # [direction, heuristicValue]
    directionHeuristics = {}
    removeSnakeCollisions(snakeObj, turnDictionary, directionHeuristics)
    # set collision directions == 5 (Danger)
    currMove = determineMovePriority(directionsCanGo, 
                                     turnDictionary,  
                                     mapObj, 
                                     directionHeuristics, 
                                     snakeObj)
    # danger check should happen after food evaluation

    # send determined move to server
    return {
        'move': currMove,
        'taunt': "Arrays start at 2. Change my mind"
        # 'taunt': tauntGenerator(mapObj)
    }
Ejemplo n.º 4
0
    def game(self,screen):                                           # MAIN FUNCTION TO START THE GAME
        clock = pygame.time.Clock()
        spots = self.make_board()
        snake = Snake(self)
        spots[0][0] = 1

        with self.lock:
            self.food.pos = self.find_food(spots)

        thread.start_new_thread(self.food.move_food,(snake,))       # THREAD FOR MOVING FOOD PARTICLE

        self.Signal=True

        while True:
            clock.tick(15)
            # Event processing
            self.done = False
            events = pygame.event.get()
            for event in events:
                if event.type == pygame.QUIT:
                    print("Quit given")
                    self.done = True
                    self.Signal=False
                    break
            if self.done:
                return False

            snake.populate_nextDir(events, "arrows")

            # Game logic
            next_head = snake.move()                                # MOVING SNAKE TO NEXT COORDINATE
            next_head=snake.get_head(next_head)

            if (self.end_condition(spots, next_head)):
                self.Signal=False
                return snake.tailmax

            if self.is_food(spots, next_head):
                snake.tailmax += 4
                self.end=pygame.time.get_ticks();
                count=snake.tailmax/4-2;
                self.food.btimer=float(self.food.btimer*((count+2))/(count+1))+50-float(self.end-self.start)/((count+1)*300);

                print self.food.btimer;

                self.start=pygame.time.get_ticks();
                with self.lock:
                    self.food.pos = self.find_food(spots)

            snake.deque.append(next_head)

            if len(snake.deque) > snake.tailmax:
                snake.deque.popleft()

            # Draw code
            screen.fill(self.BLACK)  # makes screen black
            spots = self.update_board(screen, snake)
            pygame.display.update()
Ejemplo n.º 5
0
 def create_snakes(self):
     the_Snake = Snake()
     the_Snake.initial_parts(initial_length)
     the_Snake.initial_pos()
     self.add_widget(the_Snake)
     self.da_snakes.append(the_Snake)
     #Put the following part in a function
     self.da_food = SnakeFoo()
     self.da_food.size = snake_part_size
     self.da_food.position(Window.width, Window.height)
     self.add_widget(self.da_food)
Ejemplo n.º 6
0
	def __init__(self):
		""" Inicialización del juego. """

		self.wii = WiiNunchuck()
		self.snake = Snake(3)
		self.display = Display()
		self.direction = self.snake.direction
		self.food = None
Ejemplo n.º 7
0
 def __init__(self):
     self._running = False
     self._main_clock = pygame.time.Clock()
     self._display_surf = None
     self.size = self.width, self.height = 640, 480
     self._game = Game()
     self._snake = Snake()
     self._snake.set_position(100, 100)
Ejemplo n.º 8
0
class World():
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        self.snake = Snake()
        
    def move(self):
        self.snake.plot()
        
    def plot(self):
        self.snake.plot()
        
        
Ejemplo n.º 9
0
 def __init__(self):
     self.fenetre = Tk()
     self.fenetre.geometry('480x480')
     self.canvas = Canvas(self.fenetre, bg='black', highlightthickness=0)
     self.canvas.pack(fill='both', expand=1)
     self.timer = GUI.DEFAULT_REFRESH_TIMER
     self.snake = Snake(self.canvas, randint(0, 480),
                        randint(0, 480), random()*2*pi)
     self.refresh()
     self.canvas.focus_set()
     self.canvas.bind('<Key>', self.keyPressed)
Ejemplo n.º 10
0
    def __init__(self):
        print("Game engine")
        pygame.init()
        self.screen = pygame.display.set_mode((640, 480))
        pygame.display.set_caption("Snake challenge")

        # Fill background with black
        self.background = pygame.Surface(self.screen.get_size())
        self.background = self.background.convert()
        self.background.fill((0, 0, 0))

        self.running = True
        self.apple = Apple()
        self.snake = Snake()
Ejemplo n.º 11
0
class Game(_Scene):
    """This scene is active during the gameplay phase."""
    def __init__(self):
        _Scene.__init__(self, "DEAD")
        self.reset()

    def reset(self):
        """Prepare for next run."""
        _Scene.reset(self)
        self.snake = Snake()
        self.walls = self.make_walls()
        self.apple = Apple(self.walls, self.snake)

    def make_walls(self):
        """Make the borders, and load a random level."""
        walls = set()
        for i in range(-1, BOARD_SIZE[0]+1):
            walls.add((i, -1))
            walls.add((i, BOARD_SIZE[1]))
        for j in range(-1, BOARD_SIZE[1]+1):
            walls.add((-1, j))
            walls.add((BOARD_SIZE[0], j))
        walls |= random.choice(LEVELS)
        return walls

    def get_event(self, event):
        """Pass any key presses on to the snake."""
        if event.type == pg.KEYDOWN:
            self.snake.get_key_press(event.key)

    def update(self, now):
        """Update the snake and check if it has died."""
        _Scene.update(self, now)
        self.snake.update(now)
        self.snake.check_collisions(self.apple, self.walls)
        if self.snake.dead:
            self.done = True

    def draw(self, surface):
        """Draw the food, snake, and walls."""
        surface.fill(COLORS["background"])
        draw_cell(surface, self.apple.position,
                  self.apple.color, PLAY_RECT.topleft)
        for wall in self.walls:
            draw_cell(surface, wall, COLORS["walls"], PLAY_RECT.topleft)
        self.snake.draw(surface, offset=PLAY_RECT.topleft)
Ejemplo n.º 12
0
class GameEngine:

    def __init__(self):
        print("Game engine")
        pygame.init()
        self.screen = pygame.display.set_mode((640, 480))
        pygame.display.set_caption("Snake challenge")

        # Fill background with black
        self.background = pygame.Surface(self.screen.get_size())
        self.background = self.background.convert()
        self.background.fill((0, 0, 0))

        self.running = True
        self.apple = Apple()
        self.snake = Snake()


    # Starting point of the game
    def start(self):

        clock = pygame.time.Clock()
        # Simplefied Game loop
        while self.running:
            clock.tick(50)
            self.handle_events()
            self.update()
            self.render()


    # Call rendering for all game objects
    def render(self):
        # Clear the screen
        self.screen.blit(self.background, (0, 0))
        # Render objects
        self.apple.render()
        self.snake.render()

        # Update screen
        pygame.display.flip()

    # Call updates on all game objects
    def update(self):
        self.apple.update()
        self.snake.update(self.apple)


    # Handle events such as key presses or exits
    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            else:
                self.snake.handle_event(event)
Ejemplo n.º 13
0
	def __init__(self, height, width, speed, placeObstacles=False):
		# Integer height of the plane
		self.height = height
		# Integer width of the plane
		self.width = width
		# Integer delay between frames of the of the game
		self.speed = speed
		# Integer score that is the length of the snake
		self.score = 0
		# The snake, starting on the left side of the plane
		self.snake = Snake(Square(height // 2, width // 2, self.width))
		# Boolean indicating whether to place obstacles or not
		self.placeObstacles = placeObstacles
		# Set of squares representing obstacles
		self.obstacles = set()
		# Square representing the food
		self.food = None
Ejemplo n.º 14
0
def gameLoop():
    global dirn, k, highscore, namehighscore
    pyExit = False
    pyOver = False
    #stop intro music and play in game music infinite loop
    intro_sound.stop()
    game_sound.play(-1)
    score = 0
    world_num = 0
    scorestr = "Score:0"
    # Initialize the game
    snake = Snake(200, 200, img)
    food = Food(int(width / 2), int(height / 2))
    blocks = worlds(width - 200, height, world_num)

    # Keeps track of the direction of the snake.
    dx, dy = 0, 0
    lossreason = ''

    while not pyExit:
        if pyOver == True:
            #play end music
            endgame_sound.play(-1)
        while pyOver:
            image = pygame.image.load(python_path)
            game_display.blit(image, (0, 0))

            message("Game Over! Press C to play Again, Q to Quit",
                    (255, 0, 0), -20)
            message(lossreason, (255, 0, 0), 30)
            # display score on game over
            message("Your" + scorestr, (255, 0, 0), 80)
            if totalscore > highscore:
                # message("Highscore!!!",(255,0,0),120)
                # write new highscore
                highscorefile = open('highscore.txt', 'wt')
                highscorefile.write(str(totalscore) + "\n")

                # name window
                def namewrite():
                    highscorefile.write(v.get())
                    scorewindow.destroy()

                scorewindow = Tk()
                scorewindow.geometry('300x100')
                frame = Frame(scorewindow, width=100, height=100)
                frame.pack()
                scorewindow.title("congratulations")

                Label(frame, text='you\'ve made highscore!!!!').pack(side='top')
                v = StringVar()
                v.set("type your name")
                textbox = Entry(frame, textvariable=v)
                textbox.pack(side='top')

                okbutton = Button(frame, text="ok", fg="black",
                                  bg="white", command=namewrite)
                okbutton.pack(side='bottom')

                scorewindow.mainloop()
                highscorefile.close()

                # incase user wants to countinue after creating highscore
                # to read his new score
                highscorefile = open('highscore.txt', 'rt')
                highscore = highscorefile.readline()
                highscore = int(highscore)
                namehighscore = highscorefile.readline()
                highscorefile.close()

            else:
                message("Highscore by " + namehighscore +
                        ":" + str(highscore), (255, 0, 0), 120)
            pygame.display.update()

            for event in pygame.event.get():
                keyp = action()
                if keyp != None or event.type == pygame.KEYDOWN:
                    try:
                        if keyp == 'q' or event.key == pygame.K_q:
                            pyExit = True
                            pyOver = False
                    except:
                        blank = []  # bypass the exception
                    try:
                        if keyp == 'c' or event.key == pygame.K_c:
                            #stop endgame music
                            endgame_sound.stop()
                            gameLoop()
                    except:
                        blank = []  # bypass the exception
                        
        """ Events """
        #the conditions are modified to work with the buttons
        for event in pygame.event.get():
            keyp = action()
            # blank is not used anywhere
            # it is just used to jump the exception
            if event.type == pygame.QUIT:
                pyExit = True
            if event.type == pygame.KEYDOWN or keyp != None:
                try:
                    if keyp == 'lt' or event.key == pygame.K_LEFT and dirn != "right":
                        dirn = "left"
                        dx = -1
                        dy = 0
                except:
                    blank = []
                try:
                    if keyp == 'rt' or event.key == pygame.K_RIGHT and dirn != "left":
                        dirn = "right"
                        dx = 1
                        dy = 0
                except:
                    blank = []
                try:
                    if keyp == 'up' or event.key == pygame.K_UP and dirn != "down":
                        dirn = "up"
                        dy = -1
                        dx = 0
                except:
                    blank = []
                try:
                    if keyp == 'dn' or event.key == pygame.K_DOWN and dirn != "up":
                        dirn = "down"
                        dy = 1
                        dx = 0
                except:
                    blank = []
                try:
                    if keyp == 'p' or event.key == pygame.K_p:
                        pause(scorestr)
                except:
                    blank = []
                try:
                    if keyp == 'q' or event.key == pygame.K_q:
                        pygame.quit()
                        quit(0)
                except:
                    blank = []

        # level changer value
        if score > 10:
            score = 0
            world_num += 1
            blocks = worlds(width - 200, height, world_num)
            food.x, food.y = int(width / 2), int(height / 2)

        # Engage boost of pressing shift
        keyp=action()
        keyPresses = pygame.key.get_pressed()
        boost_speed = keyPresses[pygame.K_LSHIFT] or keyPresses[pygame.K_RSHIFT] or keyp=='st'

        # if boost_speed is true it will move 2 blocks in one gameloop
        # else it will just move one block
        iterations = [1]
        if boost_speed == 1:
            iterations.append(2)

        for i in iterations:
            """ Update snake """
            snake.move(dx, dy, 10)
            snake.check_boundary(width, height)

            snake_rect = snake.get_rect()
            food_rect = food.get_rect()

            """ Snake-Snake collision """
            if snake.ate_itself():
                #stop game sound
                game_sound.stop()
                pyOver = True
                lossreason = 'Oooops You Hit YOURSELF'
                

            """ Snake-Block collision """
            for block in blocks:
                block_rect = block.get_rect()
                if block_rect.colliderect(snake_rect):
                    #stop game sound
                    game_sound.stop()
                    pyOver = True
                    lossreason = 'Ooops You Hit a BLOCKER'
                    
            """ Snake-Food collision """
            # if snake collides with food, increase its length.
            if food_rect.colliderect(snake_rect):
                score += 1
                snake.increment_length()

                sound = pygame.mixer.Sound(point_path)
                sound.set_volume(0.3)
                sound.play()

                # generate food at random x, y.
                food.generate_food(width, height)

                # try generating the food at a position where blocks are not present.
                while food_collides_block(food.get_rect(), blocks):
                    food.generate_food(width - food.size, height - food.size)

            """ Draw """
            game_display.fill((255, 255, 255))
            showButton()

            # draw the food and snake.
            snake.draw(game_display, dirn, (0, 155, 0))
            food.draw(game_display, (0, 255, 0))

        # draw the blocks.
        for block in blocks:
            block.draw(game_display, (255, 0, 0))
        # count and display score on screen
        totalscore = total(score, world_num)
        scorestr = 'Score: ' + str(totalscore)
        font = pygame.font.SysFont(None, 30)
        text = font.render(scorestr, True, (0, 0, 255))
        game_display.blit(text, (0, 0, 20, 20))

        pygame.display.update()
        clock.tick(FPS)

    pygame.quit()
    quit()
Ejemplo n.º 15
0
import pygame, time, sys, random
pygame.init()
from GameWindow import GameWindow
from Snake import Snake
from Collectible import Collectible

if __name__ == "__main__":
    window = GameWindow(800, 600)
    snake = Snake()
    collectibles = []
    clock = pygame.time.Clock()
    running = True

    while running:
        window.window.fill(GameWindow.white)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        #generate new collectibles
        if not collectibles:
            collectibles.append(Collectible())
        if random.randint(
                0, 120
        ) == 1:  #should generate 1 new collectible every 2 seconds???
            collectibles.append(Collectible())

        #handles keypresses and moves the snake
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_LEFT] and snake.direction != 'east':
Ejemplo n.º 16
0
from Border import Border
from Ball import Ball
from move import Move
from Tail import Tail
from sketch import Sketch

delay = 0.001
start_tail = 1
score = 0
# Set up the screen
screen = turtle.Screen()
screen.setup(width=1000, height=600)

# SNAKE PART
# Snake head
snake = Snake()
snakehead = snake.snakehead()
# long border
bor = Border()
border = bor.setUpBorder()
# Snake tail
segments = []
# Paddle
# You can move the paddle with 'z' and 's'
pad = Paddle()
paddle = pad.paddle()
# Ball of circle shape
Ball = Ball()

# Global part
#Sets key bindings to the right thing.
Ejemplo n.º 17
0
DIRECTION = RIGHT  # Always start the game with a moving right snake
FRUIT_COLOR = (0, 255, 0)
LEVEL_UP = 5  # Must eat 4  (5 - 1 = 4) fruits to go to the next level

# Setting up the GUI
pygame.display.set_caption("Classic Snake 2D")
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
icon = pygame.image.load("icon.png")
pygame.display.set_icon(icon)
large_font = pygame.font.Font("font.ttf", 35)
small_font = pygame.font.Font("font.ttf", 18)
screen.fill(BACKGROUND_COLOR)

# The snake of the game
snake = Snake(SCREEN_SIZE[0], SCREEN_SIZE[1], Snake.MIN_LENGTH)
# The fruit
fruit = None

# The boolean flag to tell the reason why the snake is dead
eat_self = False
eat_gate = False

# Open/close the gate flag
gate_open = False
# The gate
gate = None

# Stop the game
is_running = True
Ejemplo n.º 18
0
 def newRound(self):
     self.time = 0
     self.numSnake = 0
     self.snake = Snake()
Ejemplo n.º 19
0
class Program(object):
	""" TODO: Mejorar el tiempo de refresco de pantalla """


	# Condición que un hilo debe revisar para terminar su ejecución
	keep_playing = True

	def __init__(self):
		""" Inicialización del juego. """

		self.wii = WiiNunchuck()
		self.snake = Snake(3)
		self.display = Display()
		self.direction = self.snake.direction
		self.food = None

	def read_control(self):
		""" Mientras el juego siga activo, lee el control de Wii y mueve 
		la serpiente o termina el juego. """

		while (self.keep_playing):
			self.wii.read_data()
			self.change_direction()

			if self.wii.data.button_c is True:
				print "Boton C"
				self.game_over(None)

			sleep(0.01)

	def change_direction(self):
		""" Interpreta la dirección del joystick para cambiar la dirección 
		en la que avanza la serpiente. """

		if self.wii.data.joystick_y < 70: #Down arrow
			self.direction = "DOWN"
		elif self.wii.data.joystick_y > 180: #Up arrow
			self.direction = "UP"
		if self.wii.data.joystick_x < 70: #Up arrow
			self.direction = "LEFT"
		elif self.wii.data.joystick_x > 180: #Up arrow
			self.direction = "RIGHT"
	    
	def update_snake(self):
		""" Mientras el juego siga activo, actualiza la posición de la serpiente
		moviéndola hacia adelante cada 0.2 seg y verifica colisiones."""

		while(self.keep_playing):
			self.snake.move(self.direction)
			self.check_collisions()
			sleep(0.2)
		
	def check_collisions(self):
		""" Revisar si la cabeza de la serpiente colisionó con el resto 
		del cuerpo o con comida """

		for p in self.snake.body[2:]:
			if (
				self.snake.body[0].x == p.x and
				self.snake.body[0].y == p.y
				):
				self.game_over(-1)
			if self.food is not None:
				if (
					self.snake.body[0].x == self.food.place.x and
					self.snake.body[0].y == self.food.place.y
					):
					self.snake.eat()
					self.food = None

	def make_food(self):
		""" Mientras el juego siga activo, actualiza la posición del objeto 
		de comida cada 3 seg. """

		while(self.keep_playing):
			self.food = Food()
			sleep(3)

	def update_screen(self):
		""" Mientras el juego siga activo, refresca la pantalla con la posición 
		de la serpiente y de la comida """

		while(self.keep_playing):
			array_points = list(self.snake.body)
			if self.food is not None:
				array_points.append(self.food.place)
			self.display.show(array_points)

	def game_over(self, end_code):
		""" Controla cómo terminará el juego.
		Al perder, espera 3 seg y luego saldrá.

		Args:
			end_code: Un número entero negativo usado para saber
				por qué terminó el juego.
		"""

		if end_code is -1:
			print "You lost."
		print "End of game!"
		self.keep_playing = False
		sleep(3)
from Snake import Snake
from Food import Food
from Scoreboard import Score

# Storage for Variables and Lists
game_over = False

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

# Creating the snake and food using the Class imported above
snake = Snake()
food = Food()
Score = Score()

# Key's for movement
screen.listen()
screen.onkey(key="w", fun=snake.Up)
screen.onkey(key="s", fun=snake.Down)
screen.onkey(key="a", fun=snake.Left)
screen.onkey(key="d", fun=snake.Right)

while 1:

    screen.update()
    time.sleep(0.1)
    snake.move()
Ejemplo n.º 21
0
def gameLoop():
    global dirn, k, highscore, namehighscore
    pyExit = False
    pyOver = False
    #stop intro music and play in game music infinite loop
    intro_sound.stop()
    game_sound.play(-1)
    score = 0
    world_num = 0
    scorestr = "Score:0"
    # Initialize the game
    snake = Snake(200, 200, img)
    food = Food(int(width / 2), int(height / 2))
    blocks = worlds(width - 200, height, world_num)

    # Keeps track of the direction of the snake.
    dx, dy = 0, 0
    lossreason = ''

    while not pyExit:
        if pyOver == True:
            #play end music
            endgame_sound.play(-1)
        while pyOver:
            image = pygame.image.load(python_path)
            game_display.blit(image, (0, 0))

            message("Game Over! Press C to play Again, Q to Quit", (255, 0, 0),
                    -20)
            message(lossreason, (255, 0, 0), 30)
            # display score on game over
            message("Your" + scorestr, (255, 0, 0), 80)
            if totalscore > highscore:
                # message("Highscore!!!",(255,0,0),120)
                # write new highscore
                highscorefile = open('highscore.txt', 'wt')
                highscorefile.write(str(totalscore) + "\n")

                # name window
                def namewrite():
                    highscorefile.write(v.get())
                    scorewindow.destroy()

                scorewindow = Tk()
                scorewindow.geometry('300x100')
                frame = Frame(scorewindow, width=100, height=100)
                frame.pack()
                scorewindow.title("congratulations")

                Label(frame,
                      text='you\'ve made highscore!!!!').pack(side='top')
                v = StringVar()
                v.set("type your name")
                textbox = Entry(frame, textvariable=v)
                textbox.pack(side='top')

                okbutton = Button(frame,
                                  text="ok",
                                  fg="black",
                                  bg="white",
                                  command=namewrite)
                okbutton.pack(side='bottom')

                scorewindow.mainloop()
                highscorefile.close()

                # incase user wants to countinue after creating highscore
                # to read his new score
                highscorefile = open('highscore.txt', 'rt')
                highscore = highscorefile.readline()
                highscore = int(highscore)
                namehighscore = highscorefile.readline()
                highscorefile.close()

            else:
                message("Highscore by " + namehighscore + ":" + str(highscore),
                        (255, 0, 0), 120)
            pygame.display.update()

            for event in pygame.event.get():
                keyp = action()
                if keyp != None or event.type == pygame.KEYDOWN:
                    try:
                        if keyp == 'q' or event.key == pygame.K_q:
                            pyExit = True
                            pyOver = False
                    except:
                        blank = []  # bypass the exception
                    try:
                        if keyp == 'c' or event.key == pygame.K_c:
                            #stop endgame music
                            endgame_sound.stop()
                            gameLoop()
                    except:
                        blank = []  # bypass the exception
        """ Events """
        #the conditions are modified to work with the buttons
        for event in pygame.event.get():
            keyp = action()
            # blank is not used anywhere
            # it is just used to jump the exception
            if event.type == pygame.QUIT:
                pyExit = True
            if event.type == pygame.KEYDOWN or keyp != None:
                try:
                    if keyp == 'lt' or event.key == pygame.K_LEFT and dirn != "right":
                        dirn = "left"
                        dx = -1
                        dy = 0
                except:
                    blank = []
                try:
                    if keyp == 'rt' or event.key == pygame.K_RIGHT and dirn != "left":
                        dirn = "right"
                        dx = 1
                        dy = 0
                except:
                    blank = []
                try:
                    if keyp == 'up' or event.key == pygame.K_UP and dirn != "down":
                        dirn = "up"
                        dy = -1
                        dx = 0
                except:
                    blank = []
                try:
                    if keyp == 'dn' or event.key == pygame.K_DOWN and dirn != "up":
                        dirn = "down"
                        dy = 1
                        dx = 0
                except:
                    blank = []
                try:
                    if keyp == 'p' or event.key == pygame.K_p:
                        pause(scorestr)
                except:
                    blank = []
                try:
                    if keyp == 'q' or event.key == pygame.K_q:
                        pygame.quit()
                        quit(0)
                except:
                    blank = []

        # level changer value
        if score > 10:
            score = 0
            world_num += 1
            blocks = worlds(width - 200, height, world_num)
            food.x, food.y = int(width / 2), int(height / 2)

        # Engage boost of pressing shift
        keyp = action()
        keyPresses = pygame.key.get_pressed()
        boost_speed = keyPresses[pygame.K_LSHIFT] or keyPresses[
            pygame.K_RSHIFT] or keyp == 'st'

        # if boost_speed is true it will move 2 blocks in one gameloop
        # else it will just move one block
        iterations = [1]
        if boost_speed == 1:
            iterations.append(2)

        for i in iterations:
            """ Update snake """
            snake.move(dx, dy, 10)
            snake.check_boundary(width, height)

            snake_rect = snake.get_rect()
            food_rect = food.get_rect()
            """ Snake-Snake collision """
            if snake.ate_itself():
                #stop game sound
                game_sound.stop()
                pyOver = True
                lossreason = 'Oooops You Hit YOURSELF'
            """ Snake-Block collision """
            for block in blocks:
                block_rect = block.get_rect()
                if block_rect.colliderect(snake_rect):
                    #stop game sound
                    game_sound.stop()
                    pyOver = True
                    lossreason = 'Ooops You Hit a BLOCKER'
            """ Snake-Food collision """
            # if snake collides with food, increase its length.
            if food_rect.colliderect(snake_rect):
                score += 1
                snake.increment_length()

                sound = pygame.mixer.Sound(point_path)
                sound.set_volume(0.3)
                sound.play()

                # generate food at random x, y.
                food.generate_food(width, height)

                # try generating the food at a position where blocks are not present.
                while food_collides_block(food.get_rect(), blocks):
                    food.generate_food(width - food.size, height - food.size)
            """ Draw """
            game_display.fill((255, 255, 255))
            showButton()

            # draw the food and snake.
            snake.draw(game_display, dirn, (0, 155, 0))
            food.draw(game_display, (0, 255, 0))

        # draw the blocks.
        for block in blocks:
            block.draw(game_display, (255, 0, 0))
        # count and display score on screen
        totalscore = total(score, world_num)
        scorestr = 'Score: ' + str(totalscore)
        font = pygame.font.SysFont(None, 30)
        text = font.render(scorestr, True, (0, 0, 255))
        game_display.blit(text, (0, 0, 20, 20))

        pygame.display.update()
        clock.tick(FPS)

    pygame.quit()
    quit()
Ejemplo n.º 22
0
class BoardManager():
    def __init__(self, nw_tile, nh_tile):
        self.nw_tile = nw_tile  # Set number of tile in x
        self.nh_tile = nh_tile  # Set number of tile in y

        self.number_body = 3  # Set number of snake's body
        self.score = 0  # Set score of sanke

        self.db_save_size = 6  # Column size of data base
        self.id = 0  # index of database's column
        self.type = 1
        self.x = 2
        self.y = 3
        self.s = 4
        self.t = 5

        self.enemy_dict = {}  # Enemy snake dictionary
        self.client_state_dict = {
            'OK': 0,
            'notNStart': 1,
            'notNExit': 2
        }  # KList state of client
        self.client_state = self.client_state_dict[
            'notNStart']  # State of cleint
        self.play_state = False  # Playing state
        self.game_time = 0  # time of game

        self.tile_mng = TileManager(width, height, self.nw_tile,
                                    self.nh_tile)  # Set TileManager
        self.snake = Snake(1, 1, self.tile_mng, green, SNAKE,
                           raw_input("Enter : "),
                           self.number_body)  # Set my sanke
        self.apple = Apple(0, 0, self.tile_mng, red, 0)  # Set apple
        self.hud = HUD()  # Set HUD

    # Update board
    def update(self):
        for event in pygame.event.get():  # Check all event
            if event.type == pygame.QUIT:  # Click Quit to quit program
                pygame.quit()  # quit programe
                quit()
            if event.type == pygame.KEYDOWN:  # If pressed keyboard
                if event.key == pygame.K_LEFT and not self.snake.get_move_list(
                        'right'):  # Pressed left and not go right
                    self.snake.set_left()  # Go left
                elif event.key == pygame.K_RIGHT and not self.snake.get_move_list(
                        'left'):  # Pressed right and not go left
                    self.snake.set_right()  # Go right
                elif event.key == pygame.K_UP and not self.snake.get_move_list(
                        'down'):  # Pressed up and not go down
                    self.snake.set_up()  # Go up
                elif event.key == pygame.K_DOWN and not self.snake.get_move_list(
                        'up'):  # Pressed down and not go up
                    self.snake.set_down()  # Go down
                elif event.key == pygame.K_x:  # Press x
                    self.snake.snake_slide(self.snake.get_move(),
                                           self.apple)  # Use slide snake skill
                elif event.key == pygame.K_c:  # Press c
                    self.snake.snake_running()  # Use running snake skill

        x_pos_ls = [
            int(self.snake.get_x_pos()[i] / self.tile_mng.get_sizew_tile())
            for i in range(self.snake.get_number_body())
        ]  # set x's list
        y_pos_ls = [
            int(self.snake.get_y_pos()[i] / self.tile_mng.get_sizeh_tile())
            for i in range(self.snake.get_number_body())
        ]  # set y's list
        x_pos_n = self.client.pos_pattern(
            x_pos_ls)  # save in string in postion pattern (x, y)
        y_pos_n = self.client.pos_pattern(y_pos_ls)
        pattern = self.client.set_pattern(self.snake.get_id(), [
            self.snake.get_type(), x_pos_n, y_pos_n,
            self.snake.get_score(), 0
        ])  # set pattern of all data
        # id,type,xs,ys,score,time

        if self.client_state == self.client_state_dict[
                'OK']:  # Client state is "OK"
            self.snake.snake_eat_apple(
                self.apple)  # Check does snake eat apple ?
            self.snake.update()  # Update snake
            if self.apple.get_eaten():  # Apple is eaten by snake
                pattern = "eaten"  # pattern is "eaten"
                self.apple.set_eaten(False)  # Apple is not eaten
        self.client.send(pattern)  # Send pattern to client

        data, addr = self.client.recv()  # Receive data from server
        if data == None:  # Data is none => exit method
            return
        if data == "notNStart":  # data is notNStart => set client state
            self.client_state = self.client_state_dict['notNStart']
        elif data == "notNExit":  # data is notNExit => set client state
            self.client_state = self.client_state_dict['notNExit']
        else:  # otherwise
            self.client_state = self.client_state_dict[
                'OK']  # Set client state to "OK"
            split_list = self.client.split(data)  # Split data
            for ls in split_list:
                self.game_time = int(ls[self.t])  # set time
                if ls[self.id] == "*":  # See id of apple
                    self.apple = Apple(int(ls[self.x]), int(ls[self.y]),
                                       self.tile_mng, red, str(ls[self.type]))
                elif ls[self.id] != self.snake.get_id() and ls[
                        self.id] != "*":  # See enemy snake's id
                    self.enemy_dict[ls[self.id]] = Snake(
                        0, 0, self.tile_mng, blue, ls[self.type], ls[self.id],
                        0)  # Save in dictionary of enemy snake
                    x_pos = self.client.pos_split(ls[self.x])
                    y_pos = self.client.pos_split(ls[self.y])
                    x_list = [
                        int(x_pos[i] * self.tile_mng.get_sizew_tile())
                        for i in range(len(x_pos))
                    ]
                    y_list = [
                        int(y_pos[i] * self.tile_mng.get_sizeh_tile())
                        for i in range(len(y_pos))
                    ]
                    self.enemy_dict[ls[self.id]].set_pos(
                        x_list, y_list)  # Set postion enemy snake

    # Render board
    def render(self):  # Render board
        game_display.fill(white)  # Background
        if self.client_state == self.client_state_dict[
                'OK']:  # Client state is OK
            if self.snake.state == 'dead':  # If dead
                # Draw dead HUD
                self.hud.dead_hud(game_display, self.snake.get_dead_ellapse(),
                                  self.snake.get_dead_delay(), width / 2,
                                  height / 2, width / 3, height / 3)
            else:
                self.apple.render(game_display)  # Render Apple
                self.snake.render(game_display,
                                  self.snake.get_number_body() -
                                  1)  # render snake
                for key in self.enemy_dict:  # Render enemy snake
                    self.enemy_dict[key].render(
                        game_display,
                        self.enemy_dict[key].get_number_body() - 1)
                # Draw time's hud, score' hud, gauge's hud
                self.hud.time_hud(game_display, self.game_time, width / 2,
                                  height * 0.05)
                self.hud.score_hud(game_display, self.snake.get_score(),
                                   width * 0.8, height * 0.05)
                self.hud.gauge_hud(
                    game_display,
                    min(
                        self.snake.get_slide_ellapse() /
                        self.snake.get_slide_delay(), 1), 0.6 * width,
                    0.95 * height, 0.4 * width, 0.02 * height)
                self.hud.gauge_hud(
                    game_display,
                    min(
                        self.snake.get_run_use_ellapse() /
                        self.snake.get_run_use_delay(), 1), 0.6 * width,
                    0.97 * height, 0.4 * width, 0.02 * height)
        pygame.display.update()  # Update display

    def loop(self):  # Loop to play always
        self.ip = raw_input("IP : ")  # Get IP
        self.client = ClientManager(self.ip, 8000)  # Set client
        packet = str(
            "tile:" + str(width) + "," + str(height) + "," +
            str(self.nw_tile) + "," + str(self.nh_tile)
        )  # Set pattern : width, height program and number of tile program
        self.client.send(packet)  # Send data to server
        self.client.close()  # Disconnnet socket
        while True:
            try:
                self.client = ClientManager(self.ip, 8000)  # Set client
                self.update()  # Update program
                self.render()  # Render program
                self.client.close()  # Disconnect from socket
            except KeyboardInterrupt:
                pygame.quit()  # Quit program
                quit()
        pygame.quit()  # Quit program
        quit()
Ejemplo n.º 23
0
class Game(object):
    board = Board()
    snake = Snake()
    food = Food()
    direction_flag = 'R'

    def __init__(self):
        pass
        # self.new_food()
        # self.board.clear()
        # self.board.put_snake(self.snake.getPoints())
        # self.board.put_food(self.food)

    def run(self):
        while True:
            frame_rate = pygame.time.Clock().tick(20)
            self.board = Board()
            # 检测例如按键等pygame事件
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        self.direction_flag = 'R'
                    elif event.key == pygame.K_LEFT:
                        self.direction_flag = 'L'
                    elif event.key == pygame.K_UP:
                        self.direction_flag = 'U'
                    elif event.key == pygame.K_DOWN:
                        self.direction_flag = 'D'

            food_position = copy.deepcopy(self.food.food_list())
            # food_position[0] += 20
            # food_position[1] += 20
            food_image = Utils.load_image('food.png').convert()
            self.board.screen.blit(food_image, (food_position[0], food_position[1]))

            snake_position = self.snake.pos_list
            for pos in snake_position:
                snake_head = Utils.load_image('snake_head.png').convert()
                self.board.screen.blit(snake_head, (pos[0], pos[1]))
                if len(snake_position) > 1:
                    snake_image = Utils.load_image('snake_head.png').convert()
                    self.board.screen.blit(snake_image, (pos[0], pos[1]))


                # pygame.draw.rect(self.self.board.screen, (255, 0, 0), temp_rect)
            pygame.display.update()
            snake_head = snake_position[0]

            if self.direction_flag == 'R':
                if snake_head[0] < 560:
                    self.snake.change_direction(self.direction_flag)
                    self.snake.move_direction()
                else:
                    self.direction_flag = 'D'
            elif self.direction_flag == 'D':
                if snake_head[1] < 400:
                    self.snake.change_direction(self.direction_flag)
                    self.snake.move_direction()
                else:
                    self.direction_flag = 'L'
            elif self.direction_flag == 'L':
                if snake_head[0] > 20:
                    self.snake.change_direction(self.direction_flag)
                    self.snake.move_direction()
                else:
                    self.direction_flag = 'U'
            elif self.direction_flag == 'U':
                if snake_head[1] > 20:
                    self.snake.change_direction(self.direction_flag)
                    self.snake.move_direction()
                else:
                    self.direction_flag = 'R'

            if snake_head == food_position:
                self.snake.eat_food(food_position)
                self.food.update_food()
Ejemplo n.º 24
0
class MyGame(arcade.Window):
    # define the initials
    def __init__(self, width, height, title):
        super().__init__(width, height, title, update_rate=10)

        # add snake
        self.snake = Snake()
        self.direction = UP
        self.grid = []
        self.defeat = False
        self.state = 0  # 1 instruction  0 menu 2 game 3 defeat
        # add apple
        self.apple = Apple()
        self.apple.produce(self.snake)

        for row in range(ROW_COUNT):
            # Add an empty array that will hold each cell
            # in this row
            self.grid.append([])
            for column in range(COLUMN_COUNT):
                self.grid[row].append(0)  # Append a cell

        self.add_snake_to_grid()

    def add_snake_to_grid(self):
        # add a cell for each block
        for i in range(ROW_COUNT):
            for j in range(COLUMN_COUNT):
                self.grid[i][j] = 0

        for i in range(1, self.snake.length):
            row = self.snake.body[i][0]
            col = self.snake.body[i][1]
            self.grid[row][col] = SNAKE

        # give a value to a block represent different types of apple
        if self.apple.score == 1:
            apple_x = self.apple.x
            apple_y = self.apple.y
            self.grid[apple_x][apple_y] = APPLE
        elif self.apple.score == 5:
            apple_x = self.apple.x
            apple_y = self.apple.y
            self.grid[apple_x][apple_y] = APPLE5

        # define the first snake body is snake head
        head = self.snake.body[0]
        self.grid[head[0]][head[1]] = S_HEAD

    def draw_menu(self):
        # button_i for instruction, button_s for start
        xi, yi, wi, hi = button_i
        xs, ys, ws, hs = button_s

        arcade.start_render()
        arcade.set_background_color(arcade.color.VANILLA)
        # display buttons and texts
        arcade.draw_text("Snakes",
                         width / 4 + 40,
                         height / 4 * 3,
                         arcade.color.BLACK,
                         font_size=50)
        arcade.draw_xywh_rectangle_filled(xi, yi, wi, hi,
                                          arcade.color.WHITE_SMOKE)
        arcade.draw_xywh_rectangle_filled(xs, ys, ws, hs,
                                          arcade.color.WHITE_SMOKE)

        arcade.draw_text("* Instructions",
                         width / 4 + 30,
                         height / 2 - 80,
                         arcade.color.BLACK,
                         font_size=35)
        arcade.draw_text(
            "* Start",
            width / 4 + 30,
            height / 2 + 50,
            arcade.color.BLACK,
            font_size=35,
        )

    def on_mouse_press(self, x, y, button, modifiers):
        # if click the buttons, change the state
        if self.state == 0:
            i_x, i_y, i_w, i_h = button_i
            s_x, s_y, s_w, s_h = button_s
            if x > i_x and x < i_x + i_w and y > i_y and y < i_y + i_h:
                self.state = 1
                self.snake.body = []
                self.draw_game()
            elif x > s_x and x < s_x + s_w and y > s_y and y < s_y + s_h:
                self.state = 2
        elif self.state == 1:
            b_x, b_y, b_w, b_h = button_b
            if x > b_x and x < b_x + b_w and y > b_y and y < b_y + b_h:
                # start a new game
                self.setup()
        elif self.state == 3:
            b2_x, b2_y, b2_w, b2_h = button_b2
            if x > b2_x and x < b2_x + b2_w and y > b2_y and y < b2_y + b2_h:
                # start a new game
                self.setup()

    # setup function reset all values to origin
    def setup(self):
        self.state = 0
        self.snake.body = []
        self.snake.direction = UP
        self.snake.length = 0
        self.snake.tail = []
        self.snake.add_body(4, 4)
        self.snake.score = 0
        self.snake.add_body(3, 4)
        self.snake.add_body(2, 4)
        self.angle = (self.direction - 10) * 90
        self.direction = UP

    def draw_instruction(self):
        # draw instruction interface
        arcade.draw_rectangle_filled(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2,
                                     SCREEN_WIDTH, SCREEN_HEIGHT,
                                     arcade.color.ROSE_GOLD)
        arcade.draw_text("Instructions",
                         width / 2 - 95,
                         600,
                         arcade.color.BLUE_GRAY,
                         font_size=35)
        arcade.draw_text("""
                              - The player as a snake in this game,
                                the player can use the keyboard
                                (up, down, right, left) to control the snake.
                              - The goal for the player is to eat as
                                many apples as they can.
                              - Only one apple is available for the player
                                 at each time.
                              - There will be random golden apple available
                                for the player to eat,
                                they can get five bonus if they successfully eat it,
                                the golden apple will disappear if the player
                                didn't eat it for a while.
                              - The head of the snake cannot touch its body,
                                or any places out to the grid.
                                If they do so, they will lose.
                              - Do not choose the direction which opposite with
                                the direction that the snake is moving on.
                                """,
                         5,
                         height / 4,
                         arcade.color.BLACK,
                         font_size=18)

        xb, yb, wb, hb = button_b
        arcade.draw_xywh_rectangle_filled(xb, yb, wb, hb,
                                          arcade.color.WHITE_SMOKE)
        arcade.draw_text("* Back",
                         xb,
                         yb,
                         arcade.color.ROSE_GOLD,
                         font_size=20)

    def draw_defeat(self):
        # draw defeat interface
        arcade.draw_rectangle_filled(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2,
                                     SCREEN_WIDTH, SCREEN_HEIGHT,
                                     arcade.color.RED)
        arcade.draw_text("YOU LOSE",
                         SCREEN_WIDTH / 2 - 70,
                         SCREEN_HEIGHT / 2,
                         arcade.color.WHITE_SMOKE,
                         font_size=35)
        # display your scores
        arcade.draw_text(f"Score: {str(self.snake.score)}",
                         SCREEN_WIDTH / 2 - 50,
                         SCREEN_HEIGHT / 2 - 50,
                         arcade.color.BLACK,
                         font_size=35)

        xb2, yb2, wb2, hb2 = button_b2
        arcade.draw_xywh_rectangle_filled(xb2, yb2, wb2, hb2,
                                          arcade.color.WHITE_SMOKE)
        arcade.draw_text("* Back",
                         xb2,
                         yb2,
                         arcade.color.ROSE_GOLD,
                         font_size=20)

    def draw_game(self):
        """
        Render the screen.
        """

        # This command has to happen before we start drawing
        arcade.start_render()
        # Draw the grid
        if self.defeat:
            arcade.set_background_color(arcade.color.ALLOY_ORANGE)
            arcade.draw_text("LOSE", 50, 50, arcade.color.BLACK)

        for row in range(ROW_COUNT):
            for column in range(COLUMN_COUNT):
                # Figure out what color to draw the box
                if self.grid[row][column] != SNAKE:
                    color = arcade.color.ARYLIDE_YELLOW

                # Do the math to figure out where the box is
                x = (MARGIN + WIDTH) * column + MARGIN + WIDTH // 2
                y = (MARGIN + HEIGHT) * row + MARGIN + HEIGHT // 2

                # Draw the box
                arcade.draw_rectangle_filled(x, y, WIDTH, HEIGHT, color)

                # Draw sprite
                if self.grid[row][column] == S_HEAD:
                    angle = (self.direction - 10) * 90
                    snake_head.draw(x, y, WIDTH, HEIGHT, angle=angle)
                elif self.grid[row][column] == APPLE:
                    red_apple.draw(x, y, WIDTH, HEIGHT)
                elif self.grid[row][column] == APPLE5:
                    golden_apple.draw(x, y, WIDTH, HEIGHT)
                elif self.grid[row][column] == SNAKE:
                    snake_body.draw(x, y, WIDTH, HEIGHT)

    def on_draw(self):
        # draw different interfaces
        if self.state == 0:
            self.draw_menu()
        elif self.state == 2:
            self.draw_game()
        elif self.state == 1:
            self.draw_instruction()
        elif self.state == 3:
            self.draw_defeat()

    def update(self, delta_time: float):
        # update all functions
        if self.state != 2:
            return

        if self.snake.update(self.direction):
            self.state = 3

        self.snake.eat_apple(self.apple)

        self.add_snake_to_grid()

    def on_key_press(self, key: int, modifiers: int):
        # use keyboard to control directions
        if key == arcade.key.UP:
            self.direction = UP
        elif key == arcade.key.DOWN:
            self.direction = DOWN
        elif key == arcade.key.LEFT:
            self.direction = LEFT
        elif key == arcade.key.RIGHT:
            self.direction = RIGHT
Ejemplo n.º 25
0
def main():
    start_timer = 0
    invincibility_time = 2

    view_width = 1000
    view_height = 600

    # Calculate game view rectangle starting position
    start_x = (width - view_width) / 2
    start_y = (height - view_height) / 2

    spawn_area_scale = (start_x, start_y, view_width, view_height)

    # COLOURS
    lives_display_col = (0, 0, 0)

    score = 0
    live_taken = False

    # Construct a snake
    snake = Snake(1023, 350, 3, 3, 15, (0, 0, 0))

    # Apple scale
    app_width = 10
    app_height = 10

    # Randomise apple position
    rand_x, rand_y = gen_random_spawn_location(app_width, app_height,
                                               spawn_area_scale)

    # Game loop
    while run:
        curr_time = time.time()

        # Draw background, needs to happen every frame
        window.fill((255, 255, 255))

        spawn_area = pygame.draw.rect(window, (98, 244, 66), spawn_area_scale)
        # (Simply Visual) Spawn Area Border
        pygame.draw.rect(window, (3, 132, 36), spawn_area_scale, 4)

        # Draw apple
        apple = pygame.draw.rect(window, (255, 0, 0),
                                 (rand_x, rand_y, app_width, app_height))

        # Player controls and other events
        get_key_entered(snake)

        if snake.lives > 0:

            if not live_taken:
                snake.draw_snake(window)
                snake.update_position()

            # If the apple was eaten
            if snake.eat(apple):
                # Spawn a new apple
                rand_x, rand_y = gen_random_spawn_location(
                    app_width, app_height, spawn_area_scale)

                # Update score
                score += 5

            print("Snake length: ", snake.segments.length)

            snake_x = snake.segments.head.rect.x
            snake_y = snake.segments.head.rect.y

            # The top left and top right corners of the snake head.
            # Those exact points create the exact boundary needed and at the same time save computation.
            s_tl = (snake_x, snake_y)
            s_tr = (snake_x + snake.segment_size, snake_y + snake.segment_size)

            not_collide_top_left = not spawn_area.collidepoint(s_tl)
            not_collide_top_right = not spawn_area.collidepoint(s_tr)

            if not_collide_top_left and not_collide_top_right and not live_taken:
                start_timer = curr_time
                snake.lives -= 1
                live_taken = True

                # RESPAWN
                temp_lives = snake.lives
                del snake
                snake = Snake(1023, 350, 3, 3, 15, (0, 0, 0))
                snake.lives = temp_lives

                # Set all segments in the snake to start at the head position
                for counter in range(0, snake.segments.length):
                    snake.segments.get_at_pos(counter).rect.x = 1023
                    snake.segments.get_at_pos(counter).rect.y = 350

            # Can loose a life again
            if round(curr_time - start_timer, 0) == invincibility_time:
                live_taken = False
                # Strange snake scale behaviour of snake when snake respawn runs here. (To inspect that just in case.)

        else:  # GAME OVER
            # pygame.display.update()  # this update causes flicker of the rectangle and text below

            pygame.draw.rect(
                window, (155, 50, 50),
                (start_x - 2, start_y - 2, view_width + 4, view_height + 4))
            GUI.display_text(window, "GAME OVER! ", 100, (0, 0, 0), [310, 300])

        # GUI
        GUI.display_text(window, "Score: " + str(score), 50, (0, 0, 0),
                         [40, 10])
        GUI.display_text(window, "Lives: " + str(snake.lives), 50, (0, 0, 0),
                         [910, 10])

        # Limit frames to 60
        clock.tick(60)

        # Displays the buffered data
        pygame.display.update()
Ejemplo n.º 26
0
class Game:
    def __init__(self,
                 width,
                 length,
                 n_apples,
                 snake_x0,
                 snake_y0,
                 d=direction.right,
                 render=False):
        self.width_ = width
        self.length_ = length
        self.n_apples_ = n_apples
        self.snake_x0_ = snake_x0
        self.snake_y0_ = snake_y0
        self.snake_ = None
        self.direction_ = d
        self.score_ = 0
        self.render_ = render
        self.reset()

        if self.render_:
            self.render()

    def reset(self):
        self.world_ = Map(self.width_, self.length_, self.n_apples_,
                          self.render_)
        self.snake_x0_ = 1 + np.random.randint(self.length_ - 2)
        self.snake_y0_ = 1 + np.random.randint(self.width_ - 2)
        self.direction_ = direction(np.random.randint(4))
        self.snake_ = Snake(self.snake_x0_, self.snake_y0_, self.direction_)
        self.world_.update(self.snake_)
        self.score_ = 0
        s = State(self.snake_, self.world_)
        s_array = np.concatenate((s.to_array(), [self.snake_.length_],
                                  directionToArray(self.snake_.direction_)))
        return s_array

    def render(self):
        self.world_.render()

    def step(self, d):
        t = Transition()
        t.state_ = State(self.snake_, self.world_)
        t.direction_ = d
        self.snake_.turn(d)
        score_move = self.snake_.move_forward(self.world_)
        self.world_.update(self.snake_)
        t.next_state_ = State(self.snake_, self.world_)
        #t.score_ = self.snake_.length_ - 1
        self.reward_ = self.snake_.length_ + score_move - 1
        #self.reward_ = score_move
        self.score_ = self.score_ + self.reward_

        state_array = np.concatenate(
            (t.next_state_.to_array(), [self.snake_.length_],
             directionToArray(self.snake_.direction_)))
        if self.render_:
            #print('\n\nnew step')
            #print("self.snake_.length_:{}".format(self.snake_.length_))
            #print("directionToArray(self.snake_.direction_):{}".format(directionToArray(self.snake_.direction_)))
            #t.next_state_.render()
            self.render()
        return (state_array, self.reward_, not self.snake_.isAlive(),
                t.direction_)

    def get_direction_input(self):
        with Input(keynames='curses') as input_generator:
            for e in input_generator:
                if e == 'KEY_UP':
                    return direction.up
                elif e == 'KEY_DOWN':
                    return direction.down
                elif e == 'KEY_LEFT':
                    return direction.left
                elif e == 'KEY_RIGHT':
                    return direction.right
                else:
                    print(e)
Ejemplo n.º 27
0
class Gameplay:

    ended = False
    pause = False
    gameOver = False

    cols = 40
    rows = 40

    boardSize = 0
    gapSize = 0
    blockSize = 0

    WHITE = [255, 255, 255]
    GRAY = [122, 122, 122]
    BLACK = [0, 0, 0]
    RED = [255, 0, 0]
    GREEN = [0, 255, 0]
    BLUE = [0, 0, 255]

    SNAKE_COLOR = WHITE
    HEAD_COLOR = WHITE
    BACKGROUND_COLOR = BLACK
    FIELD_COLOR = [10, 10, 10]
    EDGE_COLOR = WHITE
    GRID_COLOR = [40, 40, 40]
    FOOD_COLOR = GREEN
    TEXT_COLOR = WHITE

    startX = 0
    startY = 0

    score = -1

    tick = 0

    snake = None
    food = None
    grid = None

    def __init__(self, width, height):
        self.boardSize = min(width, height) - 30
        self.gapSize = 0
        self.blockSize = self.boardSize // self.cols - self.gapSize

        self.startX = 1.5 * self.blockSize
        self.startY = 1.5 * self.blockSize

        self.areWalls = True

        self.windowEvent = threading.Event()
        self.aiEvent = threading.Event()

        self.aiIsOn = False

        self.setGame()

    def setGame(self):

        self.makeGrid()
        self.snake = Snake(self.cols // 2, self.rows // 2, self)
        self.randomFood()

        self.setColors()
        self.setPause(False)
        self.setGameOver(False)

    def endGame(self):
        self.ended = True

    def setPause(self, state):
        self.pause = state
        if state:
            self.SNAKE_COLOR = self.GRAY
            self.HEAD_COLOR = self.GRAY
            self.EDGE_COLOR = self.GRAY
        else:
            self.SNAKE_COLOR = self.WHITE
            self.HEAD_COLOR = self.WHITE
            self.EDGE_COLOR = self.WHITE

        self.setColors()

    def getPause(self):
        return self.pause

    def setGameOver(self, state):
        self.gameOver = state
        if state:
            self.SNAKE_COLOR = self.RED
            self.HEAD_COLOR = self.RED
            self.EDGE_COLOR = self.RED
        else:
            self.SNAKE_COLOR = self.WHITE
            self.HEAD_COLOR = self.WHITE
            self.EDGE_COLOR = self.WHITE

        self.setColors()

    def getTick(self):
        return self.tick

    def setTickValue(self, val):
        self.tick = val

    def makeTick(self):
        self.tick -= 1

    def isGameOver(self):
        return self.gameOver

    def hasQuitted(self):
        return self.ended

    def quit(self):

        self.ended = True

    def setEvents(self):
        self.windowEvent.set()
        self.aiEvent.set()

    def isAiOn(self):
        return self.aiIsOn

    def turnOnAi(self):
        ai = SnakeAI(self)
        self.ai = threading.Thread(target=ai.run)
        self.aiIsOn = True
        self.ai.start()

    def turnOffAi(self):
        self.aiIsOn = False

    def randomFood(self):
        x = random.randint(1, self.cols - 2)
        y = random.randint(1, self.rows - 2)
        block = self.grid[x][y]

        while self.snake.contains(block):
            x = random.randint(1, self.cols - 2)
            y = random.randint(1, self.rows - 2)
            block = self.grid[x][y]

        block.setColor(self.FOOD_COLOR)

        self.food = block

    def makeGrid(self):

        newGrid = []
        for i in range(self.cols):
            newGrid.append([])
            for j in range(self.rows):

                newGrid[i].append(Block(i, j, self))

        self.grid = newGrid

    def setColors(self):

        for i in range(self.cols):
            for j in range(self.rows):
                if i == 0 or i == self.cols - 1 or j == 0 or j == self.rows - 1:
                    if self.areWalls:
                        color = self.EDGE_COLOR
                    else:
                        color = self.FIELD_COLOR
                else:
                    color = self.FIELD_COLOR

                self.grid[i][j].setColor(color)

        self.snake.setColor()
        self.food.setColor(self.FOOD_COLOR)

    def onPress(self, event):

        key_pressed = pygame.key.get_pressed()
        if event.type == pygame.KEYDOWN:
            if key_pressed[pygame.K_LEFT] and not self.pause:
                self.snake.turnLeft()
            elif key_pressed[pygame.K_RIGHT] and not self.pause:
                self.snake.turnRight()

            if key_pressed[pygame.K_p]:
                self.setPause(not self.pause)
            elif key_pressed[pygame.K_r]:
                self.setGame()
                self.setGameOver(False)
            elif key_pressed[pygame.K_0]:
                if self.aiIsOn:
                    self.turnOffAi()
                else:
                    self.turnOnAi()

            if key_pressed[pygame.K_1]:
                self.gapSize = 0
                self.blockSize = self.boardSize // self.cols - self.gapSize
            elif key_pressed[pygame.K_2]:
                self.gapSize = 1
                self.blockSize = self.boardSize // self.cols - self.gapSize
            elif key_pressed[pygame.K_3]:
                self.gapSize = 4
                self.blockSize = self.boardSize // self.cols - self.gapSize

            if key_pressed[pygame.K_e]:
                self.areWalls = not self.areWalls
                self.setColors()

    def lock(self):
        self.gameplayLock.acquire()

    def unlock(self):
        self.gameplayLock.release()

    def play(self):
        if not self.pause and not self.gameOver:
            self.snake.move()

    def draw(self, screen):

        if self.score != self.snake.getScore() or self.pause or self.gameOver:
            self.drawBackground(screen)
            self.drawGrid(screen)

            self.food.draw(screen)

            self.score = self.snake.getScore()
            self.drawInfo(screen)
        else:
            self.drawGrid(screen)
            self.food.draw(screen)

    def drawBackground(self, screen):
        screen.fill(self.BLACK)

    def drawGrid(self, screen):
        for i in range(self.cols):
            for j in range(self.rows):
                x = self.startX + i * (self.blockSize + self.gapSize)
                y = self.startY + j * (self.blockSize + self.gapSize)
                pygame.draw.rect(screen, self.GRID_COLOR, [
                    x - self.gapSize, y - self.gapSize, self.blockSize +
                    2 * self.gapSize, self.blockSize + 2 * self.gapSize
                ])

                self.grid[i][j].draw(screen)

    def drawInfo(self, screen):

        font1 = pygame.font.SysFont("comicsansms", 42)
        font2 = pygame.font.SysFont("comicsansms", 24)

        info1 = "SNAKE!"
        info2 = "by Piotr Maliszewski"
        info3 = "Score: {}".format(self.score)

        text1 = font1.render(info1, True, self.TEXT_COLOR)
        text2 = font2.render(info2, True, self.TEXT_COLOR)
        text3 = font1.render(info3, True, self.TEXT_COLOR)

        screen.blit(text1, (self.boardSize + 3 *
                            (self.blockSize + self.gapSize), self.startY))
        screen.blit(text2,
                    (self.boardSize + 4 * (self.blockSize + self.gapSize),
                     self.startY + 4 * (self.blockSize + self.gapSize)))
        screen.blit(text3,
                    (self.boardSize + 3 * (self.blockSize + self.gapSize),
                     self.startY + 6 * (self.blockSize + self.gapSize)))

        if self.gameOver:
            overText1 = font1.render("Game Over!", True, self.TEXT_COLOR)
            overText2 = font1.render("press r to restart", True,
                                     self.TEXT_COLOR)
            screen.blit(overText1,
                        ((self.boardSize - overText1.get_width()) // 3,
                         self.boardSize // 3))
            screen.blit(overText2,
                        ((self.boardSize - overText1.get_width()) // 3,
                         self.boardSize // 3 + 4 *
                         (self.blockSize + self.gapSize)))
        elif self.pause:
            pauseText1 = font1.render("Pause", True, self.TEXT_COLOR)
            pauseText2 = font1.render("press p to unpause", True,
                                      self.TEXT_COLOR)
            screen.blit(pauseText1,
                        ((self.boardSize - pauseText1.get_width()) // 3,
                         self.boardSize // 3))
            screen.blit(pauseText2,
                        ((self.boardSize - pauseText1.get_width()) // 3,
                         self.boardSize // 3 + 4 *
                         (self.blockSize + self.gapSize)))
Ejemplo n.º 28
0
 def reset(self):
     """Prepare for next run."""
     _Scene.reset(self)
     self.snake = Snake()
     self.walls = self.make_walls()
     self.apple = Apple(self.walls, self.snake)
Ejemplo n.º 29
0
    def update(self):
        for event in pygame.event.get():  # Check all event
            if event.type == pygame.QUIT:  # Click Quit to quit program
                pygame.quit()  # quit programe
                quit()
            if event.type == pygame.KEYDOWN:  # If pressed keyboard
                if event.key == pygame.K_LEFT and not self.snake.get_move_list(
                        'right'):  # Pressed left and not go right
                    self.snake.set_left()  # Go left
                elif event.key == pygame.K_RIGHT and not self.snake.get_move_list(
                        'left'):  # Pressed right and not go left
                    self.snake.set_right()  # Go right
                elif event.key == pygame.K_UP and not self.snake.get_move_list(
                        'down'):  # Pressed up and not go down
                    self.snake.set_up()  # Go up
                elif event.key == pygame.K_DOWN and not self.snake.get_move_list(
                        'up'):  # Pressed down and not go up
                    self.snake.set_down()  # Go down
                elif event.key == pygame.K_x:  # Press x
                    self.snake.snake_slide(self.snake.get_move(),
                                           self.apple)  # Use slide snake skill
                elif event.key == pygame.K_c:  # Press c
                    self.snake.snake_running()  # Use running snake skill

        x_pos_ls = [
            int(self.snake.get_x_pos()[i] / self.tile_mng.get_sizew_tile())
            for i in range(self.snake.get_number_body())
        ]  # set x's list
        y_pos_ls = [
            int(self.snake.get_y_pos()[i] / self.tile_mng.get_sizeh_tile())
            for i in range(self.snake.get_number_body())
        ]  # set y's list
        x_pos_n = self.client.pos_pattern(
            x_pos_ls)  # save in string in postion pattern (x, y)
        y_pos_n = self.client.pos_pattern(y_pos_ls)
        pattern = self.client.set_pattern(self.snake.get_id(), [
            self.snake.get_type(), x_pos_n, y_pos_n,
            self.snake.get_score(), 0
        ])  # set pattern of all data
        # id,type,xs,ys,score,time

        if self.client_state == self.client_state_dict[
                'OK']:  # Client state is "OK"
            self.snake.snake_eat_apple(
                self.apple)  # Check does snake eat apple ?
            self.snake.update()  # Update snake
            if self.apple.get_eaten():  # Apple is eaten by snake
                pattern = "eaten"  # pattern is "eaten"
                self.apple.set_eaten(False)  # Apple is not eaten
        self.client.send(pattern)  # Send pattern to client

        data, addr = self.client.recv()  # Receive data from server
        if data == None:  # Data is none => exit method
            return
        if data == "notNStart":  # data is notNStart => set client state
            self.client_state = self.client_state_dict['notNStart']
        elif data == "notNExit":  # data is notNExit => set client state
            self.client_state = self.client_state_dict['notNExit']
        else:  # otherwise
            self.client_state = self.client_state_dict[
                'OK']  # Set client state to "OK"
            split_list = self.client.split(data)  # Split data
            for ls in split_list:
                self.game_time = int(ls[self.t])  # set time
                if ls[self.id] == "*":  # See id of apple
                    self.apple = Apple(int(ls[self.x]), int(ls[self.y]),
                                       self.tile_mng, red, str(ls[self.type]))
                elif ls[self.id] != self.snake.get_id() and ls[
                        self.id] != "*":  # See enemy snake's id
                    self.enemy_dict[ls[self.id]] = Snake(
                        0, 0, self.tile_mng, blue, ls[self.type], ls[self.id],
                        0)  # Save in dictionary of enemy snake
                    x_pos = self.client.pos_split(ls[self.x])
                    y_pos = self.client.pos_split(ls[self.y])
                    x_list = [
                        int(x_pos[i] * self.tile_mng.get_sizew_tile())
                        for i in range(len(x_pos))
                    ]
                    y_list = [
                        int(y_pos[i] * self.tile_mng.get_sizeh_tile())
                        for i in range(len(y_pos))
                    ]
                    self.enemy_dict[ls[self.id]].set_pos(
                        x_list, y_list)  # Set postion enemy snake
Ejemplo n.º 30
0
print "total_lines: " + str(nibble.total_lines)
print "center_x: " + str(nibble.center_x)
print "center_y: " + str(nibble.center_y)
print "python's dir: " + os.getcwd()
print "script's dir: " + os.path.dirname(os.path.abspath(__file__))

# Create level
currentLevel = Level(1,nibble.total_columns,nibble.total_lines)
    
# Draw level
nibble.drawLevel(currentLevel)
nibble.displayMessage("Level" + str(nibble.level) + ",        Push Space")
nibble.drawLevel(currentLevel)

# Create a Snake
mySnake = Snake(nibble.center_x,nibble.center_y)

# Show the first Apple
apple = Apple(nibble.total_columns,nibble.total_lines,currentLevel,mySnake)
pygame.draw.rect(nibble.screen, (0, 255, 0), pygame.Rect(apple.getX(), apple.getY(), mySnake.size, mySnake.size),0)

pygame.mixer.init(48000, -16, 1, 1024)
sound_eat = pygame.mixer.Sound(os.path.dirname(os.path.abspath(__file__)) + '/hit.wav')
sound_crash = pygame.mixer.Sound(os.path.dirname(os.path.abspath(__file__)) + '/sounds/crash.ogg')
sound_game_over = pygame.mixer.Sound(os.path.dirname(os.path.abspath(__file__)) + '/sounds/reverse.ogg')

def resetLevel(mySnake):
    # Recreate Level 1
    global currentLevel
    currentLevel = Level(nibble.level,nibble.total_columns,nibble.total_lines) 
            if leer:
                ausschnitt.append(0)
            else:
                ausschnitt.append(1)

    # Schritt 2: in eine Zahl umwandeln
    wertigkeit = 1
    summe = 0
    # for binärziffer in ausschnitt:
    for stelle in range(kantenlänge**2):
        binärziffer = ausschnitt[stelle]
        maskiert = int(maske[stelle])
        if maskiert != 0:
            if binärziffer == 1:
                summe += wertigkeit
            wertigkeit = wertigkeit * 2
    # 0   1    0   0   1   0  0  0  0  Eingang
    # 1   1    1   1   0   1  1  1  1  Maske
    # 128 64   32  16      8  4  2  1

    return summe


if __name__ == "__main__":
    field = Field(10, 20)
    snake = Snake(field)

    number = situation_number(3, "111 111 111", snake.get_info())
    assert number == 16 + 128
    number = situation_number(3, "111 101 111", snake.get_info())
Ejemplo n.º 32
0
class App(object):
    def __init__(self):
        self._running = False
        self._main_clock = pygame.time.Clock()
        self._display_surf = None
        self.size = self.width, self.height = 640, 480
        self._game = Game()
        self._snake = Snake()
        self._snake.set_position(100, 100)

    def on_init(self):
        pygame.init()
        
        self._display_surf = pygame.display.set_mode(
                                self.size,
                                pygame.HWSURFACE | pygame.DOUBLEBUF)
        
        pygame.display.set_caption('Snake')

        self._running = True

    def on_event(self, event):
        if event.type == pygame.QUIT:
            self._running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                self._snake.set_direction(Snake.SNAKE_DIR_LEFT)
            if event.key == pygame.K_RIGHT:
                self._snake.set_direction(Snake.SNAKE_DIR_RIGHT)
            if event.key == pygame.K_UP:
                self._snake.set_direction(Snake.SNAKE_DIR_UP)
            if event.key == pygame.K_DOWN:
                self._snake.set_direction(Snake.SNAKE_DIR_DOWN)
            if event.key == pygame.K_SPACE:
                self._snake.set_direction(Snake.SNAKE_DIR_NONE)

    def on_cleanup(self):
        pygame.quit()
        sys.exit()

    def on_loop(self):
        """
        Calculations and objects update
        """
        self._snake.update()     
    
    def on_draw(self):
        """
        Draw all objects
        """
        self._display_surf.fill(Colors['BACKGROUND'])
        
        self._snake.draw(self._display_surf)
    
    def on_execute(self):
        self.on_init()
  
        """
        Main loop
        """
        while self._running:
            for event in pygame.event.get():
                self.on_event(event)

            self.on_loop()
            
            self.on_draw()
            
            pygame.display.flip()
            
            self._main_clock.tick(60)
        
        self.on_cleanup()
Ejemplo n.º 33
0
from Snake import Snake
from Population import Population
import time
import os

response = input(
    "Please select an option: \n\n1.Play snake game\n2.Let computer learn to play\n0.Exit program\n"
)

while response != "0":
    if response == "1":
        print("\nGame starting...")
        time.sleep(1)
        snake = Snake(True, 0)
        final_score = snake.new_game()
        print("\nYou finished with a score of: " + str(final_score))
    elif response == "2":
        print("\nYou have chosen to let the computer learn how to play.")
        print(
            "The computer learns to play by generating random populations of snakes and letting them evolve and reproduce."
        )
        print(
            "In essence, the computer is attempting to mimic how we evolve in nature."
        )
        print(
            "\nNow that you understand how the computer will learn, you need to decide how many generations to simulate."
        )
        print(
            "Each generation consists of 200 snakes. The snakes will move randomly at first but slowly learn to play over time."
        )
        print(
Ejemplo n.º 34
0
        food_dir = np.array((food_dir[1], -food_dir[0]))
    elif head_dir[1] == -1:
        food_dir = np.array((-food_dir[1], food_dir[0]))

    if food_dir[0] > 0:
        return 0
    elif food_dir[1] > 0:
        return 1
    elif food_dir[1] < 0:
        return 2
    else:
        return int(np.random.randint(1, 3, []))


if __name__ == '__main__':
    env = Snake(MAP_SIZE[0], MAP_SIZE[1])
    player = NaiveDQNPlayer(MAP_SIZE)
    for i in range(MAX_EPISODE):
        s = env.reset()
        step = 0
        policy = np.random.rand(1)[0] < EPSILON + i * 0.0005
        while not env.game_over:
            a = 0
            if policy or step > 100:
                a = int(player.choose_action(s))
            else:
                a = naive_action_plan(env.get_snake(), env.food)
            s_, r, _, _ = env.step(act_list[a])
            player.add_record(s, a, r, s_)
            s = s_
            if player.step >= player.batch and player.step % 5 == 0:
Ejemplo n.º 35
0
"""
Author: Christopher Schicho
Project: Snake
Version: 0.0
"""

import sys
import pygame
from Snake import Snake
from Food import Food
from Config import Config as cfg


snake = Snake()
food = Food(snake.snake)


class Game:

    def __init__(self):
        # start pygame
        pygame.init()
        self.clock = pygame.time.Clock()

        # window
        self.window = pygame.display.set_mode((cfg.width, cfg.height))
        pygame.display.set_caption("Snake by Christopher Schicho")

        # font
        self.font = pygame.font.SysFont("comicsansms", 30)
Ejemplo n.º 36
0
class Game:
    def __init__(self, window_width, window_height):
        # tiles and pixels
        self._nb_tile_x = 60
        self._tile_width = floor(window_width / self._nb_tile_x)
        self._width_px = self._tile_width * self._nb_tile_x
        self._nb_tile_y = floor(window_height / self._tile_width)
        self._height_px = self._tile_width * self._nb_tile_y

        # elements
        # screen
        self._screen = pygame.display.set_mode((self._width_px, self._height_px))
        self._background = pygame.image.load('../assets/grass.jpg')
        self._background = pygame.transform.scale(self._background, (self._width_px, self._height_px))
        # objects
        self._snake = Snake(self._nb_tile_x, self._nb_tile_y, self._tile_width)
        self._apple = Apple(self._nb_tile_x - 1, self._nb_tile_y - 1, self._tile_width)

        # other
        self._running = True

    def play(self):
        self.create_new_apple()
        while not self.has_lost() and self._running:
            self.manage_event()
            self.draw_screen()
            self._snake.move_head()
            if self.is_catching_the_apple():
                self.create_new_apple()
                self._snake.growth()
            else:
                self._snake.move_body()
            pygame.display.flip()
            time.sleep(0.05)

    def manage_event(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self._running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w or event.key == pygame.K_UP:
                    self._snake.direction_current = Direction.UP
                elif event.key == pygame.K_a or event.key == pygame.K_LEFT:
                    self._snake.direction_current = Direction.LEFT
                elif event.key == pygame.K_s or event.key == pygame.K_DOWN:
                    self._snake.direction_current = Direction.DOWN
                elif event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                    self._snake.direction_current = Direction.RIGHT

    def is_catching_the_apple(self):
        return self._apple.x == self._snake.head_x and self._apple.y == self._snake.head_y

    def has_lost(self):
        return self._snake.has_lost()

    def create_new_apple(self):
        apple_coord = self._apple.get_coordinate()
        while apple_coord in self._snake.body_coordinates or apple_coord == self._snake.get_head_coordinate():
            self._apple.set_new_coordinates(self._nb_tile_x - 1, self._nb_tile_y - 1)
            apple_coord = self._apple.get_coordinate()

    def draw_screen(self):
        # background
        self._screen.blit(self._background, (0, 0))

        # draw apple
        self._screen.blit(self._apple.image, self._apple.rect_i)

        # draw snake
        # head
        head_coordinate = self._snake.get_head_coordinate()
        rect = pygame.Rect(head_coordinate[0] * self._tile_width, head_coordinate[1] * self._tile_width,
                           self._tile_width, self._tile_width)
        pygame.draw.rect(self._screen, GREEN, rect)
        # body
        for part in self._snake.body_coordinates:
            rect = pygame.Rect(part[0] * self._tile_width, part[1] * self._tile_width, self._tile_width,
                               self._tile_width)
            pygame.draw.rect(self._screen, RED, rect)
Ejemplo n.º 37
0
class Game:
	"""The game of Snake."""

	def __init__(self, height, width, speed, placeObstacles=False):
		# Integer height of the plane
		self.height = height
		# Integer width of the plane
		self.width = width
		# Integer delay between frames of the of the game
		self.speed = speed
		# Integer score that is the length of the snake
		self.score = 0
		# The snake, starting on the left side of the plane
		self.snake = Snake(Square(height // 2, width // 2, self.width))
		# Boolean indicating whether to place obstacles or not
		self.placeObstacles = placeObstacles
		# Set of squares representing obstacles
		self.obstacles = set()
		# Square representing the food
		self.food = None

	def play(self):
		"""Play the game."""
		previousDirection = None
		listener = KeyListener()

		# Start the key listener
		listener.start()
		# Get the command for clearing the screen (dependent on OS)
		clearScreen = "cls" if platform.system() == "Windows" else "clear"
		# Place the first food
		self.placeFood()

		# Main game loop
		while not self.gameOver() and not listener.quit:
			# Display the game
			os.system(clearScreen)
			self.display(listener.paused)

			# Delay movement for the specified time
			time.sleep(self.speed)

			# Update the current direction
			currentDirection = listener.direction

			# Snake cannot immediately reverse direction
			if currentDirection == Direction.opposite(previousDirection):
				currentDirection = previousDirection

			# Move the snake if not paused
			if not listener.paused:
				self.move(currentDirection)

			# Store previous direction
			previousDirection = currentDirection

		# End the key listener
		listener.end()

		# Pause for 1 second
		time.sleep(1)

	def move(self, currentDirection):
		"""Move the snake."""
		next = self.nextSquare(currentDirection)

		if next:
			# Snake gets a food and grows by 1 square
			if next == self.food:
				self.snake.grow(next)
				self.placeFood()
				if self.placeObstacles:
					self.placeObstacle()

				self.score += 1
			# Snake moves to next square
			else:
				self.snake.advance(next)

	def display(self, paused):
		"""Display the game.

		paused -- boolean indicating whether the game is paused
		"""
		string = ""

		pausedString = "| PAUSED |"
		pausedString = pausedString if len(pausedString) + 2 <= self.width and paused else ""
		string += "+" + pausedString.center(self.width, "-") + "+\n"

		for row in reversed(range(self.height)):
			string += "|"
			for column in range(self.width):
				# Print the snake
				if Square(row, column, self.width) in self.snake:
					string += "O"
				# Print an obstacle
				elif Square(row, column, self.width) in self.obstacles:
					string += "&"
				# Print the food
				elif Square(row, column, self.width) == self.food:
					string += "+"
				# Print an empty space
				else:
					string += " "
			string += "|\n"

		# Display the score in the bottom border
		scoreString = "| SCORE: " + str(self.score) + " |"
		scoreString = scoreString if len(scoreString) + 2 <= self.width else "| " + str(self.score) + " |"
		string += "+" + scoreString.center(self.width, "-") + "+\n"

		print(string)

	def gameOver(self):
		"""Return whether the game is over."""
		head = self.snake.head()

		# Snake is out of bounds
		if head.x < 0 or head.x >= self.height or head.y < 0 or head.y >= self.width:
			return True
		# Snake has run into itself
		elif head in self.snake.snake[:-1]:
			return True
		# Snake has run into an obstacle
		elif head in self.obstacles:
			return True
		else:
			return False

	def nextSquare(self, currentDirection):
		"""Return the next square based off the snake's direction."""
		head = self.snake.head()

		if currentDirection == Direction.UP:
			return head.up()
		elif currentDirection == Direction.LEFT:
			return head.left()
		elif currentDirection == Direction.DOWN:
			return head.down()
		elif currentDirection == Direction.RIGHT:
			return head.right()

	def placeFood(self):
		"""Place the food on a random square on the plane."""
		x = random.randint(0, self.height - 1)
		y = random.randint(0, self.width - 1)

		food = Square(x, y, self.width)

		# Make sure not to place the food on the snake or an obstacle
		while food in self.snake or food in self.obstacles:
			x = random.randint(0, self.height - 1)
			y = random.randint(0, self.width - 1)

			food = Square(x, y, self.width)

		self.food = food

	def placeObstacle(self):
		"""Place an obstacle on a random square on the plane."""
		x = random.randint(0, self.height - 1)
		y = random.randint(0, self.width - 1)

		obstacle = Square(x, y, self.width)

		# Make sure not to place the obstacle on the snake or food
		while obstacle in self.snake or obstacle == self.food:
			x = random.randint(0, self.height - 1)
			y = random.randint(0, self.width - 1)

			obstacle = Square(x, y, self.width)

		self.obstacles.add(obstacle)
Ejemplo n.º 38
0
episodes_index = 0
moves_since_score = 0
danger_array = [0, 1]
dir_array = [Direction.UP, Direction.RIGHT, Direction.DOWN, Direction.LEFT]
food_dir_array = [-1, 0, 1]
q_model = QModel(generate_all_combinations([danger_array, danger_array, danger_array, dir_array,
                                            food_dir_array, food_dir_array]),
                 [AIDirectionChoice.LEFT, AIDirectionChoice.FORWARD, AIDirectionChoice.RIGHT])
player_died = False
player_ate = False
previous_dist = -1.0

state = GameState.RUNNING
last_tick = math.floor(time.time() * 1000)
grid = Grid(0, 100, WIDTH, HEIGHT - 100, 15, 15, 0, 5)
snake = Snake(grid.get_size())
food = Food(grid.get_size(), snake)
player_points = 0
player_direction = Direction.RIGHT

print("Grid size: %s" % (grid.get_size(),))

running = True
while running:
    time_now = math.floor(time.time() * 1000)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player_direction = Direction.LEFT
Ejemplo n.º 39
0
    def game_loop(self):
        """The game loop for 1 player mode"""
        snake_length = 6
        snake = Snake(snake_length, color=GREEN, game=self)
        apple = Apple(APPLE_SIZE, game=self)

        def game_reset():
            nonlocal snake, apple
            snake = Snake(snake_length, color=GREEN, game=self)
            apple = Apple(APPLE_SIZE, game=self)

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.game_exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT and snake.direction != 'RIGHT' and not snake.turned:
                        snake.started = True
                        snake.turned = True
                        snake.turn('LEFT')
                    elif event.key == pygame.K_RIGHT and snake.direction != 'LEFT' and not snake.turned:
                        snake.started = True
                        snake.turned = True
                        snake.turn('RIGHT')
                    elif event.key == pygame.K_UP and snake.direction != 'DOWN' and not snake.turned:
                        snake.started = True
                        snake.turned = True
                        snake.turn('UP')
                    elif event.key == pygame.K_DOWN and snake.direction != 'UP' and not snake.turned:
                        snake.started = True
                        snake.turned = True
                        snake.turn('DOWN')

            if snake.hit_wall() or snake.hit_tail():
                self.show_score(snake, game_reset)

            self.display.fill(WHITE)
            pygame.draw.rect(self.display, BLACK, [0, self.height, self.width, PANEL_HEIGHT])
            self.message("Score: " + str(snake.score), RED, h_align='left', v_align='bottom', off_set_y=20)
            apple.draw()
            snake.draw()

            if snake.started:
                snake.go()
                snake.turned = False

            pygame.display.update()

            if snake.eat(apple):
                apple = Apple(APPLE_SIZE, game=self)

            CLOCK.tick(FPS)
Ejemplo n.º 40
0
    def Show(self):   
        screen = self.display
        field = PlayField()
        group = Snake()
        group.ConstructSnake()
        feed = Food()
        block = feed.GetNewBlock(group.sprites())
        groupFood = pygame.sprite.Group()
        groupFood.add(block)

        print(block.rect.center)

        UPDATE = pygame.USEREVENT + 1
        pygame.time.set_timer(UPDATE,70)
        textsurface = Font.MonoSpace(15).render(str(self.highscore),False,Color.Black)

        ps4 = PS4Controller()
        ps4.init()
        print(ps4.joystick_present)
        if ps4.joystick_present:
            if not ps4.hat_data:
                ps4.hat_data = {}
                for i in range(ps4.controller.get_numhats()):
                    ps4.hat_data[i] = (0, 0)

        while not self.decision:
            self.CheckEvents()
            
            for event in pygame.event.get():
                if ps4.joystick_present:
                    if event.type == pygame.JOYHATMOTION:
                        ps4.hat_data[event.hat] = event.value
                        hatValues = ps4.hat_data[0]
                        if hatValues[0] == -1:
                            self.key = pygame.K_LEFT
                        elif hatValues[0] == 1:
                            self.key = pygame.K_RIGHT
                        elif hatValues[1] == -1:
                            self.key = pygame.K_DOWN
                        elif hatValues[1] == 1:
                            self.key = pygame.K_UP                       
                    
                if event.type==pygame.KEYDOWN:
                    self.key = event.key


                if event.type==UPDATE:
                    group.UpdateDirection(self.key)
                    game_over = not(pygame.sprite.collide_rect(field,group.sprites()[0])) or group.DetectCollisionWithItself()
                    if game_over:
                        self.decision = True
                        self.Quit(False)
                    else:
                        screen.fill(Color.White)
                        screen.blit(textsurface,(620,20))
                        group.Move()
                        group.draw(screen)
                        pygame.display.update()
                        groupFood.draw(screen)

                        if pygame.sprite.collide_rect(group.sprites()[0],groupFood.sprites()[0]):
                            group.EatFood(groupFood.sprites()[0])
                            block = feed.GetNewBlock(group.sprites())
                            groupFood.empty()
                            groupFood.add(block)
                            self.highscore+=1
                            textsurface = Font.MonoSpace(15).render(str(self.highscore),False,Color.Black)
Ejemplo n.º 41
0
body_path = os.path.join(base_path, "body.png")
tail_path = os.path.join(base_path, "tail.png")
apple_path = os.path.join(base_path, "apple.png")

pygame.init()

scene = pygame.display.set_mode(settings)
CLOCK = pygame.time.Clock()

head_img = pygame.image.load(head_path).convert()
body_img = pygame.image.load(body_path).convert()
tail_img = pygame.image.load(tail_path).convert()
apple_img = pygame.image.load(apple_path).convert()

apple = Apple(apple_img)
snake = Snake(head_img, body_img, tail_img)
allSprites = pygame.sprite.Group()
allSprites.add(snake.head)
allSprites.add(apple)

Running = True
score = 0


def process():
    global score
    global Running

    if snake.is_out_of_bounds or snake.is_eating_self:
        Running = False
Ejemplo n.º 42
0
WHITE = (255, 255, 255)
RED = (255, 0, 0)
ORANGE = (255, 165, 0)
YELLOW = (255, 255, 0)
ANOTHER_YELLOW = (230, 230, 5)
GREEN = (0, 255, 0)
LIGHTBLUE = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (128, 0, 128)
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3

apple = pygame.Rect(randint(3,87)*10, randint(3,47)*10, 10, 10)
new_snake = Snake(head_img, body_img, tail_img)
snake = [new_snake.get_head_rect()]
snakeHead = snake[0]


RAINBOW = [RED, ORANGE, ANOTHER_YELLOW, GREEN, LIGHTBLUE, BLUE, PURPLE]

dir = DOWN

def move_rect():

    global dir

    cur_y = snakeHead.y
    cur_x = snakeHead.x
Ejemplo n.º 43
0
 def __init__(self, screenProps):
     self.game = Snake.Snake(screenProps)
     self.winningScore = 21
Ejemplo n.º 44
0
 def __init__(self):
     '''
     Constructor
     '''
     self.snake = Snake()
Ejemplo n.º 45
0
def main():
    clock = pygame.time.Clock()
    window_width = 300
    window_height = 300
    display_width = 80
    display_height = 80

    game = True
    while game:
        score = 60
        game_display = Board(window_width, window_height)
        snake = Snake(20, 20, 3)
        food = Food(10, display_width, display_height, 10, snake)
        font = pygame.font.SysFont('Time New Roman, Arial', 20)
        text = font.render('Score: %d' % tuple([game_display.game_score]),
                           False, Board.gold)

        x_change = 0
        y_change = 0
        first_time = True
        eat = True
        mov = 0

        data_sets = np.arange(66)

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    game = False
                if event.type == pygame.KEYDOWN:
                    first_time = False
                    if event.key == pygame.K_LEFT:
                        if x_change != 10:
                            x_change = -10
                            y_change = 0
                            mov = 4
                    elif event.key == pygame.K_RIGHT:
                        if x_change != -10:
                            x_change = 10
                            y_change = 0
                            mov = 6
                    elif event.key == pygame.K_UP:
                        if y_change != 10:
                            x_change = 0
                            y_change = -10
                            mov = 8
                    elif event.key == pygame.K_DOWN:
                        if y_change != -10:
                            x_change = 0
                            y_change = 10
                            mov = 2

            if not first_time:
                data_sets = update_data_set(data_sets, mov, snake, food)
                snake.update(score)
            if score % 10 == 0 and eat:
                snake.append(
                    SnakeBody(snake[len(snake) - 1].x,
                              snake[len(snake) - 1].y))
                print(len(snake))
                eat = False
            snake.move_head(x_change, y_change)

            if (snake[0].x < food.food_x + 10 and snake[0].x >= food.food_x
                    and snake[0].y < food.food_y + 10
                    and snake[0].y >= food.food_y):
                score += 10
                game_display.game_score += 1
                food = Food(10, display_width, display_height, 10, snake)

                eat = True

            if snake.check_death(display_width, display_height):
                print("*****DEAD*****")
                restart = game_display.pop_exit_window(data_sets)
                if restart == True:
                    break

            game_display.clean()
            game_display.borders(display_height, display_width)
            pygame.draw.rect(
                game_display.GAME_display, Board.red,
                (food.food_x, food.food_y, Snake.factor, Snake.factor))
            snake.draw(game_display.GAME_display)
            game_display.GAME_display.blit(text, (game_display.width - 50, 50))
            pygame.display.flip()
            time.sleep(0.280)
            clock.tick(60)
Ejemplo n.º 46
0
def makeRectSegment(segment):
    return pygame.Rect(
            segment.x - segment.size / 2,
            segment.y + segment.size / 2,
            segment.size,
            segment.size)

# game options
width          = 600
height         = 400
gameDifficulty = 6 # the higher the difficulty, the faster the snake moves
random.seed()

# make snake alive
snakey = Snake(width/2, height/2, 0)
segmentRectQueue = deque()
segSize = snakey.theSnake[0].size

# configure pygame window 
pygame.init()
screenSize = width, height
screen = pygame.display.set_mode(screenSize, pygame.DOUBLEBUF)
screen.fill((255, 255, 255))
backgroundBlit = pygame.Surface((segSize, segSize))
backgroundBlit.fill((255, 255, 255))
pygame.display.set_caption('pySnake by bogu')


# make target alive
target = Segment(
Ejemplo n.º 47
0
from Apple import Apple
from Snake import Snake

pygame.init()

if __name__ == "__main__":
    width = 700
    height = 600

    dsply = pygame.display.set_mode((width, height))
    pygame.display.set_caption('Super Snake')
    bg = pygame.image.load("Assignment14/assets/img/background.png")
    font = pygame.font.Font('Assignment14/assets/font/ALGER.ttf', 32)
    clock = pygame.time.Clock()

    snake = Snake(dsply)
    apple = Apple(dsply)

    # Show Score Text
    text = font.render('Score: 0', True, (255, 255, 255))
    textRect = text.get_rect()
    textRect.center = (width // 2, 30)

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

        if not snake.x_move:
            if snake.x < apple.x or snake.x - 1 < apple.x or snake.x - 2 < apple.x or snake.x - 3 < apple.x or snake.x - 4 < apple.x:
                snake.direction = 'r'
Ejemplo n.º 48
0
 def divide_snake(self, snake):
     new_snake = Snake()
     new_snake.initial_parts(initial_length)
     self.derived_from(new_snake, snake)
     self.add_widget(new_snake)
     self.da_snakes.append(new_snake)
Ejemplo n.º 49
0
# Colors
red = pygame.Color(255, 0, 0)  # gameover
green = pygame.Color(0, 255, 0)  #snake
black = pygame.Color(0, 0, 0)  #score
white = pygame.Color(255, 255, 255)  #background
brown = pygame.Color(165, 42, 42)  #food

# FPS controller
fpsController = pygame.time.Clock()

#Instantiating players
numberOfPlayers = 2

#TODO:BEAUTIFY
snake1 = Snake(100, 100, 100, 100, 90, 100, 80, 100)
snake2 = Snake(100, 300, 100, 300, 90, 300, 80, 300)
print(snake1.snakeBody)
print(snake2.snakeBody)
snakes = [snake1, snake2]

foodPos = [
    random.randrange(1, frameWidth / 10) * 10,
    random.randrange(1, frameHeight / 10) * 10
]
foodSpawn = True


# Game over function
def gameOver():
    myFont = pygame.font.SysFont('monaco', 72)
Ejemplo n.º 50
0
    def game_loop_2p(self):
        """Game loop for 2 player mode"""
        snake_length = 6
        snake1 = Snake(snake_length, color=GREEN, game=self, name="Player 1")
        snake2 = Snake(snake_length, color=BLUE, game=self, img=SNAKE_HEAD_2, name="Player 2", offset_y=20)
        apple = Apple(APPLE_SIZE, game=self)

        def game_reset():
            nonlocal snake1, snake2, apple
            snake1 = Snake(snake_length, color=GREEN, game=self, name="Player 1")
            snake2 = Snake(snake_length, color=BLUE, game=self, img=SNAKE_HEAD_2, name="Player 2", offset_y=20)
            apple = Apple(APPLE_SIZE, game=self)

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.game_exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT and snake1.direction != 'RIGHT' and not snake1.turned:
                        snake1.turn('LEFT')
                    elif event.key == pygame.K_RIGHT and snake1.direction != 'LEFT' and not snake1.turned:
                        snake1.turn('RIGHT')
                    elif event.key == pygame.K_UP and snake1.direction != 'DOWN' and not snake1.turned:
                        snake1.turn('UP')
                    elif event.key == pygame.K_DOWN and snake1.direction != 'UP' and not snake1.turned:
                        snake1.turn('DOWN')
                    elif event.key == pygame.K_a and snake2.direction != 'RIGHT' and not snake2.turned:
                        snake2.turn('LEFT')
                    elif event.key == pygame.K_d and snake2.direction != 'LEFT' and not snake2.turned:
                        snake2.turn('RIGHT')
                    elif event.key == pygame.K_w and snake2.direction != 'DOWN' and not snake2.turned:
                        snake2.turn('UP')
                    elif event.key == pygame.K_s and snake2.direction != 'UP' and not snake2.turned:
                        snake2.turn('DOWN')

            self.display.fill(WHITE)

            pygame.draw.rect(self.display, BLACK, [0, self.height, self.width, PANEL_HEIGHT])
            self.message("Score: " + str(snake1.score), GREEN, h_align='left', v_align='bottom', off_set_y=20)
            self.message("Score: " + str(snake2.score), BLUE, h_align='right', v_align='bottom', off_set_y=20)

            apple.draw()
            snake1.draw()
            snake2.draw()

            snake1.go()
            snake2.go()

            if snake1.hit_wall() or snake1.hit_tail():
                snake1.die = True
            if snake2.hit_wall() or snake2.hit_tail():
                snake2.die = True

            if snake1.die and snake2.die:
                self.show_score(snake1, snake2, game_reset)

            pygame.display.update()

            if snake1.eat(apple) or snake2.eat(apple):
                apple = Apple(APPLE_SIZE, game=self)

            CLOCK.tick(FPS)
Ejemplo n.º 51
0
import pygame
from Objects import Apple, Pear, Bomb
from Snake import Snake

pygame.init()

if __name__ == "__main__":
    width = 700
    height = 600

    dsply = pygame.display.set_mode((width, height))
    pygame.display.set_caption('Super Snake')
    bg = pygame.image.load("Assignment11/assets/img/background.png")
    clock = pygame.time.Clock()

    snake = Snake(dsply)
    apple = Apple(dsply)
    pear = Pear(dsply)
    bomb = Bomb(dsply)

    # Show Score Text
    font = pygame.font.Font('Assignment11/assets/font/ALGER.ttf', 32)
    text = font.render('Score: 0', True, (255, 255, 255))
    textRect = text.get_rect()
    textRect.center = (width // 2, 30)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a or event.key == pygame.K_LEFT:
                    snake.grow_dir = 'l'
Ejemplo n.º 52
0
from Food import Food
from Score import Score
from Snake import Snake
from turtle import Screen
import time

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

snake = Snake()
food = Food()
score = Score()
screen.listen()

game_is_on = True

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

    if snake.segments[0].distance(food) < 15:
        food.create_food()
        score.increase_score()
        snake.increase_length()

    head = snake.segments[0]

    for segment in snake.segments[1:]:
Ejemplo n.º 53
0
class Worker():
    def __init__(self, name, trainer, model_path, global_episodes,
                 global_steps):
        self.name = "worker_" + str(name)
        self.number = name
        self.model_path = model_path
        self.trainer = trainer
        self.global_episodes = global_episodes
        self.increment_episodes = self.global_episodes.assign_add(1)
        self.global_steps = global_steps
        self.increment_steps = self.global_steps.assign_add(1)
        self.episode_rewards = []
        self.episode_lengths = []
        self.episode_mean_values = []
        self.summary_writer = tf.summary.FileWriter("train_" +
                                                    str(self.number))

        # Create the local copy of the network and the tensorflow op to copy global paramters to local network
        self.local_AC = AC_Network(self.name, trainer)
        self.update_local_ops = update_target_graph('global', self.name)

        print('Initializing environment #{}...'.format(self.number))
        self.env = Snake(grid_height=GRID_HEIGHT, grid_width=GRID_WIDTH)

    def train(self, rollout, sess, gamma, bootstrap_value):
        rollout = np.array(rollout)
        obs_grid = rollout[:, 0]
        actions = rollout[:, 1]
        rewards = rollout[:, 2]
        next_obs_grid = rollout[:, 3]
        values = rollout[:, 4]

        # Here we take the rewards and values from the rollout, and use them to calculate the advantage and discounted returns
        # The advantage function uses generalized advantage estimation from [2]
        self.rewards_plus = np.asarray(rewards.tolist() + [bootstrap_value])
        discounted_rewards = discount(self.rewards_plus, gamma)[:-1]
        self.value_plus = np.asarray(values.tolist() + [bootstrap_value])
        advantages = rewards + gamma * self.value_plus[
            1:] - self.value_plus[:-1]
        advantages = discount(advantages, gamma)

        # Update the global network using gradients from loss
        # Generate network statistics to periodically save
        feed_dict = {
            self.local_AC.target_v:
            discounted_rewards,
            self.local_AC.inputs:
            np.stack(obs_grid).reshape(-1, GRID_HEIGHT, GRID_WIDTH, 3),
            self.local_AC.actions:
            actions,
            self.local_AC.advantages:
            advantages
        }

        v_l, p_l, e_l, g_n, v_n, _ = sess.run([
            self.local_AC.value_loss, self.local_AC.policy_loss,
            self.local_AC.entropy, self.local_AC.grad_norms,
            self.local_AC.var_norms, self.local_AC.apply_grads
        ],
                                              feed_dict=feed_dict)
        return v_l / len(rollout), p_l / len(rollout), e_l / len(
            rollout), g_n, v_n

    def work(self, max_episode_length, gamma, sess, coord, saver):
        episode_count = sess.run(self.global_episodes)
        total_steps = 0
        print("Starting worker " + str(self.number))
        with sess.as_default(), sess.graph.as_default():
            while not coord.should_stop():
                # Download copy of parameters from global network
                sess.run(self.update_local_ops)

                episode_buffer = []
                episode_values = []
                episode_frames = []
                episode_reward = 0
                episode_step_count = 0
                episode_end = False

                # Start new episode
                obs = self.env.reset()
                episode_frames.append(obs)
                feature_stack = np.array([
                    np.zeros_like(self.env.grid),
                    np.zeros_like(self.env.grid),
                    np.zeros_like(self.env.grid)
                ])
                reward, features, episode_end = process_observation(obs)

                feature_stack = np.concatenate((feature_stack[1:], [features]))
                s_features = np.expand_dims(np.stack(feature_stack, axis=2),
                                            axis=0)
                while not episode_end:

                    # Take an action using distributions from policy networks' outputs
                    action_dist, v = sess.run(
                        [self.local_AC.policy_actions, self.local_AC.value],
                        feed_dict={self.local_AC.inputs: s_features})

                    # Apply filter to remove unavailable actions and then renormalize
                    for action_id, action_prob in enumerate(action_dist[0]):
                        if action_id not in obs.available_actions:
                            action_dist[0][action_id] = 0
                    if np.sum(action_dist[0]) != 1:
                        current_sum = np.sum(action_dist[0])
                        action_dist[0] /= current_sum

                    action = sample_dist(action_dist, self.global_steps)

                    obs = self.env.step(action)

                    r, features, episode_end = process_observation(obs)

                    feature_stack = np.concatenate(
                        (feature_stack[1:], [features]))
                    s1_features = np.expand_dims(np.stack(feature_stack,
                                                          axis=2),
                                                 axis=0)

                    if not episode_end:
                        episode_frames.append(obs)
                    else:
                        s1_features = s_features

                    # Append latest state to buffer
                    episode_buffer.append([
                        s_features, action, r, s1_features, episode_end, v[0,
                                                                           0]
                    ])
                    episode_values.append(v[0, 0])

                    episode_reward += r
                    s_features = s1_features
                    sess.run(self.increment_steps)
                    total_steps += 1
                    episode_step_count += 1

                    # If the episode hasn't ended, but the experience buffer is full, then we make an update step using that experience rollout
                    if len(
                            episode_buffer
                    ) == 30 and not episode_end and episode_step_count != max_episode_length - 1:
                        # Since we don't know what the true final return is, we "bootstrap" from our current value estimation
                        v1 = sess.run(
                            self.local_AC.value,
                            feed_dict={self.local_AC.inputs: s_features})[0, 0]
                        v_l, p_l, e_l, g_n, v_n = self.train(
                            episode_buffer, sess, gamma, v1)
                        episode_buffer = []
                        sess.run(self.update_local_ops)
                    if episode_end:
                        break

                self.episode_rewards.append(episode_reward)
                self.episode_lengths.append(episode_step_count)
                self.episode_mean_values.append(np.mean(episode_values))
                episode_count += 1

                global _max_score, _running_avg_score, _episodes, _steps
                if _max_score < episode_reward:
                    _max_score = episode_reward
                _running_avg_score = (2.0 / 101) * (
                    episode_reward - _running_avg_score) + _running_avg_score
                _episodes[self.number] = episode_count
                _steps[self.number] = total_steps

                if episode_count % 1 == 0:
                    print("{} Step #{} Episode #{} Reward: {}".format(
                        self.name, total_steps, episode_count, episode_reward))
                    print(
                        "Total Steps: {}\tTotal Episodes: {}\tMax Score: {}\tAvg Score: {}"
                        .format(sess.run(self.global_steps),
                                sess.run(self.global_episodes), _max_score,
                                _running_avg_score))

                # Update the network using the episode buffer at the end of the episode
                if len(episode_buffer) != 0:
                    v_l, p_l, e_l, g_n, v_n = self.train(
                        episode_buffer, sess, gamma, 0.0)

                if episode_count % 5 == 0 and episode_count != 0:
                    if episode_count % 10 == 0 and self.name == 'worker_0':
                        saver.save(
                            sess, self.model_path + '/model-' +
                            str(episode_count) + '.cptk')
                        print("Saved Model")

                    mean_reward = np.mean(self.episode_rewards[-5:])
                    mean_length = np.mean(self.episode_lengths[-5:])
                    mean_value = np.mean(self.episode_mean_values[-5:])
                    summary = tf.Summary()
                    summary.value.add(tag='Perf/Reward',
                                      simple_value=float(mean_reward))
                    summary.value.add(tag='Perf/Length',
                                      simple_value=float(mean_length))
                    summary.value.add(tag='Perf/Value',
                                      simple_value=float(mean_value))
                    summary.value.add(tag='Losses/Value Loss',
                                      simple_value=float(v_l))
                    summary.value.add(tag='Losses/Policy Loss',
                                      simple_value=float(p_l))
                    summary.value.add(tag='Losses/Entropy',
                                      simple_value=float(e_l))
                    summary.value.add(tag='Losses/Grad Norm',
                                      simple_value=float(g_n))
                    summary.value.add(tag='Losses/Var Norm',
                                      simple_value=float(v_n))
                    self.summary_writer.add_summary(summary, episode_count)

                    self.summary_writer.flush()
                if self.name == 'worker_0':
                    sess.run(self.increment_episodes)
Ejemplo n.º 54
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("Snake O Mania")
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")

is_game_on = True

while is_game_on:
    screen.update()
    time.sleep(.1)
    snake.move()
    # detecting the collision with food
    if snake.head.distance(food) < 15:
        food.refresh()
Ejemplo n.º 55
0
from kilo import led
from GamePadEmu import GamePadEmu
from Snake import Snake

if __name__ == "__main__":
    import time
    with GamePadEmu() as pad:
        anim = Snake(led, pad)
        try:
            anim.run(fps=30)
        except KeyboardInterrupt:
            led.all_off()
            led.update()
            time.sleep(1)