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控制台显示时钟的示例
Feb 24 Python
Python制作数据导入导出工具
Jul 31 Python
bpython 功能强大的Python shell
Feb 16 Python
Python用UUID库生成唯一ID的方法示例
Dec 15 Python
python中判断文件编码的chardet(实例讲解)
Dec 21 Python
Python实现文件信息进行合并实例代码
Jan 17 Python
Python Threading 线程/互斥锁/死锁/GIL锁
Jul 21 Python
python编写计算器功能
Oct 25 Python
Python通过Tesseract库实现文字识别
Mar 05 Python
python网络编程:socketserver的基本使用方法实例分析
Apr 09 Python
linux系统下pip升级报错的解决方法
Jan 31 Python
Python Pandas数据分析之iloc和loc的用法详解
Nov 11 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
怎样在UNIX系统下安装MySQL
2006/10/09 PHP
php获取用户IPv4或IPv6地址的代码
2012/11/15 PHP
php 参数过滤、数据过滤详解
2015/10/26 PHP
php 实现银联商务H5支付的示例代码
2019/10/12 PHP
修改Laravel自带的认证系统的User类的命名空间的步骤
2019/10/15 PHP
js里的prototype使用示例
2010/11/19 Javascript
jQuery EasyUI API 中文文档 - Tree树使用介绍
2011/11/19 Javascript
基于JQuery的抓取博客园首页RSS的代码
2011/12/01 Javascript
Javascript 颜色渐变效果的实现代码
2013/10/01 Javascript
让新消息在网页标题闪烁提示的jQuery代码
2013/11/04 Javascript
封装的jquery翻页滚动(示例代码)
2013/11/18 Javascript
JS记录用户登录次数实现代码
2014/01/15 Javascript
javascript跨域的4种方法和原理详解
2014/04/08 Javascript
jQuery实现弹出窗口中切换登录与注册表单
2015/06/05 Javascript
微信小程序封装http访问网络库实例代码
2017/05/24 Javascript
基于jQuery实现手风琴菜单、层级菜单、置顶菜单、无缝滚动效果
2017/07/20 jQuery
js中call()和apply()改变指针问题的讲解
2019/01/17 Javascript
了解JavaScript函数中的默认参数
2019/05/30 Javascript
vue props 一次传多个值实例
2020/07/22 Javascript
[51:32]Optic vs Serenity 2018国际邀请赛淘汰赛BO3 第一场 8.22
2018/08/23 DOTA
Python实现的检测web服务器健康状况的小程序
2014/09/17 Python
Windows下使Python2.x版本的解释器与3.x共存的方法
2015/10/25 Python
新建文件时Pycharm中自动设置头部模板信息的方法
2020/04/17 Python
Python自定义聚合函数merge与transform区别详解
2020/05/26 Python
matplotlib事件处理基础(事件绑定、事件属性)
2021/02/03 Python
CSS3之2D与3D变换的实现方法
2019/01/28 HTML / CSS
Marriott中国:万豪国际酒店查询预订
2016/09/02 全球购物
Hurley官方网站:扎根于海滩生活方式的全球青年文化品牌
2020/05/18 全球购物
教师实习自我鉴定
2013/12/18 职场文书
挂职思想汇报
2013/12/31 职场文书
追悼会子女答谢词
2014/01/28 职场文书
酒店中秋节活动方案
2014/01/31 职场文书
旅行社各个岗位职责
2014/03/15 职场文书
蟋蟀的住宅教学反思
2014/04/26 职场文书
电子商务求职信
2014/06/15 职场文书
在职证明书模板
2015/06/15 职场文书