Mushroom cloud [blank board Python tutorial] lesson 5: 2D maze

Playful maker 2022-05-14 15:33:10 阅读数:620

mushroomcloudblankboardpython

2D maze

Maze is a game that many children often play when they are children , It can exercise our spatial reasoning ability 、 Logical force 、 Patience and perseverance , It can also bring a lot of joy .

Let's design a maze game , stay DFRobot- Experience it on the blank board screen !
2D maze

Mission objectives

The acceleration value is obtained through the three-axis acceleration sensor , Then control the character to move on the map and walk out of the maze .

 Get the acceleration value of the empty board
 Get the acceleration value of the empty board

Knowledge point

1、 Know the three-axis acceleration sensor

2、 Learn to use Pinpong Library method for reading acceleration value

3、 Learn to use turtle Library drawing maze method

List of materials

 Blank board material list

Software use :Mind+ Programming software x1

Knowledge reserve

1、 What is gravitational acceleration and acceleration sensor

The acceleration of objects near the earth's surface due to gravity is called gravitational acceleration , Also known as free fall acceleration , use g Express .

Acceleration sensor , It's a device that can measure acceleration , A device that converts it into an electrical signal .

The acceleration sensor of the empty board is built into the board , It can measure X,Y,Z Acceleration in three directions , among ,X The positive direction of the axis is the direction of one side of the golden finger ,Y The positive direction of the axis is Home The direction of one side of the key ,Z The axis is perpendicular to the board , The positive direction is the direction of the back side of the screen .
 Empty board XYZ Directional acceleration value
 Three axis accelerometer

2、Pinpong The library reads the acceleration value

Pinpong Library “pinpong.extension.unihiker” Under the document “GD32Sensor_acc” Class “get_x()”、“get_y()”、“get_z()” The three methods can obtain x/y/z Acceleration values in three directions , And because the class has been instantiated in the file, a accelerometer object , therefore , When we use , You can go directly through “accelerometer.getx()”/“accelerometer.gety()”/“accelerometer.getz()” Command to obtain the acceleration value in their respective directions . Of course , before this , We need to import Pinpong Library related files and initialize the board .

from pinpong.board import Board # from pinpong.board Import Board modular

from pinpong.extension.unihiker import * # Import pinpong.extension.unihiker All modules in the package

Board().begin() # initialization , Select board type and port number , If it is not entered, it will be recognized automatically

 x = accelerometer.get_x() # obtain x Axis acceleration value
y = accelerometer.get_y() # obtain y Axis acceleration value

among ,x and y It's a variable , Respectively used to store the detected x and y Acceleration value in the axial direction .

3、turtle Common functions of library screen control

turtle There are many functions about screen control in the library , We only use some of them , When programming , adopt “import turtle” After importing the library, you can use “turtle. Function name ()” To realize the function .

(1)bgpic() Function to set the drawing window ( canvas ) Background color

adopt bgpic() Function, we can set the background color for the current window screen .

turtle.bgcolor(“pink”) # Set the window background color

among ,“pink” It means pink . The color here can also be through RGB value 、 Hexadecimal value 、 Fixed values are expressed in three different ways .

(2)clear() Function to clear the window

adopt clear() Function, we can clear the contents of the window .

turtle.clear() # Clear the window

4、turtle Library common functions of brush motion

(1)setheading() The current brush setting

adopt setheading() Function, we can make the brush face any direction .0° It means due east ,90° Indicates due north ,180°/-180° It means due west ,270°/-90° The direction is due south .

setheading() Function to set the brush orientation

turtle.setheading(90) # Set the orientation of the brush to 90° Direction

among ,“90” It refers to the specific direction and angle to point to . The orientation of the brush can be changed by changing the azimuth angle value .

(2)write() Function writing text

adopt write() Function, we can make the brush write text on the window screen .

turtle.write(‘you win!’,font = (‘ Microsoft YaHei ’, 30)) # Writing “you win!”

among ,“you win!” It refers to the specific text content to be written ,align Refers to the alignment ,“center” Indicates center alignment ,font Refers to the font , Here is the size 30 Microsoft elegant black font .

