网站开发招聘名称/爱站网seo综合查询工具
本文实例为大家分享了python简单贪吃蛇的具体代码,供大家参考,具体内容如下
import sys
import random
import pygame
from pygame.locals import *
# 目标方块的颜色 红色
redcolor = pygame.color(255, 0, 0)
# 游戏界面的背景颜色 纯黑色
blackcolor = pygame.color(0, 0, 0)
# 贪吃蛇的颜色 白色
whitecolor = pygame.color(255, 255, 255)
# 定义游戏结束的函数
def gameover():
pygame.quit()
sys.exit()
# 定义main函数
def main():
# 初始化pygame
pygame.init()
# 定义一个控制速度的函数
fpsclock = pygame.time.clock()
# 创建显示层
playsurface = pygame.display.set_mode((640,480)) # 界面的大小
pygame.display.set_caption('贪吃蛇')
# 初始化蛇的位置
snake_position=[100,100]
# 初始化蛇的长度
snake_body = [[100,100],[80,100],[60,100]]
# 初始化目标方块的位置
target_position = [300,300]
# 目标方块的状态
target_flag = 1
# 初始化一个方向
direction = 'right'
# 定义蛇的方向变量
changedirection = direction
while true:
# pygame的交互模块和事件队列
for event in pygame.event.get():
# 是否推出
if event.type == quit:
pygame.quit()
sys.exit()
# 判断键盘事件
elif event.type == keydown:
if event.key == k_right:
changedirection = 'right'
if event.key == k_left:
changedirection = 'left'
if event.key == k_up:
changedirection = 'up'
if event.key == k_down:
changedirection = 'down'
if event.key == k_space:
pygame.event.post(pygame.event.event(quit))
# 根据键盘反应确定方向
if changedirection == 'left' and not direction == 'right':
direction = changedirection
if changedirection == 'right' and not direction == 'left':
direction = changedirection
if changedirection == 'up' and not direction == 'down':
direction = changedirection
if changedirection == 'down' and not direction == 'up':
direction = changedirection
# 根据方向移动蛇头的坐标
if direction == 'right':
snake_position[0] += 20
if direction == 'left':
snake_position[0] -= 20
if direction == 'up':
snake_position[1] -= 20
if direction == 'down':
snake_position[1] += 20
# 蛇与自身的碰撞检测
for body in snake_body:
if snake_position[0] == body[0] and snake_position[1] == body[1]:
gameover()
# 蛇移动
snake_body.insert(0,list(snake_position))
if snake_position[0] == target_position[0] and snake_position[1] == target_position[1]:
target_flag = 0
else:
# 如果没吃到,蛇尾弹出栈
snake_body.pop()
# 如果吃掉目标方块,重新生成一个目标方块
if target_flag == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
# 20*20的像素为一个小矩形
target_position = [int(x*20),int(y*20)]
target_flag = 1
# 绘制显示层
playsurface.fill(blackcolor)
# 绘制蛇
for position in snake_body:
pygame.draw.rect(playsurface, redcolor, rect(position[0],position[1],20,20))
# 画目标方块
pygame.draw.rect(playsurface, whitecolor, rect(target_position[0], target_position[1], 20, 20))
pygame.display.flip()
# 判断死亡
if snake_position[0] > 620 or snake_position[1] < 0:
gameover()
elif snake_position[1] > 460 or snake_position[1] < 0:
gameover()
# 控制游戏的速度
fpsclock.tick(5)
if __name__ == '__main__':
main()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。
希望与广大网友互动??
点此进行留言吧!