El juego Snake es uno de los juegos de arcade más populares de la historia. En este juego, el objetivo principal del jugador es atrapar la mayor cantidad de frutas sin chocar contra la pared ni contra sí mismo. Crear un juego de serpientes puede ser un desafío mientras se aprende Python o Pygame. Es uno de los mejores proyectos para principiantes que todo programador novato debería tomar como un desafío. Aprender un videojuego es algo interesante y divertido.
Usaremos juego de gaitero para crear este juego de serpientes. juego de gaitero es una biblioteca de código abierto diseñada para hacer videojuegos. Tiene bibliotecas gráficas y de sonido integradas. También es amigable para principiantes y multiplataforma.
Instalación
Para instalar Pygame, debe abrir su terminal o símbolo del sistema y escribir el siguiente comando:
pip install pygame
Después de instalar Pygame, estamos listos para crear nuestro genial juego de serpientes.
Un enfoque paso a paso para crear un juego de serpientes usando Pygame:
Paso 1: En primer lugar estamos importando las bibliotecas necesarias.
- Después de eso, estamos definiendo el ancho y el alto de la ventana donde se jugará el juego.
- Y definir el color en formato RGB que usaremos en nuestro juego para mostrar texto.
Python3
# importing libraries import pygame import time import random snake_speed = 15 # Window size window_x = 720 window_y = 480 # defining colors black = pygame.Color( 0 , 0 , 0 ) white = pygame.Color( 255 , 255 , 255 ) red = pygame.Color( 255 , 0 , 0 ) green = pygame.Color( 0 , 255 , 0 ) blue = pygame.Color( 0 , 0 , 255 ) |
Paso 2: Después de importar bibliotecas, debemos comenzar a usar Pygame pygame.init() método.
- Cree una ventana de juego utilizando el ancho y el alto definidos en el paso anterior.
- Aquí pygame.tiempo.Reloj() se usa más en la lógica principal del juego para cambiar la velocidad de la serpiente.
Python3
# Initialising pygame pygame.init() # Initialise game window pygame.display.set_caption( 'GeeksforGeeks Snakes' ) game_window = pygame.display.set_mode((window_x, window_y)) # FPS (frames per second) controller fps = pygame.time.Clock() |
Paso 3: Comience con la ubicación y el tamaño de la serpiente.
- Después de comenzar la posición de la serpiente, comience la posición de los resultados aleatoriamente en cualquier lugar en la altura y el ancho especificados.
- Al configurar la dirección a la DERECHA, nos aseguramos de que cada vez que un usuario ejecute el programa/juego, la serpiente debe moverse hacia la derecha de la pantalla.
Python3
# defining snake default position snake_position = [ 100 , 50 ] # defining first 4 blocks of snake # body snake_body = [ [ 100 , 50 ], [ 90 , 50 ], [ 80 , 50 ], [ 70 , 50 ] ] # fruit position fruit_position = [random.randrange( 1 , (window_x / / 10 )) * 10 , random.randrange( 1 , (window_y / / 10 )) * 10 ] fruit_spawn = True # setting default snake direction # towards right direction = 'RIGHT' change_to = direction |
Paso 4: Crea una función para mostrar la puntuación del jugador.
- En esta función, en primer lugar estamos creando un objeto de fuente, es decir. el color de la fuente irá aquí.
- Luego, usamos render para crear una superficie de fondo que cambiaremos cada vez que se actualice nuestra partitura.
- Cree un objeto rectangular para el objeto de superficie de texto (donde se actualizará el texto)
- Entonces estamos mostrando nuestra puntuación usando blit blit Hay dos argumentos pantalla.blit(fondo,(x,y))
Python3
# initial score score = 0 # displaying Score function def show_score(choice, color, font, size): # creating font object score_font score_font = pygame.font.SysFont(font, size) # create the display surface object # score_surface score_surface = score_font.render( 'Score : ' + str (score), True , color) # create a rectangular object for the # text surface object score_rect = score_surface.get_rect() # displaying text game_window.blit(score_surface, score_rect) |
Paso 5: Ahora cree una función de finalización del juego que muestre la puntuación después de que la serpiente haya chocado contra una pared o contra sí misma.
- En la primera línea, estamos creando un objeto de fuente para mostrar las puntuaciones.
- A continuación, estamos creando superficies de texto para dar puntajes.
- Después de eso, estamos configurando la posición del texto en el medio del área jugable.
- Mostrar las puntuaciones usando blit y actualice la puntuación actualizando la superficie con flip().
- Estamos usando sleep(2) para esperar 2 segundos antes de cerrar la ventana usando quit().
Python3
# game over function def game_over(): # creating font object my_font my_font = pygame.font.SysFont( 'times new roman' , 50 ) # creating a text surface on which text # will be drawn game_over_surface = my_font.render( 'Your Score is : ' + str (score), True , red) # create a rectangular object for the text # surface object game_over_rect = game_over_surface.get_rect() # setting position of the text game_over_rect.midtop = (window_x / 2 , window_y / 4 ) # blit will draw the text on screen game_window.blit(game_over_surface, game_over_rect) pygame.display.flip() # after 2 seconds we will quit the # program time.sleep( 2 ) # deactivating pygame library pygame.quit() # quit the program quit() |
Paso 6: Ahora crearemos nuestra función principal que hará lo siguiente:
- Estaremos validando las teclas que serán responsables del movimiento de la serpiente, luego crearemos una condición especial para que la serpiente no pueda moverse en la dirección opuesta instantáneamente.
- Después de eso, si una serpiente y frutas chocan, aumentaremos la puntuación en 10 y se comerán nuevas frutas.
- Después de eso, estamos comprobando si la serpiente ha chocado contra una pared o no. Si una serpiente golpea una pared, pondremos una función de fin de juego.
- Si la serpiente se golpea a sí misma, el juego habrá terminado.
- Y finalmente, mostraremos los puntajes usando la función show_score creada anteriormente.
Python3
# Main Function while True : # handling key events for event in pygame.event.get(): if event. type = = pygame.KEYDOWN: if event.key = = pygame.K_UP: change_to = 'UP' if event.key = = pygame.K_DOWN: change_to = 'DOWN' if event.key = = pygame.K_LEFT: change_to = 'LEFT' if event.key = = pygame.K_RIGHT: change_to = 'RIGHT' # If two keys pressed simultaneously # we don't want snake to move into two directions # simultaneously if change_to = = 'UP' and direction ! = 'DOWN' : direction = 'UP' if change_to = = 'DOWN' and direction ! = 'UP' : direction = 'DOWN' if change_to = = 'LEFT' and direction ! = 'RIGHT' : direction = 'LEFT' if change_to = = 'RIGHT' and direction ! = 'LEFT' : direction = 'RIGHT' # Moving the snake if direction = = 'UP' : serpiente_ubicación[ 1 ] - = 10 if direction = = 'DOWN' : serpiente_ubicación[ 1 ] + = 10 if direction = = 'LEFT' : serpiente_ubicación[ 0 ] - = 10 if direction = = 'RIGHT' : serpiente_ubicación[ 0 ] + = 10 # Snake body growing mechanism # if fruits and snakes collide then scores will be # incremented by 10 snake_body.insert( 0 , list (snake_position)) if serpiente_ubicación[ 0 ] = = resultados_ubicación[ 0 ] and serpiente_ubicación[ 1 ] = = resultados_ubicación[ 1 ]: score + = 10 fruit_spawn = False else : snake_body.pop() if not fruit_spawn: fruit_position = [random.randrange( 1 , (window_x / / 10 )) * 10 , random.randrange( 1 , (window_y / / 10 )) * 10 ] fruit_spawn = True game_window.fill(black) for pos in snake_body: pygame.draw.rect(game_window, green, pygame.Rect( posición[ 0 ]posición[ 1 ], 10 , 10 )) pygame.draw.rect(game_window, white, pygame.Rect( resultados_ubicación[ 0 ]resultados_ubicación[ 1 ], 10 , 10 )) # Game Over conditions if serpiente_ubicación[ 0 ] < 0 or serpiente_ubicación[ 0 ] > ventana_x - 10 : game_over() if serpiente_ubicación[ 1 ] < 0 or serpiente_ubicación[ 1 ] > ventana_y - 10 : game_over() # Touching the snake body for block in cuerpo_de_serpiente[ 1 :]: if serpiente_ubicación[ 0 ] = = bloquear[ 0 ] and serpiente_ubicación[ 1 ] = = bloquear[ 1 ]: game_over() # displaying score countinuously show_score( 1 , white, 'times new roman' , 20 ) # Refresh game screen pygame.display.update() # Frame Per Second /Refresh Rate fps.tick(snake_speed) |
A continuación se muestra la implementación
Python3
# importing libraries import pygame import time import random snake_speed = 15 # Window size window_x = 720 window_y = 480 # defining colors black = pygame.Color( 0 , 0 , 0 ) white = pygame.Color( 255 , 255 , 255 ) red = pygame.Color( 255 , 0 , 0 ) green = pygame.Color( 0 , 255 , 0 ) blue = pygame.Color( 0 , 0 , 255 ) # Initialising pygame pygame.init() # Initialise game window pygame.display.set_caption( 'GeeksforGeeks Snakes' ) game_window = pygame.display.set_mode((window_x, window_y)) # FPS (frames per second) controller fps = pygame.time.Clock() # defining snake default position snake_position = [ 100 , 50 ] # defining first 4 blocks of snake body snake_body = [[ 100 , 50 ], [ 90 , 50 ], [ 80 , 50 ], [ 70 , 50 ] ] # fruit position fruit_position = [random.randrange( 1 , (window_x / / 10 )) * 10 , random.randrange( 1 , (window_y / / 10 )) * 10 ] fruit_spawn = True # setting default snake direction towards # right direction = 'RIGHT' change_to = direction # initial score score = 0 # displaying Score function def show_score(choice, color, font, size): # creating font object score_font score_font = pygame.font.SysFont(font, size) # create the display surface object # score_surface score_surface = score_font.render( 'Score : ' + str (score), True , color) # create a rectangular object for the text # surface object score_rect = score_surface.get_rect() # displaying text game_window.blit(score_surface, score_rect) # game over function def game_over(): # creating font object my_font my_font = pygame.font.SysFont( 'times new roman' , 50 ) # creating a text surface on which text # will be drawn game_over_surface = my_font.render( 'Your Score is : ' + str (score), True , red) # create a rectangular object for the text # surface object game_over_rect = game_over_surface.get_rect() # setting position of the text game_over_rect.midtop = (window_x / 2 , window_y / 4 ) # blit will draw the text on screen game_window.blit(game_over_surface, game_over_rect) pygame.display.flip() # after 2 seconds we will quit the program time.sleep( 2 ) # deactivating pygame library pygame.quit() # quit the program quit() # Main Function while True : # handling key events for event in pygame.event.get(): if event. type = = pygame.KEYDOWN: if event.key = = pygame.K_UP: change_to = 'UP' if event.key = = pygame.K_DOWN: change_to = 'DOWN' if event.key = = pygame.K_LEFT: change_to = 'LEFT' if event.key = = pygame.K_RIGHT: change_to = 'RIGHT' # If two keys pressed simultaneously # we don't want snake to move into two # directions simultaneously if change_to = = 'UP' and direction ! = 'DOWN' : direction = 'UP' if change_to = = 'DOWN' and direction ! = 'UP' : direction = 'DOWN' if change_to = = 'LEFT' and direction ! = 'RIGHT' : direction = 'LEFT' if change_to = = 'RIGHT' and direction ! = 'LEFT' : direction = 'RIGHT' # Moving the snake if direction = = 'UP' : serpiente_ubicación[ 1 ] - = 10 if direction = = 'DOWN' : serpiente_ubicación[ 1 ] + = 10 if direction = = 'LEFT' : serpiente_ubicación[ 0 ] - = 10 if direction = = 'RIGHT' : serpiente_ubicación[ 0 ] + = 10 # Snake body growing mechanism # if fruits and snakes collide then scores # will be incremented by 10 snake_body.insert( 0 , list (snake_position)) if serpiente_ubicación[ 0 ] = = resultados_ubicación[ 0 ] and serpiente_ubicación[ 1 ] = = resultados_ubicación[ 1 ]: score + = 10 fruit_spawn = False else : snake_body.pop() if not fruit_spawn: fruit_position = [random.randrange( 1 , (window_x / / 10 )) * 10 , random.randrange( 1 , (window_y / / 10 )) * 10 ] fruit_spawn = True game_window.fill(black) for pos in snake_body: pygame.draw.rect(game_window, green, pygame.Rect(pos[ 0 ]posición[ 1 ], 10 , 10 )) pygame.draw.rect(game_window, white, pygame.Rect( resultados_ubicación[ 0 ]resultados_ubicación[ 1 ], 10 , 10 )) # Game Over conditions if serpiente_ubicación[ 0 ] < 0 or serpiente_ubicación[ 0 ] > ventana_x - 10 : game_over() if serpiente_ubicación[ 1 ] < 0 or serpiente_ubicación[ 1 ] > ventana_y - 10 : game_over() # Touching the snake body for block in cuerpo_de_serpiente[ 1 :]: if serpiente_ubicación[ 0 ] = = bloquear[ 0 ] and serpiente_ubicación[ 1 ] = = bloquear[ 1 ]: game_over() # displaying score countinuously show_score( 1 , white, 'times new roman' , 20 ) # Refresh game screen pygame.display.update() # Frame Per Second /Refresh Rate fps.tick(snake_speed) |
Producción:
Serpiente usando Pygame