This article is participating in Python Theme Month. See the link for details

Hello everyone, today I found another interesting gadget. I’m an old poet of fun gadgets.

Same old rule. Renderings first

This is a little snake game. We, the post-8090 generation, are sure to encounter it. Snakes get longer and longer with the food they eat. Then touch the wall or touch your body to lose the game. This is a crude version of Snake, but the basic logic of the game has been implemented.

First, define the objects in the game:

food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)
Copy the code

There’s food and snakes in here, and directions.

Up, down, left and right to control the snake.

onkey(lambda: change(10, 0), 'Right')
onkey(lambda: change(-10, 0), 'Left')
onkey(lambda: change(0, 10), 'Up')
onkey(lambda: change(0, -10), 'Down')
Copy the code

Here the onkey is to detect the keyboard. Chang then changes the direction in which the snake moves. Of course, we can use other keyboard keys to operate, such as WSAD, can also control the left and right.

Move and update logic

def move():
    "Move snake forward one segment."
    head = snake[-1].copy()
    head.move(aim)

    if not inside(head) or head in snake:
        square(head.x, head.y, 9, 'red')
        update()
        return

    snake.append(head)

    if head == food:
        print('Snake:', len(snake))
        food.x = randrange(-15, 15) * 10
        food.y = randrange(-15, 15) * 10
    else:
        snake.pop(0)

    clear()

    for body in snake:
        square(body.x, body.y, 9, 'black')

    square(food.x, food.y, 9, 'green')
    update()
    ontimer(move, 100)
Copy the code

The code above is the core logic of Snake. It’s about snake movement and logic renewal.

1 The whole snake is moved from the direction of head. Move (AIM) update.

2If not inside(head) or head in snake: If not inside(head) or head in snake, then the snake will turn red. There’s a return, which is exit logic

3If head == food: Print the length of the snake and update the location of the food. Square (food.x, food.y, 9, ‘green’) is to turn food green.

4. The whole game is a recursion. Ontimer controls the number of time frames, and the final exit mechanism is return.

Overall, the game is not too difficult and easy to learn. The above idea is quite clear. Need to get the full source code, please go to the public number: poetic code. Since come in, original is not easy. Just give me a “like” and leave.

Collection series:

Pac-man, Childhood Memories | Python Theme Month

Snake, Childhood Memories | Python Theme month

Tic-tac-toe, Childhood Memories | Python Theme Month

Memory Palace, Childhood Memories | Python Theme Month