turtle is a drawing module built into Python. In fact, it can not only be used for drawing, but also for making simple mini-games. It can even be used as a simple GUI module to write Simple GUI program.
This article uses the turtle module to write a simple game. Through the writing process of this program, I will talk about my insights on the turtle module.
If you want to write a professional and interesting game, please look for pygame. The purpose of this article using turtle to write games is to deeply understand the functions of turtle.
The use of the turtle module is relatively simple, and the basic methods will not be explained. I will only talk about the slightly difficult or overlooked parts of the turtle module.
When the program is running, a red ball and many green and blue balls will appear on the canvas.
At first, the red ball will move in a certain direction. The user can control the movement direction of the red ball by pressing the up, down, left, and right direction 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 will become larger. When the red ball touches the blue ball, the red ball will become smaller.
When the red ball shrinks to a certain threshold, the game ends.
This program needs to use the turtle, random, and math modules. Before use, first Import.
import turtle import random import math ''' 初始化游戏界面大小 ''' # 游戏区域的宽度 game_wid = 600 # 游戏区域的高度 game_hei = 400 # 砖块的大小,以及每一个小球初始大小 cell = 20 # 红球初始大小 red_size = cell # 红色小球 red_ball = None # 存储绿色小球的列表 green_balls = [] # 存储蓝色小球的列表 blue_balls = [] # 红色小球的方向 当前方向 0 向右,90 向上 180 向左 -90 向下 dir = 0
Description of the above code:
There is only one red ball, which is saved by the variable red_ball
. The red ball can change its size during movement. , red_size
Save its size.
There will be many green and blue balls. Here we use 2 lists to store green_balls
and blue_balls
.
Random position calculation function: Randomly generates the initial position for the balls.
''' 随机位置计算函数 ''' def rand_pos(): # 水平有 30 个单元格,垂直有 20 个单元格 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.
''' 绘制一个指定填充颜色的正方形 填充颜色可以不指定 ''' def draw_square(color): if color is not None: # 的颜色就填充 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()
Custom brush shape:
The underlying idea of using turtle to make a game:
When we import the turtle
module , means that we have a brush that can draw on the canvas, and the default shape of the brush is a small turtle.
This article calls this default brush main brush, you can use the turtle.Turtle()
class in the turtle
module to create more brushes , and you can customize the brush shape for each brush using the turtle.register_shape(name, shape)` method provided by the ``turtle
module.
As mentioned above, is the key to using turtle
to design games.
Emphasis:
Create more brushes through the main brush, and set different shapes for each brush. It is the key to writing games. Every character in the game is essentially a paintbrush. We are just controlling the paintbrush to move on the canvas according to the trajectory we designed.
In this game, the three colors of red, green, and blue balls are round paintbrushes.
Brush list:
A red ball paintbrush.
N green ball paintbrushes.
N blue ball paintbrushes.
''' 自定义画笔形状 name:画笔名称 color:可选项 ''' 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)
turtle.register_shape(name, shape)
Method parameter description:
##name: The name of the custom shape .
shape: Shape drawn by the developer.
Which part of the graphics drawn by the developer is used as the brush shape?
The shape 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 newly drawn shape, and then using
turtle.register_shape(name, cs) to register the brush shape. You can use this shape anytime.
The above code records the drawing process of a circle, which creates a circular brush shape.
Move to a certain position function:
This function is used to move a certain brush to a specified position without leaving any trace during the movement. .''' 移到某点 ''' def move_pos(pen, pos): pen.penup() pen.goto(pos) pen.pendown()
Parameter description:
pen: Brush object.
#pos: The destination to move to.
Register keyboard event function:
Users can change the direction of the red ball through the direction keys on the keyboard.turtle
模块提供有很多事件,可以以交互式的方式使用turtle
。turtle
模块中主要有 2 类事件:键盘事件、点击事件。因 turtle
的工作重点还是绘制静态图案上,其动画绘制比较弱,所以它的事件少而简单。
''' 改变红色小球 4 方向的函数, 这些函数只有当使用者触发按键后方可调用,故这些函数也称为回调函数。 ''' def dir_right(): global dir dir = 0 def dir_left(): global dir dir = 180 def dir_up(): global dir dir = 90 def dir_down(): global dir dir = -90 ''' 注册键盘响应事件,用来改变红球的方向 ''' def register_event(): for key, f in {"Up": dir_up, "Down": dir_down, "Left": dir_left, "Right": dir_right}.items(): turtle.onkey(f, key) turtle.listen() ''' 当红色小球遇到墙体后,也要修改方向 ''' def is_meet_qt(): global dir if red_ball.xcor() < -220: dir = 0 if red_ball.xcor() > 240: dir = 180 if red_ball.ycor() > 140: dir = -90 if red_ball.ycor() < -120: dir = 90
红色的小球在 2 个时间点需要改变方向,一是使用者按下了方向键,一是碰到了墙体。
绘制墙体函数:
墙体是游戏中的虚拟区域,用来限制小球的活动范围。
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())
当小球碰到墙体后让其再随机移到墙体内部(简单粗粗暴!!)。
红色球是否碰到了蓝色或绿色小球:
此函数逻辑不复杂,计算小球相互之间的坐标,判断坐标是否重叠。
''' 红球是否碰到绿、蓝球 ''' def r_g_b_meet(): global red_size # 红色小球的坐标 s_x, s_y = red_ball.pos() # 迭代绿色小球,蓝色小球列表 for bs in [green_balls, blue_balls]: for b in bs: # 计算蓝色或绿色小球坐标 f_x, f_y = b.pos() # 计算和红色球之间的距离 x_ = math.fabs(s_x - f_x) y_ = math.fabs(s_y - f_y) # 碰撞距离:两个球的半径之和 h = cell + red_size if 0 <= x_ <= h and y_ >= 0 and y_ <= h: if b in green_balls: # 遇到绿色球红球变大 red_size += 2 if b in blue_balls: # 遇到蓝色球红球变大 red_size -= 2 # 关键代码 custom_shape('red', red_size) return True return False
上述代码整体逻辑不复杂。而 custom_shape('red', red_size)
是关键代码,因红色小球的半径发生了变化,所以需要重新定制红色小球的外观形状,这样才能在画布上看到半径变化的红色小球。
怎样让小球动起来?
每隔一定时间,让小球重新移动。 turtle.ontimer(ball_move, 100)
是让小球动起来的核心逻辑,每隔一定时间,重新移动红、蓝、绿外观如圆形状的小球。
def ball_move(): red_ball.seth(dir) red_ball.fd(40) # 检查红球是否碰到墙体 is_meet_qt() # 随机创建绿色小球 ran_gb_ball(green_balls, 'green') # 随机创建蓝色小球 ran_gb_ball(blue_balls, 'blue') # 让绿色小球移动 gb_ball_m(green_balls) # 让蓝色小球移动 gb_ball_m(blue_balls) # 检查红球是否碰到蓝色、绿色小球 r_g_b_meet() # 定时器 turtle.ontimer(ball_move, 100)
主方法:
if __name__ == "__main__": # 关闭动画效果 turtle.tracer(False) # 注册事件 register_event() # 定制 2 种画笔形状 for name in ['red', 'ball']: custom_shape(name, cell) # 主画笔移动墙体的左上角 move_pos(turtle, (-300, 200)) # 绘制墙体 draw_blocks() red_ball = init_ball(rand_pos(), 'red', 'red') turtle.tracer(True) # 让红球移动起来 ball_move() # turtle.done()
以上为此游戏程序中的每一个函数讲解。
运行后,可以控制红色小球,当遇到绿色球和蓝色球时,红色球体会变大或变小。
The above is the detailed content of How to implement ball games with turtle in Python. For more information, please follow other related articles on the PHP Chinese website!