自学内容网 自学内容网

turtle实现贪吃蛇小游戏

今天分享一篇利用python的turtle库实现贪吃蛇小游戏,适合初学者的朋友学习

技术点:

  • 函数应用
  • time库应用
  • random库应用
  • turtle库应用

无身体碰撞的版本,完整代码先附上

import turtle
import random
import time

delay = 0.1     #延迟时间
score = 0       #当前分数
high_score = 0  #最高分数

#创建游戏窗口
wn = turtle.Screen()
wn.title('贪吃蛇')
wn.bgcolor('black')
wn.setup(width=600, height=600)
wn.tracer(0)    #关闭屏幕自动刷新

#创建snake head
head = turtle.Turtle()
head.shape('square')    #方块
head.color('white')     #颜色
head.penup()
head.goto(0,0)          #出现的位置
head.direction = 'Stop' #移动方向

#创建食物
food = turtle.Turtle()
colors = random.choice(['red','green','blue'])  #随机产生食物颜色
shapes = random.choice(['square','circle'])     #随机产生食物形状
food.color(colors)
food.shape(shapes)
food.speed(0)           #食物出现速度
food.penup()
food.goto(0, 100)       #食物出现的位置

#创建积分榜
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'))

#定义方向键
def goup():
    # 方向朝下禁止向上移动
    if head.direction != "down":
        head.direction = "up"

def godown():
    # 方向朝上禁止向下移动
    if head.direction != "up":
        head.direction = "down"

def goleft():
    # 方向朝右禁止向左移动
    if head.direction != "right":
        head.direction = "left"

def goright():
    # 方向朝左禁止向右移动
    if head.direction != "left":
        head.direction = "right"

#定义移动函数
def move():
    if head.direction == 'up':
        y = head.ycor()     #当前乌龟y轴坐标
        head.sety(y+20)
    if head.direction == 'down':
        y = head.ycor()     #当前乌龟y轴坐标
        head.sety(y-20)
    if head.direction == 'left':
        x = head.xcor()     #当前乌龟x轴坐标
        head.setx(x-20)
    if head.direction == 'right':
        x = head.xcor()     #当前乌龟x轴坐标
        head.setx(x+20)

#启动事件监听,窗口能够响应键盘事件
wn.listen()
wn.onkeypress(goup, 'w')
wn.onkeypress(godown, 's')
wn.onkeypress(goleft, 'a')
wn.onkeypress(goright, 'd')

segments = []               #碎片

#循环,启动游戏
while True:
    wn.update()     #手动刷新

    #撞墙检测,重新开始
    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'
        colors = random.choice(['red','green','blue'])  #随机产生食物颜色
        shapes = random.choice(['square','circle'])     #随机产生食物形状
        for segment in segments:
            segment.goto(1000,1000)                     #清除碎片
        segments.clear()                                #清除碎片列表
        score = 0
        delay = 0.1
        pen.clear()
        pen.write('Score: 0 High Score: 0', align='center', font=('Courier', 24, 'normal'))
        food.shape(shapes)
        food.color(colors)

    #吃食物
    if head.distance(food) < 20:
        x = random.randint(-270, 270)
        y = random.randint(-270, 270)
        colors = random.choice(['red','green','blue'])  #随机产生食物颜色
        shapes = random.choice(['square','circle'])     #随机产生食物形状
        food.shape(shapes)
        food.color(colors)
        food.goto(x,y)

        # 添加新的碎片,蛇长大
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape('square')
        new_segment.color('orange')
        new_segment.penup()
        segments.append(new_segment)        #放入到列表中
        delay -= 0.001
        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'))
        
    for index in range(len(segments)-1, 0, -1):
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x,y)
    if len(segments) > 0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x,y)
    
    move()          #启动移动函数
    time.sleep(delay)       # 调用time模块中的sleep函数,使程序暂停执行0.1秒

wn.mainloop()   #启动事件循环

原文地址:https://blog.csdn.net/sinat_27956747/article/details/142408616

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!