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读取ini文件、操作mysql、发送邮件实例
Jan 01 Python
基于python的Tkinter实现一个简易计算器
Dec 31 Python
opencv python 2D直方图的示例代码
Jul 20 Python
对python捕获ctrl+c手工中断程序的两种方法详解
Dec 26 Python
解决Pycharm界面的子窗口不见了的问题
Jan 17 Python
Python操作MySQL数据库的两种方式实例分析【pymysql和pandas】
Mar 18 Python
Python中遍历列表的方法总结
Jun 27 Python
ORM Django 终端打印 SQL 语句实现解析
Aug 09 Python
keras 实现轻量级网络ShuffleNet教程
Jun 19 Python
keras CNN卷积核可视化,热度图教程
Jun 22 Python
Python中zipfile压缩包模块的使用
May 14 Python
python中validators库的使用方法详解
Sep 23 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
用文本文件制作留言板提示(下)
2006/10/09 PHP
php中读写文件与读写数据库的效率比较分享
2013/10/19 PHP
php使用cookie显示用户上次访问网站日期的方法
2015/01/26 PHP
form表单传递数组数据、php脚本接收的实例
2017/02/09 PHP
PHP For循环字母A-Z当超过26个字母时输出AA,AB,AC
2020/02/16 PHP
分享Javascript中最常用的55个经典小技巧
2013/11/29 Javascript
JavaScript定义类的几种方式总结
2014/01/06 Javascript
Nodejs实现的一个简单udp广播服务器、客户端
2014/09/25 NodeJs
网页中表单按回车就自动提交的问题的解决方案
2014/11/03 Javascript
nodejs爬虫抓取数据乱码问题总结
2015/07/03 NodeJs
jQuery实现带玻璃流光质感的手风琴特效
2015/11/20 Javascript
JavaScript优化专题之Loading and Execution加载和运行
2016/01/20 Javascript
JavaScript 定时器 SetTimeout之定时刷新窗口和关闭窗口(代码超简单)
2016/02/26 Javascript
javascript验证香港身份证的格式或真实性
2017/02/07 Javascript
jQuery插件FusionWidgets实现的Bulb图效果示例【附demo源码下载】
2017/03/23 jQuery
在vue中配置不同的代理同时访问不同的后台操作
2020/09/11 Javascript
[06:24]DOTA2亚洲邀请赛小组赛第三日 TOP10精彩集锦
2015/02/01 DOTA
Django 前后台的数据传递的方法
2017/08/08 Python
Windows下安装Django框架的方法简明教程
2018/03/28 Python
解决Pycharm运行时找不到文件的问题
2018/10/29 Python
简单了解django缓存方式及配置
2019/07/19 Python
解析python的局部变量和全局变量
2019/08/15 Python
Python configparser模块操作代码实例
2020/06/08 Python
css3 中实现炫酷的loading效果
2019/04/26 HTML / CSS
HTML5页面音视频在微信和app下自动播放的实现方法
2016/10/20 HTML / CSS
HomeAway的巴西品牌:Alugue Temporada
2018/04/10 全球购物
美国嘻哈文化生活方式品牌:GLD
2018/04/15 全球购物
String和StringBuffer的区别
2015/08/13 面试题
上海奥佳笔试题面试题
2016/11/16 面试题
成人大专生实习期的自我评价
2013/10/02 职场文书
水电工岗位职责
2014/02/12 职场文书
优质护理服务演讲稿
2014/05/07 职场文书
工会换届选举方案
2014/05/21 职场文书
正科级干部考察材料
2014/05/29 职场文书
员工2014年度工作总结
2014/12/09 职场文书
2015年社区工会工作总结
2015/05/26 职场文书