Python使用turtle库编写贪吃蛇小游戏

用turtle做一个简单的贪吃蛇小游戏,要求代码模块化,工程代码要分为主程序入口、功能模块和配置文件三个.py文件。

程序完成的功能:

(1)死亡条件:撞自己、撞边界;(额~撞自己的的功能不太好使)

(2)初始有3条生命,死亡一次减一条;

(3)添加一种随机生成的食物,效果为吃了之后变长2格;

先看一下结果图:

上shi山代码!(功能是好使的,逻辑是emmmm)

1.snake.py

import turtle
import random
import sys
from settings import *

# 死亡判断
def death():
    global life #生命数
    global flag #标记是否死亡
    # 碰到边界死亡(蛇头坐标是否>=边界值)
    if snake_pos[-1][0]>=width//2 or snake_pos[-1][1]>=height//2 or snake_pos[-1][0]<=-width//2 or snake_pos[-1][1]<=-height//2:
        life -=1
        snake_pos.clear()
        snake_pos.append([0,0])
    # 碰到自身死亡
    elif touch_self():
        life -= 1
        snake_pos.clear()
        snake_pos.append([0, 0])
    # 生命耗尽结束游戏
    elif life == 0:
        flag = True
        # turtle.clear()
        # draw_gameover()

# 判断是否碰到了自己的身体碰到自己的身体
def touch_self():
    # 新的蛇头位置
    new_head = [snake_pos[-1][0]+ direction_x *speed,snake_pos[-1][1] + direction_y * speed]
    for pos2 in snake_pos[0:]:
        if pos2[0]==new_head[0] and pos2[1]==new_head[1]:
            return True
        else:
            return False

# 绘制游戏结束
def draw_gameover():
    turtle.up()
    turtle.goto(0, 0)
    turtle.down
    turtle.write('GAMEOVER', align='center', font=('Arial', 30, 'bold'))

