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.3教程之模拟百度登陆代码分享
Jan 16 Python
python模拟登陆阿里妈妈生成商品推广链接
Apr 03 Python
通过C++学习Python
Jan 20 Python
python在windows命令行下输出彩色文字的方法
Mar 19 Python
Python 字符串大小写转换的简单实例
Jan 21 Python
浅谈Django的缓存机制
Aug 23 Python
python得到单词模式的示例
Oct 15 Python
在python中pandas的series合并方法
Nov 12 Python
python单例设计模式实现解析
Jan 07 Python
matlab中imadjust函数的作用及应用举例
Feb 27 Python
keras处理欠拟合和过拟合的实例讲解
May 25 Python
Python3自带工具2to3.py 转换 Python2.x 代码到Python3的操作
Mar 03 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实现采集程序原理和简单示例代码
2007/03/18 PHP
require(),include(),require_once()和include_once()区别
2008/03/27 PHP
PHP 5.3新特性命名空间规则解析及高级功能
2010/03/11 PHP
PHP中的float类型使用说明
2010/07/27 PHP
PHP面向对象概念
2011/11/06 PHP
php中存储用户ID和密码到mysql数据库的方法
2013/02/06 PHP
PHP chunk_split()函数讲解
2019/02/12 PHP
jQueryPad 实用的jQuery测试工具(支持IE,chrome,FF)
2010/05/22 Javascript
ExtJS判断IE浏览器类型的方法
2014/02/10 Javascript
node.js中的events.emitter.removeAllListeners方法使用说明
2014/12/10 Javascript
常用的JavaScript模板引擎介绍
2015/02/28 Javascript
javascript 数组的定义和数组的长度
2016/06/07 Javascript
AngularJS动态加载模块和依赖的方法分析
2016/11/08 Javascript
Koa2微信公众号开发之本地开发调试环境搭建
2018/05/16 Javascript
vue-router+nginx 非根路径配置方法
2018/06/30 Javascript
Layui 导航默认展开和菜单栏选中高亮设置的方法
2019/09/04 Javascript
nodeJS与MySQL实现分页数据以及倒序数据
2020/06/05 NodeJs
实例解析Python中的__new__特殊方法
2016/06/02 Python
python方向键控制上下左右代码
2018/01/20 Python
python reverse反转部分数组的实例
2018/12/13 Python
PyQt5显示GIF图片的方法
2019/06/17 Python
基于Python函数和变量名解析
2019/07/19 Python
详解程序意外中断自动重启shell脚本(以Python为例)
2019/07/26 Python
Python 类,property属性(简化属性的操作),@property,property()用法示例
2019/10/12 Python
python实现的批量分析xml标签中各个类别个数功能示例
2019/12/30 Python
利用OpenCV中对图像数据进行64F和8U转换的方式
2020/06/03 Python
HTMl5的存储方式sessionStorage和localStorage详解
2014/03/18 HTML / CSS
英国家喻户晓的折扣商场:TK Maxx
2017/05/26 全球购物
实习单位接收函
2014/01/11 职场文书
车间安全生产标语
2014/06/06 职场文书
党的群众路线教育实践活动个人整改方案
2014/09/21 职场文书
自查自纠工作总结
2014/10/15 职场文书
毕业论文致谢范文
2015/05/14 职场文书
2015年音乐教研组工作总结
2015/07/22 职场文书
回门宴新娘答谢词
2015/09/29 职场文书
十大好看的穿越动漫排名:《瑞克和莫蒂》第一,国漫《有药》在榜
2022/03/18 日漫