赞
踩
今天来尝试下用python写一个贪吃小游戏,哈哈哈哈,毕竟贪吃蛇,大家小时候都玩过,但现在却有机会自己实现一个!!!
文末送读者福利
效果图
其实就是一个点,往右,往下,往左,往上,回到原点…
# 坐标,长度,颜色名称
def square(x, y, size, color):
import turtle
turtle.up()
turtle.goto(x, y)
turtle.down()
turtle.color(color)
turtle.begin_fill()
for count in range(4):
turtle.forward(size)
turtle.left(90)
turtle.end_fill()
然后我们就可以画出一个正方啦。
蛇的身子其实就是一个一个方块列表,所以我们来尝试画多个方块。
snake = [[0,0],[0,10]]
for body in snake:
square(body[0], body[1], 10, 'black')
蛇需要可以朝四个方向移动。
x,y代表坐标
(10,0):代表向右移动
(-10,0):代表想左移动
(0,10):代表向上移动
(0,-10):代表向下移动
aim = [0, 10]
# 设置方向
def change_direction(x, y):
aim[0] = x
aim[1] = y
有了移动方向,我们就可以开始写移动的逻辑啦
思路是这样的:我们把列表看成一条蛇,这条蛇的右边在右边,尾部在左边!
移动时,我们消除尾部的一个方块。
根据方向,在头部添加一个方块。
然后在刷新动画。
就可以完成蛇移动的效果啦。
下面是代码
现在蛇就可以移动啦,但是我们还不能控制它的方向!
我们来监听键盘的按键,用上下左右来控制蛇的移动!
turtle.listen()
turtle.onkey(lambda: change_direction(10, 0), "Right")
# 右
turtle.onkey(lambda: change_direction(-10, 0), "Left")
# 左
turtle.onkey(lambda: change_direction(0, 10), "Up")
# 上
turtle.onkey(lambda: change_direction(0, -10), "Down")
# 下
首先一个食物被吃掉时,我们就在一个指定的区间里,随机产生食物。
当蛇碰到自己或者当蛇碰到边界的时候,我们就算输啦!!
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') 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, "black") 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()
这样我们就我完成了一个简单的贪吃蛇的游戏啦,我们还可以调成速度,记录分数,还有更多的功能,大家可以自行添加。
除了上述分享,如果你也喜欢编程,想通过学习Python获取更高薪资,这里给大家分享一份Python学习资料。
这里给大家展示一下我进的最近接单的截图
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。