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获取当前运行函数名称的方法实例代码
Apr 06 Python
Python入门之三角函数全解【收藏】
Nov 08 Python
Python实现的多进程和多线程功能示例
May 29 Python
Python + selenium + requests实现12306全自动抢票及验证码破解加自动点击功能
Nov 23 Python
python实现的多任务版udp聊天器功能案例
Nov 13 Python
Python random模块制作简易的四位数验证码
Feb 01 Python
tensorflow 查看梯度方式
Feb 04 Python
TensorFlow实现保存训练模型为pd文件并恢复
Feb 06 Python
将pymysql获取到的数据类型是tuple转化为pandas方式
May 15 Python
六种酷炫Python运行进度条效果的实现代码
Jul 17 Python
Python 如何测试文件是否存在
Jul 31 Python
Python机器学习应用之基于线性判别模型的分类篇详解
Jan 18 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中执行MYSQL事务解决数据写入不完整等情况
2014/01/07 PHP
从零开始学习jQuery (十一) 实战表单验证与自动完成提示插件
2011/02/23 Javascript
input标签内容改变的触发事件介绍
2014/06/18 Javascript
JavaScript取得WEB安全颜色列表的方法
2015/07/14 Javascript
基于JavaScript实现定时跳转到指定页面
2016/01/01 Javascript
快速掌握Node.js中setTimeout和setInterval的使用方法
2016/03/21 Javascript
jQuery基础知识点总结(DOM操作)
2016/06/01 Javascript
全面了解JavaScirpt 的垃圾(garbage collection)回收机制
2016/07/11 Javascript
js 文字超出长度用省略号代替,鼠标悬停并以悬浮框显示实例
2016/12/06 Javascript
js鼠标跟随运动效果
2017/03/11 Javascript
jquery中封装函数传递当前元素的方法示例
2017/05/05 jQuery
JavaScript编程设计模式之构造器模式实例分析
2017/10/25 Javascript
Node.js之readline模块的使用详解
2019/03/25 Javascript
在Vue项目中,防止页面被缩放和放大示例
2019/10/28 Javascript
浅谈vue的第一个commit分析
2020/06/08 Javascript
vue实现div可拖动位置也可改变盒子大小的原理
2020/09/16 Javascript
[00:43]2016完美“圣”典风云人物:单车宣传片
2016/12/02 DOTA
[48:24]完美世界DOTA2联赛PWL S3 Forest vs INK ICE 第一场 12.09
2020/12/12 DOTA
Python中的super用法详解
2015/05/28 Python
python实现中文分词FMM算法实例
2015/07/10 Python
Python简单爬虫导出CSV文件的实例讲解
2018/07/06 Python
python中字典按键或键值排序的实现代码
2019/08/27 Python
python GUI库图形界面开发之PyQt5布局控件QVBoxLayout详细使用方法与实例
2020/03/06 Python
python如何快速拼接字符串
2020/10/28 Python
CSS3.0实现霓虹灯按钮动画特效的示例代码
2021/01/12 HTML / CSS
美国知名生活购物网站:Goop
2017/11/03 全球购物
巴西服装和鞋子购物网站:Marisa
2018/10/25 全球购物
Hotels.com拉丁美洲:从豪华酒店到经济型酒店的预定优惠和折扣
2019/12/09 全球购物
什么是触发器(trigger)? 触发器有什么作用?
2013/09/18 面试题
医学检验专业个人求职信范文
2013/12/04 职场文书
女儿十岁生日答谢词
2014/01/27 职场文书
银行竞聘演讲稿范文
2014/04/23 职场文书
学习十八大的心得体会
2014/09/01 职场文书
《领导干部从政道德启示录》学习心得体会
2016/01/20 职场文书
导游词之崇武古城
2019/10/07 职场文书
python使用openpyxl库读写Excel表格的方法(增删改查操作)
2021/05/02 Python