pyhon小游戏贪吃蛇

该博客展示了如何使用Python的turtle库和random库创建一个基本的贪吃蛇游戏。游戏包括设置游戏环境、定义蛇的移动和碰撞检测、更新食物位置等功能。玩家可以通过键盘控制蛇的方向,当蛇碰到边界或自身时,游戏结束。
摘要由CSDN通过智能技术生成

环境:

pyhon3.6

time

turtle

random

下载:

pip install pygame
pip install random
pip install turtle

效果:

 源码:

import time
import turtle
from random import randrange

snake = [[0, 0]]
aim = [0, 10]
food = [-10, 0]


def change_direction(x, y):
    aim[0] = x
    aim[1] = y


def sqaure(x, y, size, color):
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    turtle.begin_fill()
    turtle.color(color)
    for i in range(4):
        turtle.forward(size)
        turtle.left(90)
    turtle.end_fill()


import copy

def inside(head):
    return -250<head[0]<250 and -250 <head[1] <250

def snake_move():
    #head = snake[-1][:]
    # 获取蛇头
    head = [snake[-1][0],snake[-1][1]]
    # 最后一个加方向
    head = [head[0] + aim[0], head[1] + aim[1]]
    # 加过后还在蛇里面,不在画布里面
    if head in snake or not inside(head):
        # 红色
        sqaure(head[0],head[1],10,'red')
        print('Game over.')
        turtle.update()
        return
    if head == food:
        # 遇到食物
        print("snake", len(snake))
        food[0] = randrange(-15, 15) * 10
        food[1] = randrange(-15, 15) * 10
    else:
        snake.pop(0)
        # 删除蛇尾
    snake.append(head)
    turtle.clear()
    sqaure(food[0], food[1], 10, "green")
    for body in snake:
        sqaure(body[0], body[1], 10, "Blue")
    turtle.update()
    turtle.ontimer(snake_move, 300)

turtle.setup(500,500)
turtle.hideturtle()
turtle.listen()
turtle.onkey(lambda: change_direction(0, 10), "Up")
turtle.onkey(lambda: change_direction(0, -10), "Down")
turtle.onkey(lambda: change_direction(-10, 0), "Left")
turtle.onkey(lambda: change_direction(10, 0), "Right")
turtle.tracer(False)
snake_move()
turtle.done()

如果对你有帮助的话给我点个赞吧

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值