Python small game: greedy snake - the use of turtle

  

I suddenly want to integrate the small game exercises I wrote last year and write a simple teaching article.

This article mainly explains the use of the turtle package in python to make small games, does not involve the use of pygame, and can be realized only with pycharm

0. Clarify the game idea

  The effect to be achieved is shown in the figure below:

Black is a snake, and red is an apple generated by a random function. If the snake does not eat an apple, it will add another section, and the next apple will be randomly generated in the frame.

The movement of the snake is represented by refreshing the page. Every time the page is refreshed, the drawing function will draw a small square at the position of the snake's head and delete the small square at the position of the snake's tail. In this way, the movement of the snake is realized.

The snake must not hit the border, otherwise the game fails (stops running).

Among them, snakes and apples are realized by using turtle drawing (turtle).

1.turtle library

Turtle is a library that comes with python, mainly used for drawing. (It is said to be like a sea turtle crawling picture?

The turtle library comes with many drawing functions: (here are only some of the functions used by Snake)

up() pen function
goto(x,y) function to go to (x,y) position
forward(size) Walk in a specific direction, the parameter indicates the length of the drawn line
left(size) Steering function, the parameter is the degree of turning (the snake turns 90 degrees each time, fill in 90)
begin_fill() No parameter, start drawing (pen down)
end_fill() No parameter, end of drawing
color(color_name) Set the line color, fill in the color name in the brackets

Because the "drawing" action needs to be called cyclically, you can write a function to wrap this function to facilitate multiple cyclic use.

This part of the code:

from turtle import *
from random import randrange

                        #Pay attention to the import package, (the following needs to use the random function, so also import the package random function)

def square(x,y,size,color_name):  #函数名称可自定义,参数:需要用的什么就设置什么
    up()
    goto(x,y)                     #画笔移动到某一点
    color(color_name)             #设置画笔颜色
    begin_fill()                  #落笔开画

    forward(size)                 #画笔画直线
    left(90)                      #转向90度        以下代码段表示每次画一个小方格
    forward(size)
    left(90)
    forward(size)
    left(90)
    forward(size)
    left(90)
    end_fill()                    #绘图结束

2. Define the snake and the apple

The initial length of the snake must not be a small square.

Here my initial snake defines the length of four small squares, each of which is 10; (It can be customized. Tip: It is best to use an integer to avoid the situation that the snake head and the apple "do not match".)

snack=[[0,0],[10,0],[20,0],[30,0]]
apple_x=randrange(-20,20)*10          #定义小苹果,和苹果的位置坐标
apple_y=randrange(-20,20)*10
aim_x=0
aim_y=10                              #蛇的起始位置坐标

define action function

def change(x,y):
    global aim_x,aim_y
    aim_x=x
    aim_y=y

3. Judgment of "hitting the wall"

First paste my code snippet

def inside():
    if -210<=snack[-1][0]<=200 and -210<=snack[-1][1]<210 :
        return True
    else:
        return False

The inside function determines whether the snake is inside the canvas, that is, whether it hits the wall.

Here I set the size of the canvas to 420*420 (210 is the average coordinate, from -210 to +210). Because the length of each section of the snake is 10, the judgment condition is whether the head of the snake is smaller than or equal to 200, and if it is smaller than return true, you can continue to run, otherwise false, end the run.

4. Function recycling

It is equivalent to nesting the above function in a new Loop function, so that the Loop is called once every refresh.

Clear() and update() are used together - Refresh: Erase old lines and draw new ones.

def gameLoop ():                         #自定义循环函数
    global apple_x,apple_y               #需要用到外面的全局变量
    clear()                              #擦除旧图的函数,清理函数
    snack.append([snack[-1][0]+aim_x,snack[-1][1]+aim_y])    #小蛇的出现位置
    if not inside():                                         #判断是否还在画布内
        return
    if snack[-1][0]!=apple_x or snack[-1][1]!=apple_y :
        snack.pop(0)                           #判断小蛇安全前行,擦除尾部,使用pop函数删除
    else:
        apple_x=randrange(-20,20)*10           #吃到苹果,则随机生成另一个新的苹果
        apple_y=randrange(-20,20)*10
    for n in range(len(snack)):
        square(snack[n][0],snack[n][1],10,"black")    #调用画图函数,定义黑色小蛇,红色苹果
    square(apple_x,apple_y,10,"red")
    ontimer(gameLoop,200)                            #调用循环函数,每隔一段时间调用一次
    update()                                         #更新

5. Closing: setting up the canvas, hiding the small arrows for drawing turtles, using monitoring functions, and keyboard manipulation

Note: setup(420, 420, 0, 0) means to set a flat canvas with a size of 420*420, and the previous 210 is the forward coordinate!

setup(420,420,0,0)        #设置画布
hideturtle()              #隐藏海龟画图的小标签,为了美观
tracer(False)             #不显示轨迹路线
listen()                  #监听函数
onkey(lambda :change(0,10),"w")      #键盘操控,点击相应案件实现改变方向操作
onkey(lambda :change(0,-10),"s")
onkey(lambda :change(10,0),"d")
onkey(lambda :change(-10,0),"a")
gameLoop()                            #循环函数
done()                                

———————————————————————————————————————————

Come to a code integration:

from turtle import *
from random import randrange

def square(x,y,size,color_name):
    up()
    goto(x,y)
    color(color_name)
    begin_fill()

    forward(size)
    left(90)
    forward(size)
    left(90)
    forward(size)
    left(90)
    forward(size)
    left(90)
    end_fill()

snack=[[0,0],[10,0],[20,0],[30,0]]
apple_x=randrange(-20,20)*10
apple_y=randrange(-20,20)*10
aim_x=0
aim_y=10
def change(x,y):
    global aim_x,aim_y
    aim_x=x
    aim_y=y
def inside():
    if -210<=snack[-1][0]<=200 and -210<=snack[-1][1]<210 :
        return True
    else:
        return False
def gameLoop ():
    global apple_x,apple_y
    clear()
    snack.append([snack[-1][0]+aim_x,snack[-1][1]+aim_y])
    if not inside():
        return
    if snack[-1][0]!=apple_x or snack[-1][1]!=apple_y :
        snack.pop(0)
    else:
        apple_x=randrange(-20,20)*10
        apple_y=randrange(-20,20)*10
    for n in range(len(snack)):
        square(snack[n][0],snack[n][1],10,"black")
    square(apple_x,apple_y,10,"red")
    ontimer(gameLoop,200)
    update()

setup(420,420,0,0)
hideturtle()
tracer(False)
listen()
onkey(lambda :change(0,10),"w")
onkey(lambda :change(0,-10),"s")
onkey(lambda :change(10,0),"d")
onkey(lambda :change(-10,0),"a")
gameLoop()
done()

 

 

 

Guess you like

Origin blog.csdn.net/leowutooo/article/details/124764732