网站首页 > 技术文章 正文
前言
哈喽,大家好呀~欢迎大家阅读小编的文章!
又到了每日游戏更新系列,看到这么如下.gif是不是让你想起来了童年吖~
贪吃蛇?的人气可谓是经久不衰,有过了许多不同的版本,但大体游戏规则都是控制蛇的向,
寻找吃的东西,每吃一口就能得到一定的积分,而且蛇的身子会越吃越长,身子越长玩的难度
就越大,不能碰墙,不能咬到自己的身体,更不能咬自己的尾巴,还要注意其他的蛇!? ?
?
哪个版本的贪吃蛇是你的童年?
是这个
嘿嘿?~~~
?
好了,放图片路?♀
正文:
就是这个大工程今天带大家做一款 Python 版本的贪吃蛇?游戏!
直接放代码
import pygame as pg
from random import randint
import sys
from pygame.locals import *
FPS = 6 # 画面帧数,代表蛇的移动速率
window_width = 600
window_height = 500
cellsize = 20
cell_width = int(window_width / cellsize)
cell_height = int(window_height / cellsize)
BGcolor = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
apple_color = (255, 0, 0)
snake_color = (0, 150, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
DARKGRAY = (40, 40, 40)
UP = "up"
DOWN = "down"
LEFT = "left"
RIGHT = "right"
HEAD = 0
def main(): # 有函数
global FPSclock, window, BASICFONT
pg.init()
FPSclock = pg.time.Clock()
window = pg.display.set_mode((window_width, window_height))
BASICFONT = pg.font.Font("freesansbold.ttf", 18)
pg.display.set_caption("贪吃蛇")
showStartScreen()
while True:
runGame()
showGameOverScreen()
def runGame(): # 运行游戏函数
startx = randint(5, cell_width - 6)
starty = randint(5, cell_height - 6)
snakeCoords = [{"x": startx, "y": starty}, {"x": startx - 1, "y": starty}, {"x": startx - 2, "y": starty}]
direction = RIGHT
apple = getRandomLocation()
while True:
for event in pg.event.get():
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if event.key == K_LEFT and direction != RIGHT:
direction = LEFT
elif event.key == K_RIGHT and direction != LEFT:
direction = RIGHT
elif event.key == K_UP and direction != DOWN:
direction = UP
elif event.key == K_DOWN and direction != UP:
direction = DOWN
elif event.key == K_ESCAPE:
terminate()
if snakeCoords[HEAD]["x"] == -1 or snakeCoords[HEAD]["x"] == cell_width or snakeCoords[HEAD]["y"] == -1 or \
snakeCoords[HEAD]["y"] == cell_height:
return
for snakeBody in snakeCoords[1:]:
if snakeBody["x"] == snakeCoords[HEAD]["x"] and snakeBody["y"] == snakeCoords[HEAD]["y"]:
return
if snakeCoords[HEAD]["x"] == apple["x"] and snakeCoords[HEAD]["y"] == apple["y"]:
apple = getRandomLocation()
else:
del snakeCoords[-1]
if direction == UP:
newHead = {"x": snakeCoords[HEAD]["x"], "y": snakeCoords[HEAD]["y"] - 1}
elif direction == DOWN:
newHead = {"x": snakeCoords[HEAD]["x"], "y": snakeCoords[HEAD]["y"] + 1}
elif direction == LEFT:
newHead = {"x": snakeCoords[HEAD]["x"] - 1, "y": snakeCoords[HEAD]["y"]}
elif direction == RIGHT:
newHead = {"x": snakeCoords[HEAD]["x"] + 1, "y": snakeCoords[HEAD]["y"]}
snakeCoords.insert(0, newHead)
window.fill(BGcolor)
drawGrid()
drawSnake(snakeCoords)
drawApple(apple)
drawScore(len(snakeCoords) - 3)
pg.display.update()
FPSclock.tick(FPS)
def drawPressKeyMsg(): # 游戏开始提示信息
pressKeySurf = BASICFONT.render("press a key to play", True, BLUE)
pressKeyRect = pressKeySurf.get_rect()
pressKeyRect.topleft = (window_width - 200, window_height - 30)
window.blit(pressKeySurf, pressKeyRect)
def checkForKeyPress(): # 检查是否触发按键
if len(pg.event.get(QUIT)) > 0:
terminate()
keyUpEvents = pg.event.get(KEYUP)
if len(keyUpEvents) == 0:
return None
if keyUpEvents[0].key == K_ESCAPE:
terminate()
return keyUpEvents[0].key
def showStartScreen(): # 开始画面
window.fill(BGcolor)
titleFont = pg.font.Font("freesansbold.ttf", 100)
titleSurf = titleFont.render("snake!", True, RED)
titleRect = titleSurf.get_rect()
titleRect.center = (window_width / 2, window_height / 2)
window.blit(titleSurf, titleRect)
drawPressKeyMsg()
pg.display.update()
while True:
if checkForKeyPress():
pg.event.get()
return
def terminate(): # 退出
pg.quit()
sys.exit()
def getRandomLocation(): # 出现位置
return {"x": randint(0, cell_width - 1), "y": randint(0, cell_height - 1)}
def showGameOverScreen(): # 游戏结束
gameOverFont = pg.font.Font("freesansbold.tff", 150)
gameSurf = gameOverFont.render("Game", True, WHITE)
overSurf = gameOverFont.render("over", True, WHITE)
gameRect = gameSurf.get_rect()
overRect = overSurf.get_rect()
gameRect.midtop = (window_width / 2, 10)
overRect.midtop = (window_width / 2, gameRect.height10 + 25)
window.blit(gameSurf, gameRect)
window.blit(overSurf, overRect)
drawPressKeyMsg()
pg.display.update()
pg.time.wait(500)
checkForKeyPress()
while True:
if checkForKeyPress():
pg.event.get()
return
def drawScore(score): # 显示分数
scoreSurf = BASICFONT.render("Score:%s" % (score), True, WHITE)
scoreRect = scoreSurf.get_rect()
scoreRect.topleft = (window_width - 120, 10)
window.blit(scoreSurf, scoreRect)
def drawSnake(snakeCoords): # 画蛇
for coord in snakeCoords:
x = coord["x"] * cellsize
y = coord["y"] * cellsize
snakeSegmentRect = pg.Rect(x, y, cellsize, cellsize)
pg.draw.rect(window, snake_color, snakeSegmentRect)
snakeInnerSegmentRect = pg.Rect(x + 4, y + 4, cellsize - 8, cellsize - 8)
pg.draw.rect(window, GREEN, snakeInnerSegmentRect)
def drawApple(coord):
x = coord["x"] * cellsize
y = coord["y"] * cellsize
appleRect = pg.Rect(x, y, cellsize, cellsize)
pg.draw.rect(window, apple_color, appleRect)
def drawGrid(): # 画方格
for x in range(0, window_width, cellsize):
pg.draw.line(window, DARKGRAY, (x, 0), (x, window_height))
for y in range(0, window_height, cellsize):
pg.draw.line(window, DARKGRAY, (0, y), (window_width, y))
if __name__ == "__main__":
main()
复制代码
效果展示:
结尾:
不管玩得多么纯熟,技术多么高超,但最终都会是听到贪食蛇的一声惨叫。记住:小蛇韬光养晦,中蛇欺软怕硬,大蛇明哲保身哟~
最后文章就写到这里结束啦~大家喜欢的记得点点赞
猜你喜欢
- 2024-09-09 序列化 Python 对象(序列化对象需要实现的接口)
- 2024-09-09 一篇文章读懂系列-2.二叉树及常见面试题
- 2024-09-09 Meta 如何将缓存一致性提高到 99.99999999
- 2024-09-09 自学Python笔记2(python0基础自学书)
- 2024-09-09 找到两个链表的第一个公共节点(找出两个链表的第一个公共节点)
- 2024-09-09 详解SkipList跳跃链表(跳表遍历)
- 2024-09-09 Python画豪华版圣诞树,带漂亮彩灯与文字背景
- 2024-09-09 零基础Python完全自学教程23:函数的返回值、作用域和匿名函数
- 2024-09-09 redis的内存满了之后,redis如何回收内存
- 2024-09-09 高阶Python|返回类型提示技巧 (1)
- 02-21走进git时代, 你该怎么玩?_gits
- 02-21GitHub是什么?它可不仅仅是云中的Git版本控制器
- 02-21Git常用操作总结_git基本用法
- 02-21为什么互联网巨头使用Git而放弃SVN?(含核心命令与原理)
- 02-21Git 高级用法,喜欢就拿去用_git基本用法
- 02-21Git常用命令和Git团队使用规范指南
- 02-21总结几个常用的Git命令的使用方法
- 02-21Git工作原理和常用指令_git原理详解
- 最近发表
- 标签列表
-
- cmd/c (57)
- c++中::是什么意思 (57)
- sqlset (59)
- ps可以打开pdf格式吗 (58)
- phprequire_once (61)
- localstorage.removeitem (74)
- routermode (59)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- log.warn (60)
- cannotinstantiatethetype (62)
- js数组插入 (83)
- resttemplateokhttp (59)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- reader.onload (61)
- outofmemoryerror是什么意思 (64)
- flask文件上传 (63)
- eacces (67)
- 查看mysql是否启动 (70)
- java是值传递还是引用传递 (58)
- 无效的列索引 (74)