Hands-on practice

Task description 1: Draw a maze

Draw a intricate maze on the screen .

1、 Hardware construction

STEP1: adopt USB The connecting line connects the blank board to the computer

2、 Programming

STEP1: Create and save project files

start-up Mind+, Save the project as and name it “005、2D maze ”.

STEP2: Create and save Python file

Create a Python Program files “protract.py”, Double-click to open .

STEP3: Programming 1

In this task , We will draw a maze , Because the drawing process of maze diagram is more complex , therefore , We write it separately in protract In the program file , In order to call... Directly later .

(1) Import the required libraries

here , We need to use turtle Library to draw the maze , therefore , We need to import it first .

import turtle # Import turtle library

(2) Create a graphics window

In order to make the maze appear on the screen , We need to create a graphic window with the same size as the screen first , Then create a canvas in the graphics window , Set the corresponding size and background color , And set the screen delay to 0, Avoid caton .

turtle.setup(240, 320) # Set the image window size

turtle.bgcolor(“pink”) # Set the window background color

turtle.delay(0) # Screen delay

(3) Design maze Route Scheme

For the drawing of maze diagram , We do it in two steps . First , We set a width and height to 20 The small square of pixels acts as a wall , after , Take this small square as a unit to set the overall maze , Because the width of the screen is 240 Pixels , High for 320 Pixels , In the horizontal direction , We can draw 13 A square ( The screen shows 11 A whole square +2 One and a half squares on each side ), And vertically , We can draw 13 A square .

here , We use “0” and “1” To indicate the presence or absence of a small square , The route of the maze is expressed in the form of nested list .

Maze list

