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 相关文章推荐
Python3基础之函数用法
Aug 13 Python
python批量同步web服务器代码核心程序
Sep 01 Python
基于Python Shell获取hostname和fqdn释疑
Jan 25 Python
Django rest framework基本介绍与代码示例
Jan 26 Python
python简单实现操作Mysql数据库
Jan 29 Python
Python使用遗传算法解决最大流问题
Jan 29 Python
Python可视化mhd格式和raw格式的医学图像并保存的方法
Jan 24 Python
python带参数打包exe及调用方式
Dec 21 Python
tensorflow对图像进行拼接的例子
Feb 05 Python
python判断变量是否为int、字符串、列表、元组、字典的方法详解
Feb 13 Python
Python任务自动化工具tox使用教程
Mar 17 Python
python字符串的index和find的区别详解
Jun 20 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和网站发送到邮箱实例代码
2013/11/28 PHP
php中文验证码实现示例分享
2014/01/12 PHP
PHP读取汉字的点阵数据
2015/06/22 PHP
php获取远程文件的内容和大小
2015/11/03 PHP
拖拉表格的JS函数
2008/11/20 Javascript
通用javascript脚本函数库 方便开发
2009/10/13 Javascript
js的表单操作 简单计算器
2011/12/29 Javascript
超级好用的jQuery圆角插件 Corner速成
2014/08/31 Javascript
使用Jasmine和Karma对AngularJS页面程序进行测试
2016/03/05 Javascript
jQuery实现select下拉框获取当前选中文本、值、索引
2017/05/08 jQuery
Mongoose实现虚拟字段查询的方法详解
2017/08/15 Javascript
jquery手机触屏滑动拼音字母城市选择器的实例代码
2017/12/11 jQuery
JS遍历DOM文档树的方法实例详解
2018/04/03 Javascript
JS 中可以提升幸福度的小技巧(可以识别更多另类写法)
2018/07/28 Javascript
使用Angular 6创建各种动画效果的方法
2018/10/10 Javascript
微信小程序 wxParse插件显示视频问题
2019/09/27 Javascript
用JS实现一个简单的打砖块游戏
2019/12/11 Javascript
[01:08:43]DOTA2-DPC中国联赛定级赛 Phoenix vs DLG BO3第一场 1月9日
2021/03/11 DOTA
python解决js文件utf-8编码乱码问题(推荐)
2018/05/02 Python
对Python 3.2 迭代器的next函数实例讲解
2018/10/18 Python
django实现支付宝支付实例讲解
2019/10/17 Python
python实现的多任务版udp聊天器功能案例
2019/11/13 Python
python 6.7 编写printTable()函数表格打印(完整代码)
2020/03/25 Python
解决django xadmin主题不显示和只显示bootstrap2的问题
2020/03/30 Python
Python通过Schema实现数据验证方式
2020/11/12 Python
大学生求职简历的自我评价
2013/10/14 职场文书
秘书岗位职责
2013/11/18 职场文书
小学二年级评语
2014/04/21 职场文书
植树节标语
2014/06/27 职场文书
研修心得体会
2014/09/04 职场文书
基层党组织建设整改方案
2014/09/16 职场文书
停电调休通知
2015/04/16 职场文书
2015年社区宣传工作总结
2015/05/20 职场文书
课题研究阶段性总结
2015/08/13 职场文书
Python使用MapReduce进行简单的销售统计
2022/04/22 Python
前端框架ECharts dataset对数据可视化的高级管理
2022/12/24 Javascript