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 相关文章推荐
使用Protocol Buffers的C语言拓展提速Python程序的示例
Apr 16 Python
python实现文本文件合并
Dec 29 Python
python实现图像识别功能
Jan 29 Python
python实现批量按比例缩放图片效果
Mar 30 Python
Python3.6通过自带的urllib通过get或post方法请求url的实例
May 10 Python
Python中的取模运算方法
Nov 10 Python
Python图像处理之直线和曲线的拟合与绘制【curve_fit()应用】
Dec 26 Python
Pyecharts绘制全球流向图的示例代码
Jan 08 Python
Python使用pyexecjs代码案例解析
Jul 13 Python
Python3爬虫关于代理池的维护详解
Jul 30 Python
python 使用xlsxwriter循环向excel中插入数据和图片的操作
Jan 01 Python
python将YUV420P文件转PNG图片格式的两种方法
Jan 22 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
33道php常见面试题及答案
2015/07/06 PHP
Ajax+PHP实现的分类列表框功能示例
2019/02/11 PHP
PHP内部实现打乱字符串顺序函数str_shuffle的方法
2019/02/14 PHP
比较简单的异步加载JS文件的代码
2009/07/18 Javascript
javascript 显示当前系统时间代码
2009/12/28 Javascript
用Juery网页选项卡实现代码
2011/06/13 Javascript
js几秒以后倒计时跳转示例
2013/12/26 Javascript
javascript实现类似超链接的效果
2014/12/26 Javascript
jQuery插件Elastislide实现响应式的焦点图无缝滚动切换特效
2015/04/12 Javascript
Web安全测试之XSS实例讲解
2016/08/15 Javascript
微信分享调用jssdk实例
2017/06/08 Javascript
浅谈JS 数字和字符串之间相互转化的纠纷
2017/10/20 Javascript
vue draggable resizable gorkys与v-chart使用与总结
2019/09/05 Javascript
基于JavaScript实现单例模式
2019/10/30 Javascript
使用JavaScript和MQTT开发物联网应用示例解析
2020/08/07 Javascript
[01:04:30]Fnatic vs Mineski 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
Python 文件操作技巧(File operation) 实例代码分析
2008/08/11 Python
python爬取网站数据保存使用的方法
2013/11/20 Python
Python实现partial改变方法默认参数
2014/08/18 Python
使用Python编写一个模仿CPU工作的程序
2015/04/16 Python
Python中输出ASCII大文字、艺术字、字符字小技巧
2015/04/28 Python
python在linux系统下获取系统内存使用情况的方法
2015/05/11 Python
python中关于for循环的碎碎念
2017/06/30 Python
读取本地json文件,解析json(实例讲解)
2017/12/06 Python
Python 实现两个列表里元素对应相乘的方法
2018/11/14 Python
详解pandas安装若干异常及解决方案总结
2019/01/10 Python
Python3获取拉勾网招聘信息的方法实例
2019/04/03 Python
opencv3/Python 稠密光流calcOpticalFlowFarneback详解
2019/12/11 Python
Xadmin+rules实现多选行权限方式(级联效果)
2020/04/07 Python
python如何操作mysql
2020/08/17 Python
JAVA招聘远程笔试题
2015/07/23 面试题
大学生个人简历自我评价
2013/11/16 职场文书
法律专业实习鉴定
2013/12/22 职场文书
小学科学教学计划
2015/01/21 职场文书
学校节水倡议书
2015/04/29 职场文书
Python破解极验滑动验证码详细步骤
2021/05/21 Python