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中内置的itertools模块
Apr 29 Python
浅谈Python类里的__init__方法函数,Python类的构造函数
Dec 10 Python
利用Python实现网络测试的脚本分享
May 26 Python
python遍历一个目录,输出所有的文件名的实例
Apr 23 Python
python利用多种方式来统计词频(单词个数)
May 27 Python
python里dict变成list实例方法
Jun 26 Python
解决django中ModelForm多表单组合的问题
Jul 18 Python
python:按行读入,排序然后输出的方法
Jul 20 Python
python统计指定目录内文件的代码行数
Sep 19 Python
tensorflow使用L2 regularization正则化修正overfitting过拟合方式
May 22 Python
搭建pypi私有仓库实现过程详解
Nov 25 Python
python 中[0]*2与0*2的区别说明
May 10 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
多php服务器实现多session并发运行
2006/10/09 PHP
WordPress中给媒体文件添加分类和标签的PHP功能实现
2015/12/31 PHP
图文详解phpstorm配置Xdebug进行调试PHP教程
2016/06/13 PHP
PHP使用curl制作简易百度搜索
2016/11/03 PHP
ThinkPHP5.0 图片上传生成缩略图实例代码说明
2018/06/20 PHP
一个很简单的jquery+xml+ajax的无刷新树结构(无css,后台是c#)
2010/06/02 Javascript
juqery 学习之五 文档处理 插入
2011/02/11 Javascript
解决node-webkit 不支持html5播放mp4视频的方法
2015/03/11 Javascript
jQuery插件pagination实现分页特效
2015/04/12 Javascript
JavaScript实现把rgb颜色转换成16进制颜色的方法
2015/06/01 Javascript
jQuery自定义数值抽奖活动代码
2016/06/11 Javascript
JavaScript如何实现跨域请求
2016/08/05 Javascript
使用jQuery操作DOM的方法小结
2017/02/27 Javascript
帝国cms首页列表页实现点赞功能
2017/10/30 Javascript
在vue项目中引入vue-beauty操作方法
2019/02/11 Javascript
jQuery实现验证用户登录
2019/12/10 jQuery
浅谈Vue组件单元测试究竟测试什么
2020/02/05 Javascript
JavaScript冒泡算法原理与实现方法深入理解
2020/06/04 Javascript
在vue中封装的弹窗组件使用队列模式实现方法
2020/07/23 Javascript
[02:37]TI8勇士令状不朽珍藏II视频展示
2018/06/23 DOTA
python基于queue和threading实现多线程下载实例
2014/10/08 Python
Python中使用select模块实现非阻塞的IO
2015/02/03 Python
Python中将字典转换为XML以及相关的命名空间解析
2015/10/15 Python
tensorflow中next_batch的具体使用
2018/02/02 Python
python3实现网络爬虫之BeautifulSoup使用详解
2018/12/19 Python
python中的协程深入理解
2019/06/10 Python
python命令行工具Click快速掌握
2019/07/04 Python
用Pelican搭建一个极简静态博客系统过程解析
2019/08/22 Python
在tensorflow实现直接读取网络的参数(weight and bias)的值
2020/06/24 Python
Python 将代码转换为可执行文件脱离python环境运行(步骤详解)
2021/01/25 Python
澳大利亚礼品卡商店:Gift Card Store
2019/06/24 全球购物
将"引用"作为函数参数有哪些特点
2013/04/05 面试题
基本公共卫生服务健康教育工作方案
2014/05/22 职场文书
党委工作总结2015
2015/04/27 职场文书
2016年党员公开承诺书格式范文
2016/03/24 职场文书
vue/cli 配置动态代理无需重启服务的方法
2022/05/20 Vue.js