# 显示生命数
def draw_life():
    turtle.up()
    turtle.goto(-width//2+20,height//2-50)
    turtle.down()
    turtle.write('生命:'+str(life),align='left',font=('楷体',15,'normal'))

# 绘画圆圈
def draw_circle(x,y,clr):
    turtle.up()
    turtle.goto(x, y)
    turtle.down()
    turtle.dot(20,clr)
    turtle.up()

#随机生成特殊食物的坐标和颜色
def gen_super():
    """每运行一次生成一个食物"""
    x = random.randrange(-width//2, width//2, size)
    y = random.randrange(-height//2, height//2, size)
    c = random.choice(colors)
    super = (x, y, c)
    superfoods.append(super)

#绘画特殊食物
def draw_super():
    for super in superfoods:
        x, y, c = super
        draw_circle(x, y, clr=c)

#移除食物并更新蛇
def collision2():
    global superfoods,score
    eated2 = []
    sx,sy = snake_pos[-1]
    for super in superfoods:
        x,y,c = super
        # 如果蛇吃到食物,分数加一
        if sx == x and sy == y:
            eated2 = x,y,c
            snake_pos.insert(0,[x,y,])
            snake_pos.insert(0,[x,y,])
    # 将被吃到的食物从foods中移除
    if len(eated2):
        superfoods.remove(eated2)
        score +=2

# 绘画小方块
def draw_rect(x,y,s=size,clr='red'):
    turtle.up()
    turtle.goto(x,y)
    turtle.color(clr)
    turtle.down()
    turtle.begin_fill()
    for i in range(4):
        turtle.forward(s) #小方块边长
        turtle.left(90)
    turtle.end_fill()
    turtle.up()

# 随机生成颜色 并存入color
def gen_color():
    global colors
    r = random.randint(0,255)
    g = random.randint(0,255)
    b = random.randint(0,255)
    c = (r,g,b)
    colors.append(c)

# 食物随机生成的参数,并添加到foods
def gen_food():
    """每运行一次生成一个食物"""
    x = random.randrange(-width//2, width//2, size)
    y = random.randrange(-height//2, height//2, size)
    c = random.choice(colors)
    food = (x, y, c)
    foods.append(food)

# 绘画食物
def draw_food():
    for food in foods:
        x, y, c = food
        draw_rect(x, y, clr=c)

def draw_snake():
    for pos in snake_pos:
        if pos == snake_pos[-1]:
            draw_rect(pos[0], pos[1],clr='black')
        else:
            draw_rect(pos[0],pos[1])

#蛇的更新
def update_snake():
    headx = snake_pos[-1][0]+ direction_x *speed
    heady = snake_pos[-1][1] + direction_y * speed
    snake_pos.append([headx,heady])
    snake_pos.pop(0)

# 控制方向
# 向左
def key_left():
    global direction_x, direction_y
    direction_x = -1
    direction_y = 0

# 向右
def key_right():
    global direction_x, direction_y
    direction_x = 1
    direction_y = 0
# 向上
def key_up():
    global direction_x, direction_y
    direction_y = 1
    direction_x = 0
# 向下
def key_down():
    global direction_x, direction_y
    direction_y = -1
    direction_x = 0

def key_Q():
    global q
    q = True

#暂停游戏
def key_P():
    global p
    p = not p

#绘制暂停界面
def draw_pause():
    turtle.up()
    turtle.goto(0,0)
    turtle.down
    turtle.write('PAUSE', align='center', font=('Arial',100,'bold'))

def collision():
    global foods,score
    eated = []
    sx,sy = snake_pos[-1]
    for food in foods:
        x,y,c = food
        # 如果蛇吃到食物,分数加一
        if sx == x and sy == y:
            eated = x,y,c
            snake_pos.insert(0,[x,y,])
    # 将被吃到的食物从foods中移除
    if len(eated):
        foods.remove(eated)
        score +=1

# 显示得分
def draw_score():
    turtle.up()
    turtle.goto(-width//2+20,height//2-20)
    turtle.down()
    turtle.write('得分:'+str(score),align='left',font=('楷体',15,'normal'))

def init():
    turtle.setup(width, height)
    turtle.tracer(0)   # 隐藏轨迹
    turtle.hideturtle() # 隐藏画笔
    turtle.listen() # 创建监听
    turtle.onkey(key_left, 'Left')
    turtle.onkey(key_right, 'Right')
    turtle.onkey(key_up, 'Up')
    turtle.onkey(key_down, 'Down')
    turtle.onkey(key_Q, 'Q')
    turtle.onkey(key_Q, 'q')
    turtle.onkey(key_P, 'P')
    turtle.onkey(key_P, 'p')
    turtle.colormode(255)
    #初始化生成五个颜色
    for i in range(5):
        gen_color()
    #三个普通食物
    for i in range(3):
        gen_food()
    #两个特殊食物
    for i in range(2):
        gen_super()

def run():
    # 程序运行
    global clock
    turtle.clear()
    if p:
        draw_pause()
    elif flag:
        draw_gameover()
    else:
        # if .... gen_food(), 每3秒
        clock += 1
        if clock >= 30:
            gen_food()
            gen_super()
            clock = 0

        collision()
        collision2()
        draw_food()
        draw_super()
        draw_snake()
        draw_score()
        draw_life()
        touch_self()
        death()
        turtle.update()
        update_snake()
        # print('score:',score)

    if q:
        sys.exit(0)
    # turtle.ontimer('函数','时间(ms)')
    turtle.ontimer(run, 100)

def mainloop():
    run()
    turtle.done()

2.main_snake.py(程序的入口)

from app import *

if __name__ == '__main__':
    init()
    mainloop()

3.settings.py(相关基础设定)

width  = 600  # -width//2,  width//2
height = 400  # -height//2, height//2

# 设置相关
size = 20
q = False
p = False
clock = 0 # 0~3之间
score = 0 #得分
life = 3 #生命
flag = False

# 蛇相关
snake_pos = [[0, 0]]
speed = size
direction_x = 1 # 0不动,1向右,-1向左
direction_y = 0 # 0不动,1向上,-1向下

# 食物相关
foods = []
colors = []
superfoods = []

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值