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 sys.argv用法实例
May 28 Python
python妹子图简单爬虫实例
Jul 07 Python
Python和Perl绘制中国北京跑步地图的方法
Mar 03 Python
Python数据结构之翻转链表
Feb 25 Python
微信跳一跳python辅助软件思路及图像识别源码解析
Jan 04 Python
基于python实现的百度音乐下载器python pyqt改进版(附代码)
Aug 05 Python
Python导入数值型Excel数据并生成矩阵操作
Jun 09 Python
python对批量WAV音频进行等长分割的方法实现
Sep 25 Python
PyCharm安装PyQt5及其工具(Qt Designer、PyUIC、PyRcc)的步骤详解
Nov 02 Python
python+flask编写一个简单的登录接口
Nov 13 Python
Django中日期时间型字段进行年月日时分秒分组统计
Nov 27 Python
Python3+Flask安装使用教程详解
Feb 16 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实现小偷程序实例
2016/10/31 PHP
PHP开发APP端微信支付功能
2017/02/17 PHP
PHP实现单文件、多个单文件、多文件上传函数的封装示例
2019/09/02 PHP
jquery tablesorter.js 支持中文表格排序改进
2009/12/09 Javascript
jQuery中bind,live,delegate与one方法的用法及区别解析
2013/12/30 Javascript
javascript实现日期格式转换
2014/12/16 Javascript
判断数组的最佳方法(推荐)
2016/10/11 Javascript
Vue.js第四天学习笔记(组件)
2016/12/02 Javascript
基于bootstrap按钮式下拉菜单组件的搜索建议插件
2017/03/25 Javascript
jQuery响应滚动条事件功能示例
2017/10/14 jQuery
浅谈Vue.js组件(二)
2019/04/09 Javascript
Angular CLI 使用教程指南参考小结
2019/04/10 Javascript
Ant-design-vue Table组件customRow属性的使用说明
2020/10/28 Javascript
[03:19]2016国际邀请赛中国区预选赛第四日TOP10镜头集锦
2016/07/01 DOTA
[02:50]【扭转乾坤,只此一招】DOTA2永雾林渊版本开启新篇章
2020/12/22 DOTA
python实现的一只从百度开始不断搜索的小爬虫
2013/08/13 Python
跟老齐学Python之不要红头文件(2)
2014/09/28 Python
python映射列表实例分析
2015/01/26 Python
Python中isnumeric()方法的使用简介
2015/05/19 Python
Python中Iterator迭代器的使用杂谈
2016/06/20 Python
Python中的上下文管理器和with语句的使用
2018/04/17 Python
PyCharm设置SSH远程调试的方法
2018/07/17 Python
pygame实现俄罗斯方块游戏(基础篇3)
2019/10/29 Python
Appium+Python实现简单的自动化登录测试的实现
2021/01/26 Python
5个你不知道的HTML5的接口介绍
2013/08/07 HTML / CSS
美国嘻哈文化生活方式品牌:GLD
2018/04/15 全球购物
如何拷贝一整个Java对象,包括它的状态
2013/12/27 面试题
行政助理岗位职责
2013/11/10 职场文书
应届生的求职推荐信范文
2013/11/30 职场文书
个人简历自我评价
2014/01/06 职场文书
全运会口号
2014/06/20 职场文书
2014年音乐教师工作总结
2014/12/03 职场文书
西安兵马俑导游词
2015/02/02 职场文书
2016孝老爱亲模范事迹材料
2016/02/26 职场文书
python实现监听键盘
2021/04/26 Python
Python中使用tkFileDialog实现文件选择、保存和路径选择
2022/05/20 Python