当前位置: 首页 > article >正文

turtle实现贪吃蛇小游戏

今天分享一篇利用python的turtle库实现贪吃蛇小游戏,适合初学者的朋友学习

技术点:

  • 函数应用
  • time库应用
  • random库应用
  • turtle库应用

无身体碰撞的版本,完整代码先附上

import turtle
import random
import time

delay = 0.1     #延迟时间
score = 0       #当前分数
high_score = 0  #最高分数

#创建游戏窗口
wn = turtle.Screen()
wn.title('贪吃蛇')
wn.bgcolor('black')
wn.setup(width=600, height=600)
wn.tracer(0)    #关闭屏幕自动刷新

#创建snake head
head = turtle.Turtle()
head.shape('square')    #方块
head.color('white')     #颜色
head.penup()
head.goto(0,0)          #出现的位置
head.direction = 'Stop' #移动方向

#创建食物
food = turtle.Turtle()
colors = random.choice(['red','green','blue'])  #随机产生食物颜色
shapes = random.choice(['square','circle'])     #随机产生食物形状
food.color(colors)
food.shape(shapes)
food.speed(0)           #食物出现速度
food.penup()
food.goto(0, 100)       #食物出现的位置

#创建积分榜
pen = turtle.Turtle()
pen.speed(0)
pen.shape('square')
pen.color('white')
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write('Score: 0 High Score: 0', align='center', font=('Courier', 24, 'normal'))

#定义方向键
def goup():
    # 方向朝下禁止向上移动
    if head.direction != "down":
        head.direction = "up"

def godown():
    # 方向朝上禁止向下移动
    if head.direction != "up":
        head.direction = "down"

def goleft():
    # 方向朝右禁止向左移动
    if head.direction != "right":
        head.direction = "left"

def goright():
    # 方向朝左禁止向右移动
    if head.direction != "left":
        head.direction = "right"

#定义移动函数
def move():
    if head.direction == 'up':
        y = head.ycor()     #当前乌龟y轴坐标
        head.sety(y+20)
    if head.direction == 'down':
        y = head.ycor()     #当前乌龟y轴坐标
        head.sety(y-20)
    if head.direction == 'left':
        x = head.xcor()     #当前乌龟x轴坐标
        head.setx(x-20)
    if head.direction == 'right':
        x = head.xcor()     #当前乌龟x轴坐标
        head.setx(x+20)

#启动事件监听,窗口能够响应键盘事件
wn.listen()
wn.onkeypress(goup, 'w')
wn.onkeypress(godown, 's')
wn.onkeypress(goleft, 'a')
wn.onkeypress(goright, 'd')

segments = []               #碎片

#循环,启动游戏
while True:
    wn.update()     #手动刷新

    #撞墙检测,重新开始
    if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
        time.sleep(1)
        head.goto(0,0)
        head.direction = 'Stop'
        colors = random.choice(['red','green','blue'])  #随机产生食物颜色
        shapes = random.choice(['square','circle'])     #随机产生食物形状
        for segment in segments:
            segment.goto(1000,1000)                     #清除碎片
        segments.clear()                                #清除碎片列表
        score = 0
        delay = 0.1
        pen.clear()
        pen.write('Score: 0 High Score: 0', align='center', font=('Courier', 24, 'normal'))
        food.shape(shapes)
        food.color(colors)

    #吃食物
    if head.distance(food) < 20:
        x = random.randint(-270, 270)
        y = random.randint(-270, 270)
        colors = random.choice(['red','green','blue'])  #随机产生食物颜色
        shapes = random.choice(['square','circle'])     #随机产生食物形状
        food.shape(shapes)
        food.color(colors)
        food.goto(x,y)

        # 添加新的碎片,蛇长大
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape('square')
        new_segment.color('orange')
        new_segment.penup()
        segments.append(new_segment)        #放入到列表中
        delay -= 0.001
        score += 10
        if score > high_score:
            high_score = score
        pen.clear()
        pen.write('Score: {} High Score: {}'.format(score, high_score), align='center', font=('Courier', 24, 'normal'))
        
    for index in range(len(segments)-1, 0, -1):
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x,y)
    if len(segments) > 0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x,y)
    
    move()          #启动移动函数
    time.sleep(delay)       # 调用time模块中的sleep函数,使程序暂停执行0.1秒

wn.mainloop()   #启动事件循环

http://www.kler.cn/news/315588.html

相关文章:

  • 【鼠标滚轮专用芯片】KTH57913D 霍尔位置传感器
  • 面试题(二)
  • 大学生请码住!分享10款AI论文工具搞定论文开题到答辩全过程!
  • 动态路由---OSPF协议基础
  • 【时时三省】(C语言基础)指针笔试题3
  • 配置实验用的 Rocky Linux
  • World of Warcraft [CLASSIC] International translation bug
  • 常见单片机
  • Java中stream流及Collectors的常见用法详细汇总!!!
  • 掌握回流与重绘面试回答:优化网页加载与响应速度
  • 前后端分离的情况下,后端接口有必要加CSP策略吗?
  • 数据集-目标检测系列-自行车检测数据集 bike>> DataBall
  • Linux系统中文件I/O
  • yolov5实战拓展
  • 使用git命令
  • 基于SpringBoot+Vue的时尚美妆电商网站系统
  • Web APIs 1:基础介绍+DOM+定时器
  • 饭局礼仪:以下这7种动作,特容易被视为没教养,不要犯
  • Vue学习记录之三(ref全家桶)
  • 今日leetCode 1. 两数之和
  • (转载)智能指针shared_ptr从C++11到C++20
  • SpringSecurity6.x整合手机短信登录授权
  • 2024 硬盘格式恢复软件大揭秘
  • 《论分布式存储系统架构设计》写作框架,软考高级系统架构设计师
  • 无限边界:现代整合安全如何保护云
  • 怀庄之醉是勾兑酒吗?
  • YOLOv10改进,YOLOv10替换主干网络为PP-HGNetV2(百度飞桨视觉团队自研,独家手把手教程,助力涨点)
  • re题(38)BUUCTF-[FlareOn6]Overlong
  • 在vue中嵌入vitepress,基于markdown文件生成静态网页从而嵌入社团周报系统的一些想法和思路
  • 【GMNER】Grounded Multimodal Named Entity Recognition on Social Media