当前位置:网站首页>How to make a simple Snake game with pyGame
How to make a simple Snake game with pyGame
2022-06-10 16:51:00 【InfoQ】
1. preface
2. Installation and import
import pygame,sys,random
from pygame.locals import *
3. Define the subsequent required parameters
# initialization pygame library
pygame.init()
# Initialize a game interface
DISPLAY=pygame.display.set_mode((800,800))
# Set game window title
pygame.display.set_caption(' snake ')
# Define a variable to control the game speed
FPSCLOCK=pygame.time.Clock()
# Define color
BLACK=pygame.Color(0,0,0)
WHITE=pygame.Color(255,255,255)
RED=pygame.Color(255,0,0)
# Define the initial position of the snake head
snake_Head=[100,100]
# Define the initial length of a snake , Because the interfaces are 20*20 So the length is minus 20
snake_Body=[[80,100], [60,100]]
# # The initial direction of the snake
direction="right"
# Define variables that change direction , Key
changeDirection = direction
# Define the initial food location
food_Postion = [300,300]
# Define food status ,0 Means to be eaten ,1 It means not being eaten
food_Total = 1
4. Draw snakes and food
# Draw greedy snake
def drawSnake(snake_Body):
for i in snake_Body:
pygame.draw.rect(DISPLAY,WHITE,Rect(i[0],i[1],20,20))
# Draw food location
def drawFood(food_Postion):
pygame.draw.rect(DISPLAY,RED,Rect(food_Postion[0],food_Postion[1],20,20))
5. Game rules and operation
def gameover():
# sign out pygame
pygame.quit()
# Exit procedure
sys.exit()
game_flag=True
while game_flag:
# Render the background color
DISPLAY.fill(BLACK)
# Draw a greedy snake
drawSnake(snake_Body)
# Draw the food position
drawFood(food_Postion)
# Increase game speed
game_speed=1+len(snake_Body)//3
# Refresh the display layer , Greedy snakes and food move every time , Will refresh the display layer
pygame.display.flip()
FPSCLOCK.tick(game_speed)
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
# If it's a right arrow or d, The snake moves to the right
if event.key == K_RIGHT or event.key == K_d:
changeDirection = 'right'
# If it's an arrow or a, The snake moves to the left
if event.key == K_LEFT or event.key == K_a:
changeDirection = 'left'
if event.key == K_UP or event.key == K_w:
changeDirection = 'up'
if event.key == K_DOWN or event.key == K_s:
changeDirection = 'down'
# Click on esc, sign out
if event.key == KSCAN_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
# Confirm the direction , Determine if the reverse direction is entered
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
# Move the snake's head according to the direction
if direction=='right':
snake_Head[0]+=20
if direction=='left':
snake_Head[0]-=20
if direction=='up':
snake_Head[1]-=20
if direction=='down':
snake_Head[1]+=20
# Increase the length of the snake
snake_Body.insert(0,list(snake_Head))
# Judge whether you have food
if snake_Head[0] == food_Postion[0] and snake_Head[1] == food_Postion[1]:
food_Total = 0
else:
snake_Body.pop()
if food_Total == 0:
x = random.randrange(1, 32)
y = random.randrange(1, 24)
food_Postion = [int(x * 20), int(y * 20)]
food_Total = 1
if snake_Head[0] > 800 or snake_Head[0] < 0:
gameover()
elif snake_Head[0] > 800 or snake_Head[0] < 0:
gameover()
# If you meet yourself
for body in snake_Body[1:]:
if snake_Head[0] == body[0] and snake_Head[1] == body[1]:
gameover()
6. Finished product display

