首页 > 其他分享 >turtle实现贪吃蛇小游戏

turtle实现贪吃蛇小游戏

时间:2024-09-20 17:03:45浏览次数:1  
标签:turtle head food wn random direction pen 小游戏 贪吃蛇

今天分享一篇利用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()   #启动事件循环

 

标签:turtle,head,food,wn,random,direction,pen,小游戏,贪吃蛇
From: https://www.cnblogs.com/liuyangjava/p/18422851

相关文章

  • 在ARM开发板上实现2048小游戏
     event.h屏幕点击事件.h文件:获取屏幕的xy坐标,获取手指滑动的方向,获取点击事件。#ifndef__EVENT_H_#define__EVENT_H_#include<stdio.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<unistd.h>#include<dirent.h>#inclu......
  • BlockCraft小游戏开发搭建
    BlockCraft小游戏开发搭建(张先生13101716752微电)BlockCraft游戏模式开发以下是关于BlockCraft游戏开发的一些要点:一、游戏概念与设计游戏主题与背景方块建造与探索以方块为基本元素构建一个开放世界的游戏主题。游戏背景设定在一个充满无限可能的虚拟世界,这个世界由各种......
  • 几种提升turtle绘图速度的方法
    问题来源最近老师要求设计程序模拟伽尔顿板。程序设计还是很简单的只需在每次下落时从[0,1]之间产生一个随机整数,若为零则向左反之向右,并用一个变量来记录向右的次数以确定小球的最终出口。但是为了准确性,要投成千上万次,看着小乌龟慢慢爬。。。。光绘制10层柱子都要1分钟。......
  • C++实现的小游戏
    大家好,这几天做项目太忙,时间不够去更新,十分抱歉。今天凌晨花了半个点的时间写了一个小游戏的青春版,给大家分享。游戏名:想玩电脑?先过我这关!首先我先来说明一下游戏的规则:我们用C++写了一个0~100的随机数,用户有五次机会可以猜数字,猜对了就可以玩电脑,猜错了电脑就会关机(当然你要......
  • 少儿编程小游戏 | Scratch 火柴人团队冒险:重装上阵
    在线玩:Scratch多人游戏-《火柴人团队冒险:重装上阵》免费下载-小虎鲸Scratch资源站在少儿编程的世界中,团队合作和冒险精神是激发孩子创造力的重要元素。今天我们将为大家介绍一款Scratch平台上的经典少儿编程小游戏——《火柴人团队冒险:重装上阵》。这款游戏不仅带来了团队合......
  • C语言小游戏:猜数字 惩罚关机
    #define_CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<time.h>#include<stdlib.h>#include<windows.h>//菜单voidmenu(){   printf("******************\n");   printf("*****1.play*****\n");   prin......
  • 用Python做一个小游戏
    首先,我们需要定义一个类,然后创建一副牌,最后实现一些基本的功能定义扑克牌类:classCard:def__init__(self,suit,rank):self.suit=suitself.rank=rankdef__repr__(self):returnf"{self.rank}of{self.suit}"创建一副扑克牌:suits=[......
  • C#编程挑战: 从零开始构建贪吃蛇游戏
    C#编程挑战:从零开始构建贪吃蛇游戏引言贪吃蛇游戏是一款经典且广受欢迎的电子游戏,玩家通过控制一条蛇在屏幕上移动,吃掉食物并避免撞到墙壁或自己的身体。本文将指导你如何使用C#编程语言从零开始构建一个简单的贪吃蛇游戏。我们将涵盖游戏的基本逻辑、图形用户界面(GUI)的实现以及......
  • 贪吃蛇游戏开发 scratch 20240916_140728
    项目名称贪吃蛇规则只要吃食物就会变长碰到边界就死亡碰到自己的尾巴就会死亡角色贪吃蛇食物障碍物关于图像图像分为矢量图与位图矢量图可以无限放大位图放大后会模糊绘制蛇头要求:使用一个圆形来画蛇头圆形有边框蛇头有两个眼睛蛇头有一根红蛇头使用矢量图来绘......
  • Python制作一个中秋赏月的拼图小游戏
    中秋节是中国四大传统节日之一,主要活动包括赏月、吃月饼、玩花灯、赏桂花、饮桂花酒等。给大家分享用Python制作的一个中秋的拼图小游戏模块安装pipinstallpygame实例代码importpygame,sys,randomfrompygame.localsimport*#一些常量#WINDOW_WIDTH=30#WIND......