maze_list = [

[0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0], # The first 0 That's ok

[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # The first 1 That's ok

[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0], # The first 2 That's ok

[0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], # The first 3 That's ok

[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0], # The first 4 That's ok

[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # The first 5 That's ok

[0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0], # The first 6 That's ok

[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # The first 7 That's ok

[0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0], # The first 8 That's ok

[0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], # The first 9 That's ok

[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0], # The first 10 That's ok

[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # The first 11 That's ok

[0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0], # The first 12 That's ok

]

(4) Create a maze class and set the basic properties of the drawing in the class

In actual programming , Let's first create a maze class , Then create the maze object through the instantiation of the class , In the maze class , We first need to define the size of a square , And set some basic properties of the drawing .

class Maze(turtle.Turtle): # Definition Maze class

size = 20 # Set the side width of a grid wall in the maze to 20 Pixels
def __init__(self, maze_list):
# All classes have a name __init__() Function of , It always executes... When the class is started
# __init__ Methods are methods that are specifically used to define which properties a class has
# You need to invoke the initialization method of the parent class before you can call the parent class in the initialization method.
turtle.Turtle.__init__(self) # Unbundling Maze Methods in class , Make it own Turtle Methods in class
self.maze_list = maze_list # Set maze list
# To speed up drawing, hide turtles , Set the speed to the fastest
self.hideturtle() # Hide turtle brush
self.speed(0) # Set turtle movement ( mapping ) The speed is the fastest
self.draw_walls() # Draw the whole maze

(5) Create a function to draw a single square in the maze class

after , We also need to define a function to draw a single square in the class, so that when drawing the whole maze, we can call .

The process of drawing a grid wall in the maze

def draw_wall(self):
self.pendown() # Set pen to paper
self.begin_fill() # fill
self.fillcolor('red') # Set the fill color to red
# First draw a distance of 20 The horizontal line , And then to the right 90 degree , loop 4 Form a square once
for i in range(4):
self.forward(20) # Forward 20 Pixels
self.right(90) # Right rotation 90 degree
self.end_fill() # End of filling
self.penup() # Lift up the brush.

(6) Create a function to draw the whole maze in the maze class

here , We can draw the whole maze by calling the function of drawing a single square and combining the line .

Draw the walls of the entire maze

def draw_walls(self):
self.penup() # Lift up the brush.
self.goto(-120, 120) # Go to the initial position
# Draw walls , A nested loop , Repeat horizontally and vertically 13 Time ( The length and width of the whole maze are determined by 13 The lattice wall consists of )
for row in range(13): # Row cycle
for col in range(13): # Column loop
# In the main function maze_list Inside 1 Then a grid wall is printed
if self.maze_list[row][col] == 1: # If a row or column in the maze list is 1
self.draw_wall() # Draw a single wall
self.goto(20 * (col + 1) - 130, 130 - 20 * row) # Move a column to the right
self.goto(-130, 130 - 20 * (row + 1)) # Down the line

Tips: complete protract The example program is as follows :

Slide up to read

import turtle # Import turtle library

turtle.setup(240, 320) # Set the image window size

turtle.bgcolor(“pink”) # Set the window background color

turtle.delay(0) # Screen delay , Set to 0 Avoid caton

**# turtle.tracer(0) # turns off screen updates
**# turtle.delay(0) # there’s a 10-millisecond pause whenever the turtle moves if the delay is not turned off.
# turtle.tracer(0, 0)

Maze list

maze_list = [

[0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0], # The first 0 That's ok

[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # The first 1 That's ok

[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0], # The first 2 That's ok

[0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], # The first 3 That's ok

[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0], # The first 4 That's ok

[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # The first 5 That's ok

[0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0], # The first 6 That's ok

[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # The first 7 That's ok

[0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0], # The first 8 That's ok

[0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], # The first 9 That's ok

[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0], # The first 10 That's ok

[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # The first 11 That's ok

[0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0], # The first 12 That's ok

]

class Maze(turtle.Turtle): # Definition Maze class

size = 20 # Set the side width of a grid wall in the maze to 20 Pixels
def __init__(self, maze_list):
# All classes have a name __init__() Function of , It always executes when the class is started
# __init__ Methods are methods that are specifically used to define which properties a class has
# You need to invoke the initialization method of the parent class before you can call the parent class in the initialization method.
turtle.Turtle.__init__(self) # Unbundling Maze Methods in class , Make it own Turtle Methods in class
self.maze_list = maze_list # Set maze list
# To speed up drawing, hide turtles , Set the speed to the fastest
self.hideturtle() # Hide turtle brush
self.speed(0) # Set turtle movement ( mapping ) The speed is the fastest
self.draw_walls() # Draw the whole maze
# The process of drawing a grid wall in the maze
def draw_wall(self):
self.pendown() # Set pen to paper
self.begin_fill() # fill
self.fillcolor('red') # Set the fill color to red
# First draw a distance of 20 The horizontal line , And then to the right 90 degree , loop 4 Form a square once
for i in range(4):
self.forward(20) # Forward 20 Pixels
self.right(90) # Right rotation 90 degree
self.end_fill() # End of filling
self.penup() # Lift up the brush.
# Draw the walls of the entire maze
def draw_walls(self):
self.penup() # Lift up the brush.
self.goto(-120, 120) # Go to the initial position
# Draw walls , A nested loop , Repeat horizontally and vertically 13 Time ( The length and width of the whole maze are determined by 13 The lattice wall consists of )
for row in range(13): # Row cycle
for col in range(13): # Column loop
# In the main function maze_list Inside 1 Then a grid wall is printed
if self.maze_list[row][col] == 1: # If a row or column in the maze list is 1
self.draw_wall() # Draw a single wall
self.goto(20 * (col + 1) - 130, 130 - 20 * row) # Move a column to the right
self.goto(-130, 130 - 20 * (row + 1)) # Down the line

STEP4: Programming 2

In the above “protract” In the program , We just created a maze class , But you can't see the effect directly , therefore , Next , So let's create another one “main1.py”Python file , Double click to open the writer , Observe the effect of the drawn maze .

(1) Import the required files

In this task , In order to create maze objects and maintain the window interface , We need to import the just written protract Procedure documents and turtle The library files .

import turtle # Import turtle library

import protract # Import protract modular

(2) Generate the maze object and end the drawing

Last , We generate maze objects through class instantiation , And end the drawing hold window .

protract.Maze(protract.maze_list) # Instantiation Maze class , Create maze objects

turtle.done() # Finish drawing , Hold window

Tips: The complete sample program is as follows :

import turtle # Import turtle library

import protract # Import protract modular

protract.Maze(protract.maze_list) # Instantiation Maze class , Create maze objects

turtle.done() # Finish drawing , Hold window

3、 The program runs

STEP1: Connecting boards

STEP2: Click the run button at the top right , function “main1.py” Program

STEP3: Observe the effect

Observe the empty board , You can see that a pink background appears first , Then small red squares appear in turn from the upper left corner , Finally put together , Formed an intricate maze .

 Observation on the effect of empty board maze

Task description 2: Detect acceleration value

In the last task , We finished drawing the maze map , In order to control the character's movement on the maze through the acceleration value , Next , We need to check the change of acceleration value in different directions first .

1、 Programming

STEP1: Create and save project files

Create a new one Python Program files “main2.py”, Double-click to open .

Step2: Programming

(1) Import the required libraries

Because we will display the acceleration value on the screen , therefore , We need to import unihiker Kuhe time Time bank . meanwhile , In order to be able to detect acceleration , We also need to import Pinpong Related libraries and initialize the line blank board .

from unihiker import GUI # Import unihiker library

import time # Import time library

from pinpong.board import Board # from pinpong.board Import Board modular

from pinpong.extension.unihiker import * # Import pinpong.extension.unihiker All modules in the package

Board().begin() # initialization , Select board type and port number , If the port number is not entered, it will be automatically identified

(2) Instantiation GUI Class and display the initial... On the screen x、y Acceleration value in the axial direction
When displaying the initial acceleration value , We don't have to enter a value , Said is empty .

gui = GUI() # Instantiation GUI class , establish gui object

value_1 = gui.draw_text(x=65, y=65, text=‘x Axis acceleration value :’, font_size=13) # According to the text

value_2 =gui.draw_text(x=65, y=178, text=‘y Axis acceleration value :’, font_size=13)# According to the text

value_x = gui.draw_text(x=85, y=122, text=‘’, font_size=13) # Show initial x Axis acceleration value

value_y = gui.draw_text(x=85, y=240, text=‘’, font_size=13) # Show initial y Axis acceleration value

(3) Cycle to detect the acceleration value and update the value

Next , We do it every 1 It's been testing for seconds x and y Acceleration value in the axial direction , And real-time update is displayed on the screen .

while True:

x = accelerometer.get_x() # obtain x Axis acceleration value
y = accelerometer.get_y() # obtain y Axis acceleration value
value_x.config(text = x) # Update display x Axis acceleration value
value_y.config(text = y) # Update display y Axis acceleration value
time.sleep(1)
print(x,y)

Tips: The complete sample program is as follows :

Slide up to read

from unihiker import GUI # Import unihiker library

import time # Import time library

from pinpong.board import Board # from pinpong.board Import Board modular

from pinpong.extension.unihiker import * # Import pinpong.extension.unihiker All modules in the package

Board().begin() # initialization , Select board type and port number , If it is not entered, it will be recognized automatically

gui = GUI() # Instantiation GUI class , establish gui object

value_1 = gui.draw_text(x=65, y=65, text=‘x Axis acceleration value :’, font_size=13) # According to the text

value_2 = gui.draw_text(x=65, y=178, text=‘y Axis acceleration value :’, font_size=13) # According to the text

value_x = gui.draw_text(x=85, y=122, text=‘’, font_size=13) # Show initial x Axis acceleration value

value_y = gui.draw_text(x=85, y=240, text=‘’, font_size=13) # Show initial y Axis acceleration value

while True:

x = accelerometer.get_x() # obtain x Axis acceleration value
y = accelerometer.get_y() # obtain y Axis acceleration value
value_x.config(text = x) # Update display x Axis acceleration value
value_y.config(text = y) # Update display y Axis acceleration value
time.sleep(1)
print(x,y)

2、 The program runs

STEP1: Connecting boards

STEP2: Run the program and observe the effect

When I hit run , Tilt the empty board from the horizontal position to four different directions . Because when the board is stationary, it only receives a gravitational acceleration , And the gravitational acceleration is always toward the ground , therefore , You can see that when the board tilts down ,x The acceleration value in the axial direction is increasing , When vertical, the value is 1 about ; When the board tilts upward ,x The acceleration value in the axial direction decreases continuously , When vertical, the value is -1 about ; When the board tilts to the left ,y The acceleration value in the axial direction is increasing , When vertical, the value is 1 about ; When the board tilts to the right ,y The acceleration value in the axial direction decreases continuously , When vertical, the value is -1 about ;
 Insert picture description here
 Insert picture description here
 Insert picture description here

Task description 3: Labyrinth

Next , We will combine the drawn maze diagram with acceleration detection , Control the character to walk through the maze through different directions of acceleration .

1、 Programming

STEP1: Create and save project files

Create a new one Python Program files “main3.py”, Double-click to open .

Step2: Programming

(1) Import the required libraries

In this task , We will create a turtle character as a player on the drawn maze , The movement is controlled by the on-board three-axis accelerometer , So we need to import turtle library , Drawing a maze protract Program files ,time Time bank and Pinpong library , And initialize the line blank board .

import turtle # Import turtle library

import time # Import time library

import protract # Import drawing maze file

from pinpong.board import Board # Import pinpong.board In bag Board modular

from pinpong.extension.unihiker import * # Import pinpong.extension.unihiker All modules in the package

Board().begin() # initialization , Select board type and port number , If the port number is not entered, it will be automatically identified

(2) Draw a maze
Because our game is on the maze , therefore , We need to instantiate the last task first protract Created in the program file “Maze“ Class to generate a maze object .

protract.Maze(protract.maze_list) # Instantiation Maze class , Create maze objects

(3) Create a player class , And set the basic properties and functions of players in the class

For player characters on the maze , We generate player objects by creating player classes first and then instantiating them .

meanwhile , In the created player class , We need to set some basic properties and functions of players .

here , We set the player's initial position and end position , Set the map where the player character is located as the maze map , Set the movement speed to the fastest , And make the player move to the starting point of the maze and display it on the screen in the form of a turtle , meanwhile , Set the turtle player's color and initial orientation .

class Player(turtle.Turtle): # Create a player class

def __init__(self, maze_list, start_m, start_n, end_m, end_n):
turtle.Turtle.__init__(self) # Parent class initialization
self.m = start_m # Set the number of lines at the starting point
self.n = start_n # Set the number of columns for the starting point
self.end_m = end_m # Set the number of lines at the end
self.end_n = end_n # Set the number of columns at the end
self.maze_list = maze_list # Set the maze list
self.hideturtle() # Hide turtle brush
self.speed(0) # Set turtle movement ( mapping ) The speed is the fastest
self.penup() # Lift up the brush.
self.goto(self.n * 20 - 120, 120 - self.m * 20) # The player moves to the corresponding position
self.shape('turtle') # Set the player form to turtle
self.color('yellow') # Set the player color to yellow
self.setheading(270) # Set the player's initial direction
self.showturtle() # Show players

(4) Set the movable range in the player class
Due to the game mechanism , We need to set that players can only move in the channels in the maze .

def canmove(self, m, n): # Define where players can move , That is, it is only allowed to move in the channel in the maze

 if 0 <= m and m <= 12: # If in the first place 0 Go to the first place 12 In line
print(m,n) # Print
return self.maze_list[m][n] == 0 # Return value 0, It means the first one m Xing di n There are no walls , Can be moved

(5) Create and set the change of position when moving in the player class
After the player can move , We need to set the change of position when moving .

def move(self, m, n): # Define the player's movement

 self.m = m # Define the number of rows
self.n = n # Define the number of columns
self.goto(self.n * 20 - 120, 120 - self.m * 20) # Move to this position
self.reach_exit(m, n) # Determine whether to reach the terminal

(6) Set the movement in different directions in the player class

after , We also need to set the movement of players in four directions .

def go_up(self): # Move up

 if self.canmove(self.m - 1, self.n): # If it moves upward
self.setheading(90) # Set orientation
self.move(self.m - 1, self.n) # Set move up
def go_down(self): # Move down the
if self.canmove(self.m + 1, self.n): # If you can move down
self.setheading(270) # Set orientation
self.move(self.m + 1, self.n) # Set move down
def go_left(self): # Move to the left
if self.canmove(self.m, self.n - 1): # If you move to the left
self.setheading(180) # Set orientation
self.move(self.m, self.n - 1) # Set to move left
def go_right(self): # To the right
if self.canmove(self.m, self.n + 1): # If you move to the right
self.setheading(0) # Set orientation
self.move(self.m, self.n + 1) # Set to move right

(7) Set the judgment of the end point in the player class
When the player's horizontal and vertical coordinates are consistent with the end coordinate point , We decided that the game was over , And display the winning information on the screen , meanwhile , Restart the game .

def reach_exit(self, m, n): # Determine whether to reach the terminal , When the player reaches the end , Show ’you win!’

 if m == self.end_m and n == self.end_n: # If you move to the end
text = turtle.Turtle() # Create text object
text.hideturtle() # Hide the brush
text.penup() # Lift up the brush.
text.goto(0,0) # Move to origin
text.color('blue') # Set the color to blue
text.write('you win!',align="center",font = (' Microsoft YaHei ', 30)) # Writing “you win!”
time.sleep(2) # Two seconds later
text.clear() # Empty
self.restart() # Restart the game

(8) Set the restart mechanism in the player class

After reaching the end , We bring the player back to the original position again .

def restart(self): # Restart the game

 self.goto(-20, 120) # Move to (-20,120) Coordinate point
self.m = 0 # The number of lines at the starting point
self.n = 5 # The number of columns at the starting point
self.end_m = 12 # The number of lines at the end
self.end_n = 5 # The number of columns at the end

(9) Generate players

after , We generate a player character by instantiating a class .

player = Player(protract.maze_list, 0, 5, 12, 5) # Instantiation Player class , Create a player object

(10) Set the gyro flag value

In order to be able to pass x Axis and y The azimuth is determined by the acceleration value on the axis , We need to set a reference flag value for comparison in advance . here , After the above tasks 2 Read detection of , We choose “0.4” As a flag value .

thread_value = 0.4 # Define a flag value

(11) Cycle to read the acceleration value and detect it

Last , We use a permanent loop to continuously acquire the gyroscope x Axis and y The value of the axial acceleration , And compare it with the flag value , Then determine the direction of movement .

while True:

x = accelerometer.get_x() # obtain x Axis acceleration value
y = accelerometer.get_y() # obtain y Axis acceleration value
time.sleep(0.15)
if x > thread_value : # If x Axis acceleration value > threshold
player.go_down() # Move down the
time.sleep(0.1)
if x < -thread_value: # If x Axis acceleration value < threshold
player.go_up() # Move up
time.sleep(0.1)
if y > thread_value : # If y Axis acceleration value > threshold
player.go_left() # Move to the left
time.sleep(0.1)
if y < -thread_value : # If y Axis acceleration value < threshold
player.go_right() # To the right
time.sleep(0.1)

Tips: The complete sample program is as follows :

Slide up to read

import turtle # Import turtle library

import time # Import time library

import protract # Import protract modular

from pinpong.board import Board # Import pinpong.board In bag Board modular

from pinpong.extension.unihiker import * # Import pinpong.extension.unihiker All modules in the package

Board().begin() # initialization , Select board type and port number , If it is not entered, it will be recognized automatically

thread_value = 0.4 # Define a flag value

protract.Maze(protract.maze_list) # Instantiation Maze class , Create maze objects

class Player(turtle.Turtle): # Create a player class

def __init__(self, maze_list, start_m, start_n, end_m, end_n):
turtle.Turtle.__init__(self) # Parent class initialization
self.m = start_m # Set the number of lines at the starting point
self.n = start_n # Set the number of columns for the starting point
self.end_m = end_m # Set the number of lines at the end
self.end_n = end_n # Set the number of columns at the end
self.maze_list = maze_list # Set the maze list
self.hideturtle() # Hide turtle brush
self.speed(0) # Set turtle movement ( mapping ) The speed is the fastest
self.penup() # Lift up the brush.
self.goto(self.n * 20 - 120, 120 - self.m * 20) # The player moves to the corresponding position
self.shape('turtle') # Set the player form to turtle
self.color('yellow') # Set the player color to yellow
self.setheading(270) # Set the player's initial direction
self.showturtle() # Show players
def canmove(self, m, n): # Define where players can move , That is, it is only allowed to move in the channel in the maze
if 0 <= m and m <= 12: # If in the first place 0 Go to the first place 12 In line
print(m,n) # Print
return self.maze_list[m][n] == 0 # Return value 0, It means the first one m Xing di n There are no walls , Can be moved
def move(self, m, n): # Define the player's movement
self.m = m # Define the number of rows
self.n = n # Define the number of columns
self.goto(self.n * 20 - 120, 120 - self.m * 20) # Move to this position
self.reach_exit(m, n) # Determine whether to reach the terminal
def go_up(self): # Move up
if self.canmove(self.m - 1, self.n): # If it moves upward
self.setheading(90) # Set orientation
self.move(self.m - 1, self.n) # Set move up
def go_down(self): # Move down the
if self.canmove(self.m + 1, self.n): # If you can move down
self.setheading(270) # Set orientation
self.move(self.m + 1, self.n) # Set move down
def go_left(self): # Move to the left
if self.canmove(self.m, self.n - 1): # If you move to the left
self.setheading(180) # Set orientation
self.move(self.m, self.n - 1) # Set to move left
def go_right(self): # To the right
if self.canmove(self.m, self.n + 1): # If you move to the right
self.setheading(0) # Set orientation
self.move(self.m, self.n + 1) # Set to move right
def reach_exit(self, m, n): # Determine whether to reach the terminal , When the player reaches the end , Show 'you win!'
if m == self.end_m and n == self.end_n: # If you move to the end
text = turtle.Turtle() # Create text object
text.hideturtle() # Hide the brush
text.penup() # Lift up the brush.
text.goto(0,0) # Move to origin
text.color('blue') # Set the color to blue
text.write('you win!',align="center",font = (' Microsoft YaHei ', 30)) # Writing “you win!”
time.sleep(2) # Two seconds later
text.clear() # Empty
self.restart() # Restart the game
def restart(self): # Restart the game
self.goto(-20, 120) # Move to (-20,120) Coordinate point
self.m = 0 # The number of lines at the starting point
self.n = 5 # The number of columns at the starting point
self.end_m = 12 # The number of lines at the end
self.end_n = 5 # The number of columns at the end

player = Player(protract.maze_list, 0, 5, 12, 5) # Instantiation Player class , Create a player object

while True:

x = accelerometer.get_x() # obtain x Axis acceleration value
y = accelerometer.get_y() # obtain y Axis acceleration value
time.sleep(0.15)
if x > thread_value : # If x Axis acceleration value > threshold
player.go_down() # Move down the
time.sleep(0.1)
if x < -thread_value: # If x Axis acceleration value < threshold
player.go_up() # Move up
time.sleep(0.1)
if y > thread_value : # If y Axis acceleration value > threshold
player.go_left() # Move to the left
time.sleep(0.1)
if y < -thread_value : # If y Axis acceleration value < threshold
player.go_right() # To the right
time.sleep(0.1)

2、 The program runs

STEP1: Connecting boards

STEP2: Run the program and observe the effect

When I hit run , Observe the empty board , We found that a maze was drawn on the screen first , Then a little turtle appeared at the exit of the maze , After turning the maze, we can control the sea and air !

 Blank board screen operation effect
 Effect drawing of empty board operation

Challenge yourself

Try to replace... In the maze line list “0、1“, To design your own maze , Have a game !
More relevant blank boards Python For a series of introductory tutorials, please pay attention to “ Mushroom clouds create ”.

版权声明:本文为[Playful maker]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/134/202205141527526941.html