How to write a Snake game in Python?

王林
Release: 2023-05-09 20:55:06
forward
3353 people have browsed it

Snake Python mini game (source code comments can be pasted and used) This Snake game is very simple and avoids using pygame which is difficult to load. The following is the running diagram:

How to write a Snake game in Python?

How to write a Snake game in Python?

Game code implementation

1. Drawing images

In drawing game images, we use a database that is more accurate than pygame Light Turtle Graphics

Build database (gamebase.py)
from turtle import * # "*"是引用所有函数

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

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

    end_fill()
Copy after login

The above is drawing through turtle, advance unit distance and then rotate 90 degrees, and then rotate 90 degrees again until a small square is drawn

Draw Apple (snake.py)

Reference the database we just drew

from turtle import *
from gamebase import square
from random import randrange
Copy after login

Then define the size of the canvas

setup(420,420,0,0)
//隐藏乌龟头 emoj.emoj.
hideturtle
//隐藏轨迹
tracer(False)

//绘制
done()
Copy after login
Define the game program loop (equivalent to Loop thread in Java)
def gameLoop():
	//随机生成苹果
	apple_x = randrange(-200, 200)
	apple_y = randrange(-200, 200)
	//绘制苹果
	square(apple_x, apple_y, 10, "red")
	//刷新画布
	update()
Copy after login
Drawing Snake (snake.py)

Note that we can think of Snake as a queue, and each element in this queue Both contain two variables (the horizontal and vertical coordinates of the element)

def gameLoop():
	//随机生成苹果
	apple_x = randrange(-200, 200)
	apple_y = randrange(-200, 200)
	//绘制蛇
	for n in range(len(sanke)):
		square(snake[n][0],snake[n][1[],10,"black)
	//绘制苹果
	square(apple_x, apple_y, 10, "red")
	//刷新画布
	update()
Copy after login
Drawing the movement of the greedy snake

Principle of the movement of the snake: In order to facilitate the movement of the snake, we have to flip the snake into the queue, when it moves, we will throw out the first element of the snake queue (pop()), and then add an element to the tail of the snake (append())

global apple_x, apple_y, snake, aim_x, aim_y #全局变量申请snake.append([ snake[-1][0] + aim_x, snake[-1][1] + aim_y ])snake.pop(0)global apple_x, apple_y, snake, aim_x, aim_y 
#全局变量申请
snake.append([ snake[-1][0] + aim_x, snake[-1][1] + aim_y ])
snake.pop(0)
Copy after login

Then, we To add a loop to refresh the running time,

ontimer(gameLoop, 100)
 # 每100毫秒运行一下gameLoop函数
Copy after login
Create a snake operation response

We need to establish a keyboard monitor, which is very simple for python

listen() #监听
onkey(lambda: change(0, 10), "w")
onkey(lambda: change(0, -10), "s")
onkey(lambda: change(-10, 0), "a")
onkey(lambda: change(10, 0), "d")
gameLoop()
Copy after login
Determine the snake Whether to eat the apple

This is also very easy. We only need to compare whether the horizontal and vertical coordinates of the snake's head are equal to the horizontal and vertical coordinates of the apple (the snake's head coincides with the apple)

 if snake[-1][0] != apple_x or snake[-1][1] != apple_y:
        snake.pop(0)
    else:
        apple_x = randrange(-20, 18) * 10
        apple_y = randrange(-19, 19) * 10
Copy after login
To determine whether the snake has bitten Myself

This principle is similar to the above principle of whether the snake eats the apple

def bite():
    for n in range(len(snake)-1):
        if snake[-1][0] == snake[n][0] and snake[-1][1] == snake[n][1]:
            return True
    return False
Copy after login
Determine whether the snake is within the bounds
def inside():
    if -200 <= snake[-1][0] <= 180 and -190 <= snake[-1][1]<=190:
        return True
    else :
        return False
Copy after login

Game source code

gamebase.py
from turtle import * # "*"是引用所有函数

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

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

   end_fill()
Copy after login
snake.py
from  time import sleep

apple_x = randrange(-20, 18) * 10
apple_y = randrange(-19, 19) * 10
snake = [[0, 0], [10, 0], [20, 0], [30, 0], [40, 0], [50, 0]]
aim_x = 10
aim_y = 0


def inside():
    if -200 <= snake[-1][0] <= 180 and -190 <= snake[-1][1]<=190:
        return True
    else :
        return False


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


def bite():
    for n in range(len(snake)-1):
        if snake[-1][0] == snake[n][0] and snake[-1][1] == snake[n][1]:
            return True
    return False


def gameLoop():
    global apple_x, apple_y, snake, aim_x, aim_y #全局变量申请
    snake.append([ snake[-1][0] + aim_x, snake[-1][1] + aim_y ])
    if snake[-1][0] != apple_x or snake[-1][1] != apple_y:
        snake.pop(0)
    else:
        apple_x = randrange(-20, 18) * 10
        apple_y = randrange(-19, 19) * 10

    if(not inside()) or bite():
        square(snake[-1][0], snake[-1][1], 10,"hotpink")
        update()
        sleep(2)# 暂停2秒
        apple_x = randrange(-20, 18) * 10
        apple_y = randrange(-19, 19) * 10
        snake = [[0, 0], [10, 0], [20, 0], [30, 0], [40, 0], [50, 0]]
        aim_x = 10
        aim_y = 0
    n = 0
    clear()
    square(-210,-200,410,"black")
    square(-200,-190,390,"white")
    square(apple_x, apple_y, 10, "red")
    for n in range(len(snake)):
        square(snake[n][0], snake[n][1], 10, 'black')
    ontimer(gameLoop, 100)  # 每300毫秒运行一下gameLoop函数
    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), "a")
onkey(lambda: change(10, 0), "d")
gameLoop()
done()
Copy after login

The above is the detailed content of How to write a Snake game in Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template