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下利用OpenCV来旋转图像的教程
Apr 16 Python
Python3处理文件中每个词的方法
May 22 Python
python daemon守护进程实现
Aug 27 Python
Python单元测试实例详解
May 25 Python
python利用ffmpeg进行录制屏幕的方法
Jan 10 Python
Python进阶:生成器 懒人版本的迭代器详解
Jun 29 Python
python读取图片的方式,以及将图片以三维数组的形式输出方法
Jul 03 Python
python如何从文件读取数据及解析
Sep 19 Python
Python celery原理及运行流程解析
Jun 13 Python
matplotlib.pyplot.matshow 矩阵可视化实例
Jun 16 Python
python实现猜数游戏(保存游戏记录)
Jun 22 Python
Python IO文件管理的具体使用
Mar 20 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
模板引擎Smarty深入浅出介绍
2006/12/06 PHP
jQuery对象和DOM对象的相互转化实现代码
2010/03/02 Javascript
Eval and new funciton not the same thing
2012/12/27 Javascript
js实现点小图看大图效果的思路及示例代码
2013/10/28 Javascript
javascript设置连续两次点击按钮时间间隔的方法
2014/10/28 Javascript
JavaScript设计模式之外观模式介绍
2014/12/28 Javascript
Javascript removeChild()删除节点及删除子节点的方法
2015/12/27 Javascript
javascript实现tab响应式切换特效
2016/01/29 Javascript
[原创]Bootstrap 中下拉菜单修改成鼠标悬停直接显示
2016/04/14 Javascript
Jquery实现的简单轮播效果【附实例】
2016/04/19 Javascript
购物车前端开发(jQuery和bootstrap3)
2016/08/27 Javascript
js时间戳格式化成日期格式的多种方法介绍
2017/02/16 Javascript
JS 实现获取验证码 倒计时功能
2018/10/29 Javascript
trackingjs+websocket+百度人脸识别API实现人脸签到
2018/11/26 Javascript
ES6知识点整理之函数对象参数默认值及其解构应用示例
2019/04/17 Javascript
JavaScript中0、空字符串、'0'是true还是false的知识点分享
2019/09/16 Javascript
[52:06]FNATIC vs NIP 2019国际邀请赛小组赛 BO2 第二场 8.16
2019/08/19 DOTA
[05:24]TI9采访——教练
2019/08/24 DOTA
零基础写python爬虫之神器正则表达式
2014/11/06 Python
python-docx修改已存在的Word文档的表格的字体格式方法
2018/05/08 Python
python 2.7.13 安装配置方法图文教程
2018/09/18 Python
Python脚本完成post接口测试的实例
2018/12/17 Python
Python构建图像分类识别器的方法
2019/01/12 Python
Appium Python自动化测试之环境搭建的步骤
2019/01/23 Python
python中pow函数用法及功能说明
2020/12/04 Python
全球地下的服装和态度:Slam Jam
2018/02/04 全球购物
联想马亚西亚官方网站:Lenovo Malaysia
2018/09/19 全球购物
澳大利亚最受欢迎的超级商场每日优惠:Catch
2020/11/17 全球购物
北京捷通华声语音技术有限公司Java软件工程师笔试题
2012/04/10 面试题
办公室年终个人自我评价
2013/10/28 职场文书
企业办公室主任岗位职责
2014/02/19 职场文书
小学安全教育月活动总结
2014/07/07 职场文书
优秀护士事迹材料
2014/12/25 职场文书
圣诞晚会主持词
2015/07/01 职场文书
教务处干事工作总结
2015/08/14 职场文书
解决hive中导入text文件遇到的坑
2021/04/07 Python