Python turtle实现贪吃蛇游戏


Posted in Python onJune 18, 2021

本文实例为大家分享了Python turtle实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下

# Simple Snake Game in Python 3 for Beginners
 
import turtle
import time
import random
 
delay = 0.1
 
# Score
score = 0
high_score = 0
 
# Set up the screen
wn = turtle.Screen()
wn.title("Snake Game by @TokyoEdTech")
wn.bgcolor("green")
wn.setup(width=600, height=600)
wn.tracer(0)  # Turns off the screen updates
 
# Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"
 
# Snake food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
 
segments = []
 
# Pen
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"))
 
# Functions
 
 
def go_up():
    if head.direction != "down":
        head.direction = "up"
 
 
def go_down():
    if head.direction != "up":
        head.direction = "down"
 
 
def go_left():
    if head.direction != "right":
        head.direction = "left"
 
 
def go_right():
    if head.direction != "left":
        head.direction = "right"
 
 
def move():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 20)
 
    if head.direction == "down":
        y = head.ycor()
        head.sety(y - 20)
 
    if head.direction == "left":
        x = head.xcor()
        head.setx(x - 20)
 
    if head.direction == "right":
        x = head.xcor()
        head.setx(x + 20)
 
 
# Keyboard bindings
wn.listen()
wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_left, "Left")
wn.onkeypress(go_right, "Right")
 
# Main game loop
while True:
    wn.update()
 
    # Check for a collision with the border
    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"
 
        # Hide the segments
        for segment in segments:
            segment.goto(1000, 1000)
 
        # Clear the segments list
        segments.clear()
 
        # Reset the score
        score = 0
 
        # Reset the delay
        delay = 0.1
 
        pen.clear()
        pen.write("Score: {}  High Score: {}".format(score, high_score),
                  align="center", font=("Courier", 24, "normal"))
 
    # Check for a collision with the food
    if head.distance(food) < 20:
        # Move the food to a random spot
        x = random.randint(-290, 290)
        y = random.randint(-290, 290)
        food.goto(x, y)
 
        # Add a segment
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("grey")
        new_segment.penup()
        segments.append(new_segment)
 
        # Shorten the delay
        delay -= 0.001
 
        # Increase the score
        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"))
 
    # Move the end segments first in reverse order
    for index in range(len(segments)-1, 0, -1):
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x, y)
 
    # Move segment 0 to where the head is
    if len(segments) > 0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x, y)
 
    move()
 
    # Check for head collision with the body segments
    for segment in segments:
        if segment.distance(head) < 20:
            time.sleep(1)
            head.goto(0, 0)
            head.direction = "stop"
 
            # Hide the segments
            for segment in segments:
                segment.goto(1000, 1000)
 
            # Clear the segments list
            segments.clear()
 
            # Reset the score
            score = 0
 
            # Reset the delay
            delay = 0.1
 
            # Update the score display
            pen.clear()
            pen.write("Score: {}  High Score: {}".format(
                score, high_score), align="center", font=("Courier", 24, "normal"))
 
    time.sleep(delay)
 
wn.mainloop()

Python turtle实现贪吃蛇游戏

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python读取注册表中值的方法
Apr 08 Python
Python操作列表的常用方法分享
Feb 13 Python
Python算法应用实战之栈详解
Feb 04 Python
pyqt5自定义信号实例解析
Jan 31 Python
Python基于matplotlib画箱体图检验异常值操作示例【附xls数据文件下载】
Jan 07 Python
关于python之字典的嵌套,递归调用方法
Jan 21 Python
Python Flask框架模板操作实例分析
May 03 Python
创建Django项目图文实例详解
Jun 06 Python
浅谈keras中的后端backend及其相关函数(K.prod,K.cast)
Jun 29 Python
去除python中的字符串空格的简单方法
Dec 22 Python
Selenium Webdriver元素定位的八种常用方式(小结)
Jan 13 Python
一行Python命令实现批量加水印
Apr 07 Python
python中%格式表达式实例用法
Jun 18 #Python
如何用python清洗文件中的数据
Jun 18 #Python
Python中glob库实现文件名的匹配
python中的装饰器该如何使用
Jun 18 #Python
Python预测分词的实现
学会Python数据可视化必须尝试这7个库
python tqdm用法及实例详解
Jun 16 #Python
You might like
Search File Contents PHP 搜索目录文本内容的代码
2010/02/21 PHP
php微信公众平台开发之微信群发信息
2016/09/13 PHP
IE与Firefox在JavaScript上的7个不同写法小结
2009/09/14 Javascript
使用JavaScript检测Firefox浏览器是否启用了Firebug的代码
2010/12/28 Javascript
js图片延迟技术一般的思路与示例
2014/03/20 Javascript
ExtJS4给Combobox设置列表中的默认值示例
2014/05/02 Javascript
js实现使用鼠标拖拽切换图片的方法
2015/05/04 Javascript
jQuery实现下拉框选择图片功能实例
2015/08/08 Javascript
JS模仿编辑器实时改变文本框宽度和高度大小的方法
2015/08/17 Javascript
js带点自动图片轮播幻灯片特效代码分享
2015/09/07 Javascript
详解Angular.js数据绑定时自动转义html标签及内容
2017/03/30 Javascript
JS 调试中常见的报错问题解决方法
2017/05/20 Javascript
JS如何设置元素样式的方法示例
2017/08/28 Javascript
vue cli构建的项目中请求代理与项目打包问题
2018/02/26 Javascript
说说如何在Vue.js中实现数字输入组件的方法
2019/01/08 Javascript
nodejs语言实现验证码生成功能的示例代码
2019/10/13 NodeJs
javascript解析json格式的数据方法详解
2020/08/07 Javascript
JavaScript基于SVG的图片切换效果实例代码
2020/12/15 Javascript
[40:50]2014 DOTA2国际邀请赛中国区预选赛 5 23 CIS VS LGD第四场
2014/05/24 DOTA
[02:33]DOTA2亚洲邀请赛趣味视频之吐真话筒
2018/03/31 DOTA
python基础教程之元组操作使用详解
2014/03/25 Python
使用Python编写vim插件的简单示例
2015/04/17 Python
Python学习思维导图(必看篇)
2017/06/26 Python
用python求一个数组的和与平均值的实现方法
2019/06/29 Python
python3 requests库实现多图片爬取教程
2019/12/18 Python
tensorflow如何继续训练之前保存的模型实例
2020/01/21 Python
Python通过队列来实现进程间通信的示例
2020/10/14 Python
python-地图可视化组件folium的操作
2020/12/14 Python
Giuseppe Zanotti美国官方网站:将鞋履视为高级时装般精心制作
2018/02/06 全球购物
信息管理与信息系统专业求职信
2014/06/21 职场文书
2014年国庆晚会主持词
2014/09/19 职场文书
党员个人剖析材料
2014/09/30 职场文书
工作失职检讨书
2015/01/26 职场文书
2019交通安全宣传标语集锦!
2019/06/28 职场文书
Golang 入门 之url 包
2022/05/04 Golang
JS函数式编程实现XDM一
2022/06/16 Javascript