In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "how to achieve a simple gluttonous snake game based on Pygame", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to achieve a simple gluttonous snake game based on Pygame" this article.
Import related packages import pygame, sys, randomfrom pygame.locals import * set screen size and basic parameters
Set the screen size to 40000400 mainClock = pygame.time.Clock () to set time synchronization, not how many times the computer is running. MainClock.tick (1) will only run once a second, setting the background color of the screen to white.
# define the width and height of the screen WIDTH = 400HEIGHT = 40 "initialize the screen settings window title surface = pygame.display.set_mode ((WIDTH, HEIGHT), 0,32) pygame.display.set_caption ('gluttonous snake') pygame.init () mainClock = pygame.time.Clock () # define the color used BLACK = (0,0,0) GREEN = (0,255,0) WHITE = (255,255) While True: for event in pygame.event.get (): if event.type = = QUIT: pygame.quit () sys.exit () surface.fill (WHITE) pygame.display.update () mainClock.tick (1)
Set the location of the gluttonous snake and the size of the movement
The length and starting position of the gluttonous snake, and the width of the food and snake are set here, which must be set to a number that can be divisible by the width of the food and snake, so as to ensure that the snake can reach any position.
# set the initial length of the snake snakeWidth = set the starting position of the snake to (40) snakeX = 40snakeY = 4) set the width of the food and snake to 8FOODSNAKEWIDTH = define four directions moveLeft = FalsemoveRight = FalsemoveUp = FalsemoveDown = False# define the initial direction moveRight = Truedef getSnake (): # set the initial length of the snake to 4 and set the initial position of the snake to (40) # because gluttonous snakes can turn So set the snake to a list snake = [] for i in range (snakeWidth): snake.append (pygame.Rect (snakeX + I * FOODSNAKEWIDTH, snakeY, FOODSNAKEWIDTH, FOODSNAKEWIDTH)) return snake# gluttonous snake snake = getSnake () draw snake surface.fill (WHITE) for s in snake: pygame.draw.rect (surface, BLACK, s) make the snake move
Here the last bit of the snake list is removed, and then the position of the first bit is added or subtracted according to the direction.
Snake.pop () newTop = copy.deepcopy (snake [0]) # change the position of the snake if moveRight: newTop.left + = FOODSNAKEWIDTH if moveLeft: newTop.left-= FOODSNAKEWIDTH if moveUp: newTop.top-= FOODSNAKEWIDTH if moveDown: newTop.top + = FOODSNAKEWIDTH snake.insert (0, newTop)
There will be a problem, if we go beyond the screen, we will go beyond the screen, then it will disappear, we just need you to move the first element, and if you exceed it, move the element to another position.
# change the position of the snake if moveRight: if newTop.right = = WIDTH: newTop.left = 0 else: newTop.left + = FOODSNAKEWIDTH if moveLeft: if newTop.left = = 0: newTop.right = = WIDTH else: newTop.left-= FOODSNAKEWIDTH if moveUp: if newTop.top = = 0: newTop.bottom = HEIGHT Else: newTop.top-= FOODSNAKEWIDTH if moveDown: if newTop.bottom = = HEIGHT: newTop.top = 0 else: newTop.top + = FOODSNAKEWIDTH realize gluttonous snake turn
In order to achieve the corresponding function, we change the direction variable to a variable, so that we can easily modify the direction.
# define four directions # moveLeft moveRight moveUp moveDown# defines the initial direction snakeDirection = "moveRight"-omitted code-for event in pygame.event.get (): if event.type = = QUIT: pygame.quit () sys.exit () if event.type = = KEYDOWN: if event.key = = K_LEFT: If snakeDirection = "moveRight": snake.reverse () snakeDirection = "moveLeft" if event.key = = K_RIGHT: if snakeDirection = = "moveLeft": snake.reverse () snakeDirection = "moveRight" if event.key = = K_UP: if SnakeDirection = = "moveDown": snake.reverse () snakeDirection = "moveUp" if event.key = = K_DOWN: if snakeDirection = = "moveUp": snake.reverse () snakeDirection = "moveDown"
In order to see the effect, I set mainClock.tick (1) to mainClock.tick (3)
Realize random food
Here is a very verbose code, I can not see it myself, a little vague, here for simplicity only designed a food, traversing the screen is not gluttonous snake can put food collection, and then randomly generate a food.
If len (foods) < foodnum: canFoodColl = [] # get the location collection for x in range (sizeNum): for y in range (sizeNum): foodExist = True for sn in snake: if x * FOODSNAKEWIDTH = sn.left and y * FOODSNAKEWIDTH = sn.top: FoodExist = False break if foodExist: canFoodColl.append ({'xboys: X ) f = canFoodColl [random.randint (0, len (canFoodColl))] foods.append (pygame.Rect (f ['x'], f ['y'], FOODSNAKEWIDTH, FOODSNAKEWIDTH))
Eat food
Here colliderect is used to determine whether the two collide, and then the food set is empty without subtracting the last element of the gluttonous snake set.
If len (foods) < foodnum: canFoodColl = [] # get the location collection for x in range (sizeNum): for y in range (sizeNum): foodExist = True for sn in snake: if x * FOODSNAKEWIDTH = sn.left and y * FOODSNAKEWIDTH = sn.top: FoodExist = False break if foodExist: canFoodColl.append ({'xboys: X ) f = canFoodColl [random.randint (0, len (canFoodColl))] foods.append (pygame.Rect (f ['x'] * FOODSNAKEWIDTH, f ['y'] * FOODSNAKEWIDTH, FOODSNAKEWIDTH) FOODSNAKEWIDTH)) print (f ['x']) print (f ['y']) else: if newTop.colliderect (foods [0]): foods = [] eatFlg = True print ('xxx')
The complete code import pygame, sys, randomfrom pygame.locals import * import copy# defines the width and height of the screen WIDTH = 400HEIGHT = 40 "initialize the screen settings window title surface = pygame.display.set_mode ((WIDTH, HEIGHT), 0,32) pygame.display.set_caption ('gluttonous snake') pygame.init () mainClock = pygame.time.Clock () # define the color used BLACK = (0,0,0) GREEN = (0,255,0) WHITE = (255,255,255) # set the initial length of the snake snakeWidth = set the starting position of the snake to (40) 40) snakeX = 40snakeY = 4 the width of food and snake is set to 8FOODSNAKEWIDTH = define four directions # moveLeft moveRight moveUp moveDown# defines the initial direction snakeDirection = "moveRight" # food interval foods = [] # use the width to determine the corresponding size Minus 1 is the interval where the starting point of the food rectangle can exist # sizeNum = HEIGHT / FOODSNAKEWIDTH-"here in order to reduce the calculation of sizeNum = 3" for simplicity, we only set a food foodnum = 1def getSnake (): # set the initial length of the snake to 4, and set the snake's initial position to (40jue 40) # because gluttonous snakes turn. So set the snake to a list snake = [] for i in range (snakeWidth): snake.append (pygame.Rect (snakeX + I * FOODSNAKEWIDTH, snakeY, FOODSNAKEWIDTH) FOODSNAKEWIDTH) return snake# gluttonous snake snake = getSnake () while True: for event in pygame.event.get (): if event.type = = QUIT: pygame.quit () sys.exit () if event.type = = KEYDOWN: if event.key = = K_LEFT: if snakeDirection = = "moveRight": snake.reverse () snakeDirection = "moveLeft" if event.key = = K_RIGHT: if snakeDirection = = "moveLeft": snake.reverse () snakeDirection = "moveRight" if event.key = K_UP: if snakeDirection = = "moveDown": snake.reverse () SnakeDirection = "moveUp" if event.key = = K_DOWN: if snakeDirection = = "moveUp": snake.reverse () snakeDirection = "moveDown" surface.fill (WHITE) for s in snake: pygame.draw.rect (surface BLACK, s) for f in foods: pygame.draw.rect (surface, GREEN) F) pygame.display.update () # whether you ate the food eatFlg = False newTop = copy.deepcopy (snake [0]) # change the position of the snake if snakeDirection = = "moveRight": if newTop.right = = WIDTH: newTop.left = 0 else: newTop.left + = FOODSNAKEWIDTH if snakeDirection = "moveLeft": if newTop.left = = 0: NewTop.right = WIDTH else: newTop.left-= FOODSNAKEWIDTH if snakeDirection = = "moveUp": if newTop.top = = 0: newTop.bottom = HEIGHT else: newTop.top-= FOODSNAKEWIDTH if snakeDirection = = "moveDown": if newTop.bottom = = HEIGHT: newTop.top = 0 else: newTop.top + = FOODSNAKEWIDTH if len (foods ) < foodnum: canFoodColl = [] # get the location collection for x in range (sizeNum): for y in range (sizeNum): foodExist = True for sn in snake: if x * FOODSNAKEWIDTH = = sn.left and y * FOODSNAKEWIDTH = = sn.top: FoodExist = False break if foodExist: canFoodColl.append ({'xboys: X ) f = canFoodColl [random.randint (0, len (canFoodColl))] foods.append (pygame.Rect (f ['x'] * FOODSNAKEWIDTH, f ['y'] * FOODSNAKEWIDTH, FOODSNAKEWIDTH) FOODSNAKEWIDTH)) print (f ['x']) print (f ['y']) else: if newTop.colliderect (foods [0]): foods = [] eatFlg = True print ('xxx') snake.insert (0 NewTop) if not eatFlg: snake.pop () mainClock.tick (3) these are all the contents of the article "how to implement a simple Snake Game based on Pygame" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.