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爬虫之打包生成exe文件
Nov 06 Python
Python 多线程实例详解
Mar 25 Python
Python设计模式之中介模式简单示例
Jan 09 Python
使用python 爬虫抓站的一些技巧总结
Jan 10 Python
python 获取文件下所有文件或目录os.walk()的实例
Apr 23 Python
使用Pyinstaller转换.py文件为.exe可执行程序过程详解
Aug 06 Python
python由已知数组快速生成新数组的方法
Apr 08 Python
Java ExcutorService优雅关闭方式解析
May 30 Python
使用Keras加载含有自定义层或函数的模型操作
Jun 10 Python
Python在线和离线安装第三方库的方法
Oct 31 Python
Python实现Excel自动分组合并单元格
Feb 22 Python
pytorch 如何使用float64训练
May 24 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
建立动态的WML站点(一)
2006/10/09 PHP
PHP中抽象类、接口的区别与选择分析
2016/03/29 PHP
smarty自定义函数用法示例
2016/05/20 PHP
PHP文件及文件夹操作之创建、删除、移动、复制
2016/07/13 PHP
PHP抽象类和接口用法实例详解
2019/07/20 PHP
JavaScript窗口功能指南之在窗口中书写内容
2006/07/21 Javascript
符合标准的js表单提交的代码
2007/09/13 Javascript
js 屏蔽鼠标右键脚本附破解方法
2009/12/03 Javascript
基于JQuery的模拟苹果桌面Dock效果(稳定版)
2012/10/15 Javascript
JS 删除字符串最后一个字符的实现代码
2014/02/20 Javascript
详解js的六大数据类型
2016/12/27 Javascript
利用Vue实现移动端图片轮播组件的方法实例
2017/08/23 Javascript
javascript导出csv文件(excel)的方法示例
2019/08/25 Javascript
vue-列表下详情的展开与折叠案例
2020/07/28 Javascript
利用Python如何生成随机密码
2016/04/20 Python
pygame游戏之旅 python和pygame安装教程
2018/11/20 Python
django url到views参数传递的实例
2019/07/19 Python
关于Python中的向量相加和numpy中的向量相加效率对比
2019/08/26 Python
Python 实现Serial 与STM32J进行串口通讯
2019/12/18 Python
使用sklearn的cross_val_score进行交叉验证实例
2020/02/28 Python
使用pyecharts1.7进行简单的可视化大全
2020/05/17 Python
opencv 图像礼帽和图像黑帽的实现
2020/07/07 Python
详解python中GPU版本的opencv常用方法介绍
2020/07/24 Python
关于PyCharm安装后修改路径名称使其可重新打开的问题
2020/10/20 Python
python unichr函数知识点总结
2020/12/16 Python
使用python实现学生信息管理系统
2021/02/25 Python
说出一些常用的类,包,接口
2014/09/22 面试题
求职推荐信
2013/10/28 职场文书
销售心得体会
2014/01/02 职场文书
元旦寄语大全
2014/04/10 职场文书
群众路线党员个人整改措施
2014/10/27 职场文书
培训班开班主持词
2015/07/02 职场文书
2015暑期社会实践个人总结
2015/07/13 职场文书
中学政教处工作总结
2015/08/13 职场文书
学法用法心得体会(2016推荐篇)
2016/01/21 职场文书
Python序列化模块JSON与Pickle
2022/06/05 Python