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 查找文件夹下所有文件 实现代码
Jul 01 Python
Python线程详解
Jun 24 Python
Python 'takes exactly 1 argument (2 given)' Python error
Dec 13 Python
python中numpy包使用教程之数组和相关操作详解
Jul 30 Python
使用python进行广告点击率的预测的实现
Jul 04 Python
python中的RSA加密与解密实例解析
Nov 18 Python
python3 pathlib库Path类方法总结
Dec 26 Python
Python如何把多个PDF文件合并代码实例
Feb 13 Python
python实现根据给定坐标点生成多边形mask的例子
Feb 18 Python
Python处理PDF与CDF实例
Feb 26 Python
在python中使用pyspark读写Hive数据操作
Jun 06 Python
python实现图片素描效果
Sep 26 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
火车采集器 免费版使出收费版本功能实现原理
2009/09/17 PHP
php阻止页面后退的方法分享
2014/02/17 PHP
ThinkPHP 3.2 数据分页代码分享
2014/10/14 PHP
php基础教程
2015/08/26 PHP
微信支付开发订单查询实例
2016/07/12 PHP
PHP入门教程之使用Mysqli操作数据库的方法(连接,查询,事务回滚等)
2016/09/11 PHP
JavaScript中的object转换函数toString()与valueOf()介绍
2014/12/31 Javascript
jquery单选框radio绑定click事件实现方法
2015/01/14 Javascript
jQuery实现渐变弹出层和弹出菜单的方法
2015/02/20 Javascript
浅谈Javascript数组的使用
2015/07/29 Javascript
JavaScript jquery及AJAX小结
2016/01/24 Javascript
JavaScript结合HTML DOM实现联动菜单
2017/04/05 Javascript
深入理解node.js之path模块
2017/05/03 Javascript
Hexo已经看腻了,来手把手教你使用VuePress搭建个人博客
2018/04/26 Javascript
React 组件间的通信示例
2018/06/14 Javascript
es6函数之rest参数用法实例分析
2020/04/18 Javascript
js实现简单的贪吃蛇游戏
2020/04/23 Javascript
vue 解决无法对未定义的值,空值或基元值设置反应属性报错问题
2020/07/31 Javascript
浅谈Vue使用Cascader级联选择器数据回显中的坑
2020/10/31 Javascript
web.py中调用文件夹内模板的方法
2014/08/26 Python
python实现list元素按关键字相加减的方法示例
2017/06/09 Python
Python3.5局部变量与全局变量作用域实例分析
2019/04/30 Python
numpy中三维数组中加入元素后的位置详解
2019/11/28 Python
纯CSS改变webkit内核浏览器的滚动条样式
2014/04/17 HTML / CSS
基于ccs3的timeline时间线实现方法
2020/04/30 HTML / CSS
Tech21美国/加拿大:英国NO.1防摔保护壳品牌
2018/01/20 全球购物
香港网上花店:FlowerAdvisor香港
2019/05/30 全球购物
九年级化学教学反思
2014/01/28 职场文书
优秀中学生事迹材料
2014/01/31 职场文书
五分钟演讲稿
2014/04/30 职场文书
汽车专业求职信
2014/06/05 职场文书
机电专业毕业生求职信
2014/07/01 职场文书
2015年党支部公开承诺书
2015/01/22 职场文书
创先争优活动个人总结
2015/03/04 职场文书
浅谈Python协程asyncio
2021/06/20 Python
go开发alertmanger实现钉钉报警
2021/07/16 Golang