7. Complete code
import pygame,sys,random
from pygame.locals import *
# initialization pygame library
pygame.init()
# Initialize a game interface
DISPLAY=pygame.display.set_mode((800,800))
# Set game window title
pygame.display.set_caption(' snake ')
# Define a variable to control the game speed
FPSCLOCK=pygame.time.Clock()
# Define color
BLACK=pygame.Color(0,0,0)
WHITE=pygame.Color(255,255,255)
RED=pygame.Color(255,0,0)
# Define the initial position of the snake head
snake_Head=[100,100]
# Define the initial length of a snake , Because the interfaces are 20*20 So the length is minus 20
snake_Body=[[80,100], [60,100],[40,100]]
# # The initial direction of the snake
direction="right"
# Define variables that change direction , Key
changeDirection = direction
# Define the initial food location
food_Postion = [300,300]
# Define food status ,0 Means to be eaten ,1 It means not being eaten
food_Total = 1
# Draw greedy snake
def drawSnake(snake_Body):
for i in snake_Body:
pygame.draw.rect(DISPLAY,WHITE,Rect(i[0],i[1],20,20))
# Draw food location
def drawFood(food_Postion):
pygame.draw.rect(DISPLAY,RED,Rect(food_Postion[0],food_Postion[1],20,20))
def gameover():
# sign out pygame
pygame.quit()
# Exit procedure
sys.exit()
game_flag=True
while game_flag:
# Render the background color
DISPLAY.fill(BLACK)
# Draw a greedy snake
drawSnake(snake_Body)
# Draw the food position
drawFood(food_Postion)
# Increase game speed
game_speed=1+len(snake_Body)//3
# Refresh the display layer , Greedy snakes and food move every time , Will refresh the display layer
pygame.display.flip()
FPSCLOCK.tick(game_speed)
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
# If it's a right arrow or d, The snake moves to the right
if event.key == K_RIGHT or event.key == K_d:
changeDirection = 'right'
# If it's an arrow or a, The snake moves to the left
if event.key == K_LEFT or event.key == K_a:
changeDirection = 'left'
if event.key == K_UP or event.key == K_w:
changeDirection = 'up'
if event.key == K_DOWN or event.key == K_s:
changeDirection = 'down'
# Click on esc, sign out
if event.key == KSCAN_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
# Confirm the direction , Determine if the reverse direction is entered
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
# Move the snake's head according to the direction
if direction=='right':
snake_Head[0]+=20
if direction=='left':
snake_Head[0]-=20
if direction=='up':
snake_Head[1]-=20
if direction=='down':
snake_Head[1]+=20
# Increase the length of the snake
snake_Body.insert(0,list(snake_Head))
# Judge whether you have food
if snake_Head[0] == food_Postion[0] and snake_Head[1] == food_Postion[1]:
food_Total = 0
else:
snake_Body.pop()
if food_Total == 0:
x = random.randrange(1, 32)
y = random.randrange(1, 24)
food_Postion = [int(x * 20), int(y * 20)]
food_Total = 1
if snake_Head[0] > 800 or snake_Head[0] < 0:
gameover()
elif snake_Head[0] > 800 or snake_Head[0] < 0:
gameover()
# If you meet yourself
for body in snake_Body[1:]:
if snake_Head[0] == body[0] and snake_Head[1] == body[1]:
gameover()
边栏推荐
- 毕业季:致走向辽远未知的你
- Take you to play completablefuture asynchronous programming
- Enroulez - vous, brisez l'anxiété de 35 ans, l'animation montre le processeur enregistrer le processus d'appel de fonction, entrer dans l'usine d'interconnexion est si simple
- When visual studio 2019 is installed, vs installer cannot download files. The progress bar is 0. It shows the solutions to network problems
- Research Report on the development scale of Chinese sanatorium industry and the 14th five year plan (2022-2028)
- 纽约金融监管机构发布正式的稳定币指南
- 互联网企业与芯片
- Fiddler为测试做什么
- 卷起來,突破35歲焦慮,動畫演示CPU記錄函數調用過程,進互聯大廠如此簡單
- Rethinking atlas revolution for semantic image segmentation (deeplobv3) personal summary
猜你喜欢

AI video cloud: a good wife in the era of we media

接口测试学习笔记

How does Dao achieve decentralized governance?

Fiddler设置断点

Carry forward the past and forge ahead into the future, multiple residuals | densenet (I)

Basic use cases for jedis

看先进科技如何改变人类生活

Why do I need a thread pool? What is pooling technology?

Fosun Group hekaiduo: grow together with Alibaba cloud and help business innovation
![Jerry's ble dynamic power regulation [chapter]](/img/29/22be6dca25c4e6502f076fee73dd44.png)
Jerry's ble dynamic power regulation [chapter]
随机推荐
Why do I need a thread pool? What is pooling technology?
MM主要的表和主要字段_SAP刘梦_
AttributeError: module ‘gym. envs. Box2d 'has no attribute' lunarlander 'solution
mysql数据库实现设置字段长度
Jerry's long press reset and high level reset [chapter]
Weilai quarterly report diagram: the revenue was 9.9 billion yuan, a year-on-year increase of 24%, and the operating loss was nearly 2.2 billion yuan
What is the 100th trillion digit of PI decimal point? Google gives the answer with Debian server
PHP wechat H5 payment demo
CAN总线协议基础
Devops-3 cloud computing and cloud era operation and maintenance
那年高考
Li Ling: in six years, how did I go from open source Xiaobai to Apache top project PMC
Pytorch installation tutorial
Li Ling: in six years, how did I go from open source Xiaobai to Apache top project PMC
PV operation daily question - orange apple question (advanced version variant)
面试题-笔试
Full array of arrays
Zhangxiaobai teaches you how to use Ogg to synchronize Oracle 19C data with MySQL 5.7 (1)
Comply with medical reform and actively layout -- insight into the development of high-value medical consumables under the background of centralized purchase 2022
Diagram of the quarterly report of station B: the revenue is RMB 5.1 billion, with a year-on-year increase of 30% and nearly 300million monthly active users