1 安装python 和 pycharm
2 安装pygame 模块 直接在pycharm的terminate中 pip install pygame
然后,大致的流程为 如下图所示
-----------------------------------------------------------
首先我们需要画一个格子,我们可以想象蛇是由许多格子组成
代码如下
import pygame
import sys
from pygame.locals import * # 可以让你从键盘中输入
windows_width = 800 # 显示屏的高和宽
windows_height = 600
cell_size = 20 # 定义最小单元格的边长
blue = (0, 0, 255) # 格子的颜色
pygame.init() # pygame初始化
screen = pygame.display.set_mode((windows_width, windows_height)) # 显示屏幕
snake_coords = [{'x': 10, 'y': 10}] # 画一个小格子的坐标
while True: # 让界面一直都在
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
wormSegmentRect = (snake_coords[0]['x']*20, snake_coords[0]['y']*20, cell_size, cell_size) # 坐标,后面是长和宽
pygame.draw.rect(screen, blue, wormSegmentRect) # pygame画矩形函数,后面根三个参数
pygame.display.update() # 需要及时更新图像的情况(显示图像)
运行完毕代码如上图所示
--------------------------------------------------------------
好了,一个格子画完成,接下来画三个格子
代码如下:
import pygame
import sys
from pygame.locals import * # 可以让你从键盘中输入
windows_width = 800 # 显示屏的高和宽
windows_height = 600
cell_size = 20 # 定义最小单元格的边长
blue = (0, 0, 255) # 格子的颜色
pygame.init() # pygame初始化
screen = pygame.display.set_mode((windows_width, windows_height)) # 显示屏幕
snake_coords = [{'x': 10, 'y': 10}, {'x': 9, 'y': 10}, {'x': 8, 'y': 10}] # 画三个小格子的坐标
while True: # 让界面一直都在
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
for coords in snake_coords: # 遍历画三个格子
wormSegmentRect = (coords['x']*20, coords['y']*20, cell_size, cell_size) # 坐标,后面是长和宽
pygame.draw.rect(screen, blue, wormSegmentRect) # pygame画矩形函数,后面根三个参数
pygame.display.update() # 需要及时更新图像的情况(显示图像)
运行完毕代码如上图所示
----------------------------------------------------------------
接下来的目标,就是让三个方块动起来了
代码如下:
import pygame
import sys
from pygame.locals import * # 可以让你从键盘中输入
windows_width = 800 # 显示屏的高和宽
windows_height = 600
cell_size = 20 # 定义最小单元格的边长
blue = (0, 0, 255) # 格子的颜色
black = (0, 0, 0)
pygame.init() # pygame初始化
snake_speed_clock = pygame.time.Clock()
screen = pygame.display.set_mode((windows_width, windows_height)) # 显示屏幕
startx = 10 # 把蛇头的初始位置(x,y)单独拿出
starty = 10
snake_coords = [{'x': startx, 'y': starty}, {'x': startx-1, 'y': starty}, {'x': startx-2, 'y': starty}] # 画三个小格子的坐标
while True: # 让界面一直都在
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
screen.fill(black) # 该函数非常关键,读者可试试去除该函数的效果,蛇就不会移动了
for coords in snake_coords: # 遍历画三个格子
wormSegmentRect = (coords['x']*20, coords['y']*20, cell_size, cell_size) # 坐标,后面是长和宽
pygame.draw.rect(screen, blue, wormSegmentRect) # pygame画矩形函数,后面根三个参数
pygame.display.update() # 需要及时更新图像的情况(显示图像)
new = {'x': snake_coords[0]['x']+1, 'y': snake_coords[0]['y']} # 只加x坐标,表示向右移动(新蛇头)
snake_coords.insert(0, new) # 将蛇头插入列表中
snake_coords.pop() # 将蛇尾坐标在列表中删除
snake_speed_clock.tick(6) # 设置时钟为6,默认时钟是特别快的
----------------------------------------------------------------
随着代码规模的扩大,我们需要划分函数来避免代码的杂乱性
将上述代码化分为模块化,代码如下
import pygame
import sys
from pygame.locals import * # 可以让你从键盘中输入
windows_width = 800 # 显示屏的高和宽
windows_height = 600
cell_size = 20 # 定义最小单元格的边长
blue = (0, 0, 255) # 格子的颜色
black = (0, 0, 0)
def main():
pygame.init() # pygame初始化
snake_speed_clock = pygame.time.Clock()
screen = pygame.display.set_mode((windows_width, windows_height)) # 显示屏幕
startx = 10 # 把蛇头的初始位置(x,y)单独拿出
starty = 10
snake_coords = [{'x': startx, 'y': starty}, {'x': startx-1, 'y': starty}, {'x': startx-2, 'y': starty}] # 画三个小格子的坐标
while True: # 让界面一直都在
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
screen.fill(black) # 该函数非常关键,读者可试试去除该函数的效果,蛇就不会移动了
draw_snake(snake_coords, screen) # 画蛇
move_snake(snake_coords) # 蛇的坐标改变(蛇的移动)
pygame.display.update() # 需要及时更新图像的情况(显示图像)
snake_speed_clock.tick(6) # 设置时钟为6,默认时钟是特别快的
def draw_snake(snake_coords, screen):
for coords in snake_coords: # 遍历画三个格子
wormSegmentRect = (coords['x'] * 20, coords['y'] * 20, cell_size, cell_size) # 坐标,后面是长和宽
pygame.draw.rect(screen, blue, wormSegmentRect) # pygame画矩形函数,后面根三个参数
def move_snake(snake_coords):
new = {'x': snake_coords[0]['x'] + 1, 'y': snake_coords[0]['y']} # 只加x坐标,表示向右移动(新蛇头)
snake_coords.insert(0, new) # 将蛇头插入列表中
snake_coords.pop() # 将蛇尾坐标在列表中删除
if __name__ == '__main__':
main()
-----------------------------------------------------------------
让蛇移动后,下一步的任务就是 利用键盘来控制蛇的移动了
代码如下:
import pygame
import sys
from pygame.locals import * # 可以让你从键盘中输入
windows_width = 800 # 显示屏的高和宽
windows_height = 600
cell_size = 20 # 定义最小单元格的边长
blue = (0, 0, 255) # 格子的颜色
black = (0, 0, 0)
def main():
pygame.init() # pygame初始化
snake_speed_clock = pygame.time.Clock()
screen = pygame.display.set_mode((windows_width, windows_height)) # 显示屏幕
startx = 10 # 把蛇头的初始位置(x,y)单独拿出
starty = 10
direction = 'right' # 初始为向右移动
snake_coords = [{'x': startx, 'y': starty}, {'x': startx-1, 'y': starty}, {'x': startx-2, 'y': starty}] # 画三个小格子的坐标
while True: # 让界面一直都在
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN: # 如果从键盘中输入
if event.key == K_d and direction != 'left': # 默认方向的改变
direction = 'right'
if event.key == K_a and direction != 'right':
direction = 'left'
if event.key == K_w and direction != 'down':
direction = 'up'
if event.key == K_s and direction != 'up':
direction = 'down'
screen.fill(black) # 该函数非常关键,读者可试试去除该函数的效果,蛇就不会移动了
draw_snake(snake_coords, screen) # 画蛇
move_snake(snake_coords, direction) # 蛇的坐标改变(蛇的移动)
pygame.display.update() # 需要及时更新图像的情况(显示图像)
snake_speed_clock.tick(6) # 设置时钟为6,默认时钟是特别快的
def draw_snake(snake_coords, screen):
for coords in snake_coords: # 遍历画三个格子
wormSegmentRect = (coords['x'] * 20, coords['y'] * 20, cell_size, cell_size) # 坐标,后面是长和宽
pygame.draw.rect(screen, blue, wormSegmentRect) # pygame画矩形函数,后面根三个参数
def move_snake (snake_coords, direction):
if direction == 'right':
new = {'x': snake_coords[0]['x'] + 1, 'y': snake_coords[0]['y']} # 只加x坐标,表示向右移动(新蛇头)
elif direction == 'left':
new = {'x': snake_coords[0]['x'] - 1, 'y': snake_coords[0]['y']} # 减x坐标,表示向左移动(新蛇头)
elif direction == 'up':
new = {'x': snake_coords[0]['x'], 'y': snake_coords[0]['y']-1} # 减y坐标,表示向上移动(新蛇头)
elif direction == 'down': # 以左上角为为坐标原点,x向右为正向,y向下为正向
new = {'x': snake_coords[0]['x'], 'y': snake_coords[0]['y']+1} # 减y坐标,表示向下移动(新蛇头)
snake_coords.insert(0, new) # 将蛇头插入列表中
snake_coords.pop() # 将蛇尾坐标在列表中删除
if __name__ == '__main__':
main()
---------------------------------------------------------------------
让蛇能够用键盘控制后,下一步的做法,就是来随机生成一个食物了
代码如下
import pygame
import sys
import random
from pygame.locals import * # 可以让你从键盘中输入
windows_width = 800 # 显示屏的高和宽
windows_height = 600
cell_size = 20 # 定义最小单元格的边长
map_width = windows_width/cell_size # 以单元格为最小单位
map_height = windows_height/cell_size
blue = (0, 0, 255) # 格子的颜色
black = (0, 0, 0)
red = (255, 0, 0) # 食物的颜色
def main():
pygame.init() # pygame初始化
snake_speed_clock = pygame.time.Clock()
screen = pygame.display.set_mode((windows_width, windows_height)) # 显示屏幕
startx = 10 # 把蛇头的初始位置(x,y)单独拿出
starty = 10
food = random_food() # 初始化食物位置
direction = 'right' # 初始为向右移动
snake_coords = [{'x': startx, 'y': starty}, {'x': startx-1, 'y': starty}, {'x': startx-2, 'y': starty}] # 画三个小格子的坐标
while True: # 让界面一直都在
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN: # 如果从键盘中输入
if event.key == K_d and direction != 'left': # 默认方向的改变
direction = 'right'
if event.key == K_a and direction != 'right':
direction = 'left'
if event.key == K_w and direction != 'down':
direction = 'up'
if event.key == K_s and direction != 'up':
direction = 'down'
screen.fill(black) # 该函数非常关键,读者可试试去除该函数的效果,蛇就不会移动了
draw_snake(snake_coords, screen) # 画蛇
draw_food(food, screen) # 画食物
move_snake(snake_coords, direction) # 蛇的坐标改变(蛇的移动)
pygame.display.update() # 需要及时更新图像的情况(显示图像)
snake_speed_clock.tick(6) # 设置时钟为6,默认时钟是特别快的
def draw_snake(snake_coords, screen):
for coords in snake_coords: # 遍历画三个格子
wormSegmentRect = (coords['x'] * 20, coords['y'] * 20, cell_size, cell_size) # 坐标,后面是长和宽
pygame.draw.rect(screen, blue, wormSegmentRect) # pygame画矩形函数,后面根三个参数
def draw_food(food,screen):
pygame.draw.rect(screen, red, (food['x']*20,food['y']*20,cell_size,cell_size)) # 画食物函数
def move_snake (snake_coords, direction):
if direction == 'right':
new = {'x': snake_coords[0]['x'] + 1, 'y': snake_coords[0]['y']} # 只加x坐标,表示向右移动(新蛇头)
elif direction == 'left':
new = {'x': snake_coords[0]['x'] - 1, 'y': snake_coords[0]['y']} # 减x坐标,表示向左移动(新蛇头)
elif direction == 'up':
new = {'x': snake_coords[0]['x'], 'y': snake_coords[0]['y']-1} # 减y坐标,表示向上移动(新蛇头)
elif direction == 'down': # 以左上角为为坐标原点,x向右为正向,y向下为正向
new = {'x': snake_coords[0]['x'], 'y': snake_coords[0]['y']+1} # 减y坐标,表示向下移动(新蛇头)
snake_coords.insert(0, new) # 将蛇头插入列表中
snake_coords.pop() # 将蛇尾坐标在列表中删除
def random_food():
return {'x': random.randint(0, map_width-1), 'y': random.randint(0, map_height-1)} # 随机生成 x,y 坐标
if __name__ == '__main__':
main()
运行完毕代码如上图所示
-------------------------------------------------------------------
接下来,需要判断是否吃到食物,以及吃到食物后,新食物的随机生成
代码如下:
import pygame
import sys
import random
from pygame.locals import * # 可以让你从键盘中输入
windows_width = 800 # 显示屏的高和宽
windows_height = 600
cell_size = 20 # 定义最小单元格的边长
map_width = windows_width/cell_size # 以单元格为最小单位
map_height = windows_height/cell_size
blue = (0, 0, 255) # 格子的颜色
black = (0, 0, 0)
red = (255, 0, 0) # 食物的颜色
def main():
pygame.init() # pygame初始化
snake_speed_clock = pygame.time.Clock()
screen = pygame.display.set_mode((windows_width, windows_height)) # 显示屏幕
startx = 10 # 把蛇头的初始位置(x,y)单独拿出
starty = 10
food = random_food()
direction = 'right' # 初始为向右移动
snake_coords = [{'x': startx, 'y': starty}, {'x': startx-1, 'y': starty}, {'x': startx-2, 'y': starty}] # 画三个小格子的坐标
while True: # 让界面一直都在
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN: # 如果从键盘中输入
if event.key == K_d and direction != 'left': # 默认方向的改变
direction = 'right'
if event.key == K_a and direction != 'right':
direction = 'left'
if event.key == K_w and direction != 'down':
direction = 'up'
if event.key == K_s and direction != 'up':
direction = 'down'
screen.fill(black) # 该函数非常关键,读者可试试去除该函数的效果,蛇就不会移动了
draw_snake(snake_coords, screen) # 画蛇
draw_food(food, screen) # 画食物
move_snake(snake_coords, direction) # 蛇的坐标改变(蛇的移动)
flag = if_eat_food(snake_coords, food) # 判断是否吃到食物
if flag:
food = random_food() # 吃到则随机生成食物
pygame.display.update() # 需要及时更新图像的情况(显示图像)
snake_speed_clock.tick(6) # 设置时钟为6,默认时钟是特别快的
def draw_snake(snake_coords, screen):
for coords in snake_coords: # 遍历画三个格子
wormSegmentRect = (coords['x'] * 20, coords['y'] * 20, cell_size, cell_size) # 坐标,后面是长和宽
pygame.draw.rect(screen, blue, wormSegmentRect) # pygame画矩形函数,后面根三个参数
def draw_food(food,screen):
pygame.draw.rect(screen, red, (food['x']*20,food['y']*20,cell_size,cell_size))
def if_eat_food(snake_coords,food):
flag = 0
if snake_coords[0]['x'] == food['x'] and snake_coords[0]['y'] == food['y']:
new = {'x': snake_coords[-1]['x'], 'y': snake_coords[-1]['y']}
snake_coords.append(new)
flag = 1
return flag #吃到就新增加一节长度
def move_snake (snake_coords, direction):
if direction == 'right':
new = {'x': snake_coords[0]['x'] + 1, 'y': snake_coords[0]['y']} # 只加x坐标,表示向右移动(新蛇头)
elif direction == 'left':
new = {'x': snake_coords[0]['x'] - 1, 'y': snake_coords[0]['y']} # 减x坐标,表示向左移动(新蛇头)
elif direction == 'up':
new = {'x': snake_coords[0]['x'], 'y': snake_coords[0]['y']-1} # 减y坐标,表示向上移动(新蛇头)
elif direction == 'down': # 以左上角为为坐标原点,x向右为正向,y向下为正向
new = {'x': snake_coords[0]['x'], 'y': snake_coords[0]['y']+1} # 减y坐标,表示向下移动(新蛇头)
snake_coords.insert(0, new) # 将蛇头插入列表中
snake_coords.pop() # 将蛇尾坐标在列表中删除
def random_food():
return {'x': random.randint(0, map_width-1), 'y': random.randint(0, map_height-1)}
if __name__ == '__main__':
main()
-------------------------------------------------------------------
接下来只需要判断 蛇是否死亡
代码如下:
import pygame import sys import random from pygame.locals import * # 可以让你从键盘中输入 windows_width = 800 # 显示屏的高和宽 windows_height = 600 cell_size = 20 # 定义最小单元格的边长 map_width = windows_width/cell_size # 以单元格为最小单位 map_height = windows_height/cell_size blue = (0, 0, 255) # 格子的颜色 black = (0, 0, 0) red = (255, 0, 0) # 食物的颜色 def main(): pygame.init() # pygame初始化 snake_speed_clock = pygame.time.Clock() screen = pygame.display.set_mode((windows_width, windows_height)) # 显示屏幕 startx = 10 # 把蛇头的初始位置(x,y)单独拿出 starty = 10 food = random_food() direction = 'right' # 初始为向右移动 snake_coords = [{'x': startx, 'y': starty}, {'x': startx-1, 'y': starty}, {'x': startx-2, 'y': starty}] # 画三个小格子的坐标 while True: # 让界面一直都在 for event in pygame.event.get(): if event.type == QUIT: sys.exit() elif event.type == KEYDOWN: # 如果从键盘中输入 if event.key == K_d and direction != 'left': # 默认方向的改变 direction = 'right' if event.key == K_a and direction != 'right': direction = 'left' if event.key == K_w and direction != 'down': direction = 'up' if event.key == K_s and direction != 'up': direction = 'down' screen.fill(black) # 该函数非常关键,读者可试试去除该函数的效果,蛇就不会移动了 draw_snake(snake_coords, screen) # 画蛇 draw_food(food, screen) # 画食物 move_snake(snake_coords, direction) # 蛇的坐标改变(蛇的移动) flag = if_eat_food(snake_coords, food) #判断是否吃到食物 if flag: food = random_food() # 吃到则随机生成食物 if_die(snake_coords) pygame.display.update() # 需要及时更新图像的情况(显示图像) snake_speed_clock.tick(6) # 设置时钟为6,默认时钟是特别快的 def draw_snake(snake_coords, screen): for coords in snake_coords: # 遍历画三个格子 wormSegmentRect = (coords['x'] * 20, coords['y'] * 20, cell_size, cell_size) # 坐标,后面是长和宽 pygame.draw.rect(screen, blue, wormSegmentRect) # pygame画矩形函数,后面根三个参数 def draw_food(food,screen): pygame.draw.rect(screen, red, (food['x']*20,food['y']*20,cell_size,cell_size)) def if_eat_food(snake_coords,food): flag = 0 if snake_coords[0]['x'] == food['x'] and snake_coords[0]['y'] == food['y']: new = {'x': snake_coords[-1]['x'], 'y': snake_coords[-1]['y']} snake_coords.append(new) flag = 1 return flag def move_snake (snake_coords, direction): if direction == 'right': new = {'x': snake_coords[0]['x'] + 1, 'y': snake_coords[0]['y']} # 只加x坐标,表示向右移动(新蛇头) elif direction == 'left': new = {'x': snake_coords[0]['x'] - 1, 'y': snake_coords[0]['y']} # 减x坐标,表示向左移动(新蛇头) elif direction == 'up': new = {'x': snake_coords[0]['x'], 'y': snake_coords[0]['y']-1} # 减y坐标,表示向上移动(新蛇头) elif direction == 'down': # 以左上角为为坐标原点,x向右为正向,y向下为正向 new = {'x': snake_coords[0]['x'], 'y': snake_coords[0]['y']+1} # 减y坐标,表示向下移动(新蛇头) snake_coords.insert(0, new) # 将蛇头插入列表中 snake_coords.pop() # 将蛇尾坐标在列表中删除 def random_food(): return {'x': random.randint(0, map_width-1), 'y': random.randint(0, map_height-1)} def if_die(snake_coords): if snake_coords[0]['x'] < 0 or snake_coords[0]['x'] > map_width: terminate() if snake_coords[0]['y'] < 0 or snake_coords[0]['y'] > map_height: terminate() for coord in snake_coords[1:]: if coord['x'] == snake_coords[0]['x'] and coord['y'] == snake_coords[0]['y']: terminate() def terminate(): pygame.quit() sys.exit() if __name__ == '__main__': main()
---------------------------------------------------------------------------