单机版的小游戏贪吃蛇是一代人的回忆,今天就让我们用python来制作出这个小游戏。(这里建议用Visual Studio Code)
图片素材这里为大家准备好了,大家可以直接截图了拿去用哈~(可能会因为某些问题且只是我第一次发博客,使图片边缘有黑框或字,请谅解)
话不多说,上代码:
import pygame
from pygame import locals
import random
# 初始化pygame,为使用硬件做准备
pygame.init()
background=pygame.image.load("bg.png")
food=pygame.image.load("apple.png")
right=pygame.image.load("right.png")
left=pygame.image.load("left.png")
up=pygame.image.load("up.png")
down=pygame.image.load("down.png")
body=pygame.image.load("body.png")#加载图片 (注:括号中的是这张图片的相对路径)
x,y = 240,120 #设置初始坐标
position = [(180,90),(180,120),(210,120),(x,y)]
apple_x = 360
apple_y = 300#食物初始坐标
screen = pygame.display.set_mode((660, 480))#创建一个窗口
F = pygame.time.Clock()
setheading = "right"
snake_head = right#设置朝向
while True:
for event in pygame.event.get():
if event.type == locals.QUIT:
exit()
if event.type == locals.KEYDOWN:
if event.key == locals.K_RIGHT and setheading != "left":#向右移动
setheading = "right"
snake_head = right#向右
if event.key == locals.K_LEFT and setheading != "right":#向左移动
setheading = "left"
snake_head = left#向左
if event.key == locals.K_UP and setheading != "down":#向上移动
setheading = "up"
snake_head = up#向上
if event.key == locals.K_DOWN and setheading != "up":#向下移动
setheading = "down"
snake_head = down#向下
if setheading == "right":
x += 30
elif setheading == "left":
x -= 30
elif setheading == "up":
y -= 30
else:
setheading == "down"
y += 30 #移动
position.append((x,y))
if x == apple_x and y == apple_y:
m = random.randint(1,22)
n = random.randint(1,16)
apple_x = m*30-30
apple_y = n*30-30 #苹果随机刷新
else:
position.pop(0)
if x < 0 or x > 660 or y < 0 or y > 480:
exit() #超出窗口时失败
screen.blit(background,(0,0)) #渲染背景
for i in range(len(position)-1):
screen.blit(body,position[i]) #渲染身体
screen.blit(snake_head,(x,y)) #渲染头部
screen.blit(food,(apple_x,apple_y)) #渲染苹果
F.tick(7.5)#帧率,可自己调整
pygame.display.update()#刷新窗口