In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the Python turtle how to achieve ball Mini Game, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
1. Preface
Turtle (Little Turtle) is a built-in drawing module of Python. In fact, it can not only be used to draw, but also make simple Mini Game. It can even be used as a simple GUI module to write simple GUI procedures.
In this paper, the use of turtle module to write a simple Mini Game, through the process of writing this program to talk about the feelings of the turtle module.
To write a game, if you want to do something professional and interesting, please find pygame. The purpose of writing a game in turtle in this article is to deeply understand the functions of turtle.
The use of the turtle module is relatively simple and does not explain the basic methods. Only talk about the slightly difficult or neglected areas in the turtle module.
two。 Requirement description
When the program is running, there will be a red ball and many green and blue balls on the canvas.
At first, the red ball will move in a certain direction, and the user can control the movement direction of the red ball by pressing the up, down, left and right keys.
The green and blue balls move on the canvas in the initial default direction.
When the red ball touches the green ball, the red ball becomes bigger, and when the red ball touches the blue ball, the red ball becomes smaller.
When the red ball ball shrinks to a certain threshold, the game ends.
3. Production process 3.1 initialize variables
This procedure needs to use turtle, random, math module, before using, import first.
Import turtleimport randomimport math''' initializes the size of the game interface game_wid = 600 # the width of the game area game_hei = 400 # the size of the brick And the initial size of each ball cell = 2mm red ball initial size red_size = cell# red ball red_ball = None# store a list of green balls green_balls = [] # store a list of blue balls blue_balls = [] # the current direction of the red ball is 0 to the right, 90 upward 180 to the left-90 downward dir = 0
The above code states:
There is only one red ball, which is saved by the variable red_ball. The red ball can be resized during movement, and red_size saves its size.
There are many green and blue balls, here using green_balls and blue_balls 2 list storage.
3.2 Universal function
Random position calculation function: randomly generate the initial position for the balls.
Def rand_pos (): # there are 30 cells horizontally and 20 cells vertically x = random.randint (- 14,14) y = random.randint (- 9,9) return x * cell, y * cell
Draw a small square with a specified fill color: there is a virtual area in the game surrounded by many small squares.
To draw a square with a specified fill color, you can fill turtle.fillcolor (color) turtle.begin_fill () for i in range (4): turtle.fd (cell) turtle.left (90) if color is not None: turtle.end_fill () without specifying the color of''def draw_square (color): if color is not None:
Customize the brush shape:
The underlying idea of using turtle to make games:
When we import the turtle module, it means that we have a brush that can draw on the canvas, and the default shape of the brush is a baby turtle.
This article calls this default brush the master brush. You can use the turtle.Turtle () class in the turtle module to create more brushes, and you can use the turtle.register_shape (name, shape) `method provided by the ``turtle module to customize the brush shape for each brush.
As mentioned above, it is the key to designing games using turtle.
Emphasize:
Create more brushes with the main brush, and set a different shape for each brush. Is the key to writing the game, the essence of every character in the game is a brush, we are just controlling the brush to move on the canvas according to the track we designed.
In this game, the red, green and blue balls are round-shaped brushes.
Brush list:
A red ball paintbrush.
N green ball brushes.
N blue ball brushes.
'' Custom brush shape name: brush name color: optional''def custom_shape (name, size): turtle.begin_poly () turtle.penup () turtle.circle (size) turtle.end_poly () cs = turtle.get_poly () turtle.register_shape (name, cs)
Description of turtle.register_shape (name, shape) method parameters:
Name: the name of the custom shape.
Shape: shapes drawn by developers.
Which part of the graphics drawn by the developer is used as the shape of the brush?
The figure between the first point recorded by turtle.begin_poly () and the last point recorded by turtle.end_poly () is used as the brush shape.
Cs = turtle.get_poly () can be understood as getting the shape you just drew, and then registering the brush shape with turtle.register_shape (name, cs), which you can use at any time later.
The above code records the drawing process of a circle, that is, creating a circular brush shape.
Move to a location function:
This function is used to move a brush to a specified position without leaving a track during the move.
Def move_pos (pen, pos): pen.penup () pen.goto (pos) pen.pendown ()
Parameter description:
Pen: brush object.
Pos: the destination to move to.
Register the keyboard event function:
Users can change the direction of the red ball through the arrow keys on the keyboard.
The turtle module provides many events, and you can use turtle in an interactive way. There are mainly two kinds of events in the turtle module: keyboard events and click events. Because the focus of turtle is to draw static patterns, its animation drawing is relatively weak, so its events are few and simple.
Functions that change the 4 directions of the red ball, which can only be called after the user triggers the key, so these functions are also called callback functions. Def dir_right (): global dir dir = 0def dir_left (): global dir dir = 180def dir_up (): global dir dir = 90def dir_down (): global dir dir =-90''register keyboard response event Used to change the direction of the red ball: for key, f in {"Up": dir_up, "Down": dir_down, "Left": dir_left, "Right": dir_right} .items (): turtle.onkey (f, key) turtle.listen ()''when the red ball touches the wall Also modify the direction''def is_meet_qt (): global dir if red_ball.xcor ()
< -220: dir = 0 if red_ball.xcor() >240,240: dir = 180 if red_ball.ycor () > 140: dir =-90 if red_ball.ycor ()
< -120: dir = 90 红色的小球在 2 个时间点需要改变方向,一是使用者按下了方向键,一是碰到了墙体。 3.3 游戏角色函数 绘制墙体函数: 墙体是游戏中的虚拟区域,用来限制小球的活动范围。 Tips: 墙体由主画笔绘制。 '''绘制四面的墙体'''def draw_blocks(): # 隐藏画笔 turtle.hideturtle() # 上下各30个单元格,左右各 20 个单元格 for j in [30, 20, 30, 20]: for i in range(j): # 调用前面绘制正方形的函数 draw_square('gray') turtle.fd(cell) turtle.right(90) turtle.fd(-cell) # 回到原点 move_pos(turtle, (0, 0)) 创建小球画笔: 此函数用来创建新画笔。本程序中的红色、蓝色、绿色小球都是由此函数创建的画笔,且外观形状是圆。 def init_ball(pos, color, shape): # 由主画笔创建新画笔 ball = turtle.Turtle() ball.color(color) # 指定新画笔的形状,如果不指定,则为默认形状 ball.shape(shape) # 移到随机位置 move_pos(ball, pos) # 移动过程要不显示任何轨迹 ball.penup() return ball 参数说明: pos: 创建画笔后画笔移动的位置。 color:指定画笔和填充颜色。 shape: 已经定义好的画笔形状名称。 创建绿色、蓝色小球: def ran_gb_ball(balls, color): # 随机创建蓝色、绿色小球的频率, # 也就是说,不是调用此函数就一定会创建小球,概率大概是调用 5 次其中会有一次创建 ran = random.randint(1, 5) # 随机一个角度 a = random.randint(0, 360) # 1/5 的概率 if ran == 5: turtle.tracer(False) # 每一个小球就是一只画笔 ball = init_ball(rand_pos(), color, 'ball') ball.seth(a) # 添加到列表中 balls.append(ball) turtle.tracer(True) 为什么要设置一个概率值? 适当控制蓝色、绿色小球的数量。 turtle.tracer(False) 方法的作用:是否显示画笔绘制过程中的动画。False 关闭动画效果,True 打开动画效果。 这里设置为 False 的原因是不希望用户看到新画笔创建过程。 蓝色、绿色小球的移动函数: 蓝色、绿色小球被创建后会移到一个随机位置,然后按默认方向移动。 def gb_ball_m(balls): s = 20 a = random.randint(0, 360) r = random.randint(0, 10) for b in balls: b.fd(s) if b.xcor() < -220 or b.xcor() >240 or b.ycor () > 140 or b.ycor () <-120: b.goto (rand_pos ())
When the ball touches the wall, let it randomly move to the inside of the wall (simple and rough! ).
Whether the red ball touches a blue or green ball:
The logic of this function is not complicated. The coordinates between the balls are calculated to determine whether the coordinates overlap.
'' whether the red ball touches the green or blue ball''def r_g_b_meet (): global red_size # the coordinates of the red ball, scoffy = red_ball.pos () # iterative green ball Blue ball list for bs in [green_balls, blue_balls]: for b in bs: # calculate blue or green ball coordinates Fully = b.pos () # calculate the distance between the red ball and x _ = math.fabs (sphincx-faux) y _ = math.fabs (squary-favoy) # collision distance: the sum of the radii of the two balls h = cell + red_size if 0
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.