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 相关文章推荐
python3访问sina首页中文的处理方法
Feb 24 Python
Python线程的两种编程方式
Apr 14 Python
Django的session中对于用户验证的支持
Jul 23 Python
详解Python的Django框架中的中间件
Jul 24 Python
详解Python中open()函数指定文件打开方式的用法
Jun 04 Python
Python基础教程之浅拷贝和深拷贝实例详解
Jul 15 Python
python实现k-means聚类算法
Feb 23 Python
Python获取系统所有进程PID及进程名称的方法示例
May 24 Python
Python Django框架模板渲染功能示例
Nov 08 Python
解决python gdal投影坐标系转换的问题
Jan 17 Python
Python如何重新加载模块
Jul 29 Python
Pygame Draw绘图函数的具体使用
Nov 17 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
星际争霸兵种名称对照表
2020/03/04 星际争霸
php过滤XSS攻击的函数
2013/11/12 PHP
PHP引用(&amp;)各种使用方法实例详解
2014/03/20 PHP
Thinkphp使用mongodb数据库实现多条件查询方法
2014/06/26 PHP
10个超级有用值得收藏的PHP代码片段
2015/01/22 PHP
jQuery 版本的文本输入框检查器Input Check
2009/07/09 Javascript
jQuery select控制插件
2009/08/17 Javascript
一个javascript图片阅览组件
2010/11/09 Javascript
异步安全加载javascript文件的方法
2015/07/21 Javascript
jQuery禁用键盘后退屏蔽F5刷新及禁用右键单击
2016/01/22 Javascript
JS原型、原型链深入理解
2016/02/27 Javascript
JS实现获取来自百度,Google,soso,sogou关键词的方法
2016/12/21 Javascript
基于JQuery及AJAX实现名人名言随机生成器
2017/02/10 Javascript
Node.js利用断言模块assert进行单元测试的方法
2017/09/28 Javascript
Angular4的输入属性与输出属性实例详解
2017/11/29 Javascript
详解webpack 打包文件体积过大解决方案(code splitting)
2018/04/10 Javascript
jQuery 实现批量提交表格多行数据的方法
2018/08/09 jQuery
js实现同一个页面,多个enter事件绑定的示例
2018/10/10 Javascript
[38:38]完美世界DOTA2联赛PWL S3 access vs Rebirth 第二场 12.17
2020/12/18 DOTA
Python+django实现文件下载
2016/01/17 Python
json跨域调用python的方法详解
2017/01/11 Python
用tensorflow构建线性回归模型的示例代码
2018/03/05 Python
在CMD命令行中运行python脚本的方法
2018/05/12 Python
网红编程语言Python将纳入高考你怎么看?
2018/06/07 Python
python tornado修改log输出方式
2019/11/18 Python
Keras—embedding嵌入层的用法详解
2020/06/10 Python
PyCharm配置anaconda环境的步骤详解
2020/07/31 Python
Sneaker Studio乌克兰:购买运动鞋
2018/03/26 全球购物
super关键字的用法
2012/04/10 面试题
给排水专业应届生求职信
2013/10/12 职场文书
老师自我鉴定范文
2013/12/25 职场文书
工程开工庆典邀请函
2014/02/01 职场文书
法律专业自荐信
2014/06/03 职场文书
国土资源局开展党的群众路线教育实践活动整改措施
2014/09/26 职场文书
孝女彩金观后感
2015/06/10 职场文书
MySQL脏读,幻读和不可重复读
2022/05/11 MySQL