python-pen 2.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
python_pen/core.py ADDED
@@ -0,0 +1,1630 @@
1
+ import os
2
+ import sys
3
+ import time
4
+ import math
5
+ import random
6
+ import turtle
7
+ import platform
8
+ import python_pen
9
+ sys.setrecursionlimit(3000)
10
+
11
+ class Pen:
12
+ def __init__(self, lang="ch", use_default_icon=True):
13
+ """
14
+ 初始化 PythonPen 画笔对象。
15
+ Initialize the PythonPen drawing object.
16
+ 参数 / Parameters:
17
+ lang (str): 语言设置,'ch' 为中文,'en' 为英文
18
+ Language setting, 'ch' for Chinese, 'en' for English
19
+ use_default_icon (bool): 是否使用内置铅笔图标
20
+ Whether to use the built-in pencil icon
21
+ 功能 / Features:
22
+ - 创建 Turtle 画笔 / Create Turtle pen
23
+ - 设置窗口图标(可选,默认启用) / Set window icon (optional, enabled by default)
24
+ - 初始化数学常量 / Initialize math constants
25
+ 示例 / Examples:
26
+ # 使用默认铅笔图标(推荐)
27
+ # Use the default pencil icon (recommended)
28
+ pen = Pen(lang="ch")
29
+ # 不使用任何图标
30
+ # Do not use any icon
31
+ pen = Pen(lang="ch", use_default_icon=False)
32
+ # 使用自定义图标
33
+ # Use a custom icon
34
+ pen = Pen(lang="ch", use_default_icon=False)
35
+ pen.set_icon(r"C:/path/to/my_icon.ico")
36
+ """
37
+ # 设置窗口标题
38
+ # Set window title
39
+ turtle.title("Python Pen")
40
+ self.t = turtle.Pen()
41
+ self.screen = turtle.Screen()
42
+ self._lang = lang
43
+ if use_default_icon:
44
+ base_dir = os.path.dirname(os.path.abspath(__file__))
45
+ icon_path = os.path.join(base_dir, "title_pic.ico")
46
+ self.set_icon(icon_path)
47
+ self.I = 1j
48
+ self.E = math.e
49
+ self.PI = math.pi
50
+ self.PHI = (1 + math.sqrt(5)) / 2
51
+ self.SQRT2 = math.sqrt(2)
52
+ def _reset_pen(self):
53
+ """
54
+ 重置画笔到标准绘图状态(内部使用)。
55
+ Reset pen to standard drawing state (internal use).
56
+
57
+ 注意:
58
+ - 抬笔、回原点、朝右
59
+ - 速度重置为 6,线宽重置为 1
60
+ - 不改变颜色、填充色、画笔形状
61
+ """
62
+
63
+ self.t.penup()
64
+ self.t.goto(0, 0)
65
+ self.t.setheading(0)
66
+ self.t.speed(6)
67
+ self.t.pensize(1)
68
+ def lang(self, code='ch'):
69
+ """
70
+ 切换运行时语言(不影响退出提示语言)。
71
+ Switch runtime language (does not affect exit prompt language).
72
+ 参数 / Parameters:
73
+ code (str): 语言代码,'ch' 为中文,'en' 为英文
74
+ Language code, 'ch' for Chinese, 'en' for English
75
+ 功能 / Function:
76
+ - 切换错误提示、help、绘图提示的语言
77
+ Switch language for errors, help, and drawing hints
78
+ 示例 / Example:
79
+ pen.lang('ch') # 切换到中文
80
+ pen.lang('en') # Switch to English
81
+ """
82
+ if code in ['ch', 'en']:
83
+ self._lang = code
84
+ else:
85
+ if self._lang == "ch":
86
+ print(f'❌ 不支持的语言: {code},只能用 "ch" 或 "en"')
87
+ print('📌 示例: pen.lang("ch") 或 pen.lang("en")')
88
+ else:
89
+ print(f'❌ Language not supported: {code}, only "ch" or "en"')
90
+ print('📌 Example: pen.lang("ch") or pen.lang("en")')
91
+ def bg(self, bg_color="white", bg_pic=None):
92
+ """
93
+ 设置画布背景颜色或背景图片。
94
+ Set canvas background color or background image.
95
+ 参数 / Parameters:
96
+ bg_color (str): 背景颜色,如 'white'、'black'、'#FF0000'
97
+ Background color, e.g. 'white', 'black', '#FF0000'
98
+ bg_pic (str): 背景图片路径,如 'bg.png'(可选)
99
+ Background image path, e.g. 'bg.png' (optional)
100
+ 功能 / Function:
101
+ - 设置背景颜色 / Set background color
102
+ - 加载背景图片 / Load background image
103
+ 示例 / Example:
104
+ pen.bg(bg_color='lightblue')
105
+ pen.bg(bg_color='black', bg_pic='stars.png')
106
+ """
107
+ if bg_pic is not None and not isinstance(bg_pic, str):
108
+ if self._lang == "ch":
109
+ print(f"背景图片路径必须是字符串类型,而不是 {type(bg_pic)}")
110
+ else:
111
+ print(f"❌ Background image path must be string, not {type(bg_pic)}")
112
+ return
113
+ turtle.bgcolor(bg_color)
114
+ if bg_pic:
115
+ turtle.bgpic(bg_pic)
116
+ def style(self, pen_shape="classic", pen_color="black", pen_speed=1,
117
+ pen_size=1, show_pen=True, down_pen=True,
118
+ fill_color=None, begin_fill=False, end_fill=False,
119
+ add_shape=None, shape_coords=None):
120
+ """
121
+ 统一设置画笔样式。
122
+ Unified pen style configuration.
123
+ 参数 / Parameters:
124
+ pen_shape (str): 画笔形状,如 'classic'、'turtle'、'circle'
125
+ Pen shape, e.g. 'classic', 'turtle', 'circle'
126
+ pen_color (str): 画笔颜色,如 'red'、'#FF0000'
127
+ Pen color, e.g. 'red', '#FF0000'
128
+ pen_speed (int): 绘制速度,范围 1~10,0 为最快
129
+ Drawing speed, range 1~10, 0=fastest
130
+ pen_size (int): 画笔粗细,如 1、3、5
131
+ Pen thickness, e.g. 1, 3, 5
132
+ show_pen (bool): 是否显示画笔,True 显示,False 隐藏
133
+ Whether to show the pen
134
+ down_pen (bool): 画笔是否落下,True 落下,False 抬起
135
+ Whether the pen is down
136
+ fill_color (str): 填充颜色,如 'blue'(可选)
137
+ Fill color, e.g. 'blue' (optional)
138
+ begin_fill (bool): 是否开始填充
139
+ Whether to begin filling
140
+ end_fill (bool): 是否结束填充
141
+ Whether to end filling
142
+ add_shape (str): 注册新形状的名称,如 'my_shape'
143
+ Name for registering a new shape
144
+ shape_coords (list): 形状坐标列表,如 [(0,0), (10,10)]
145
+ Coordinate list for custom shape
146
+ 功能 / Function:
147
+ - 一次性配置画笔外观与绘制状态
148
+ Configure pen appearance and drawing state at once
149
+ 示例 / Example:
150
+ pen.style(pen_color='red', pen_size=3, show_pen=False)
151
+ pen.style(pen_shape='turtle', pen_speed=10)
152
+ pen.style(fill_color='yellow', begin_fill=True)
153
+ """
154
+ self.t.shape(pen_shape)
155
+ self.t.pencolor(pen_color)
156
+ self.t.speed(pen_speed)
157
+ self.t.pensize(pen_size)
158
+ if show_pen:
159
+ self.t.showturtle()
160
+ else:
161
+ self.t.hideturtle()
162
+ if down_pen:
163
+ self.t.pendown()
164
+ else:
165
+ self.t.penup()
166
+ if fill_color:
167
+ self.t.fillcolor(fill_color)
168
+ if begin_fill:
169
+ self.t.begin_fill()
170
+ if end_fill:
171
+ self.t.end_fill()
172
+ if add_shape:
173
+ try:
174
+ if shape_coords:
175
+ turtle.addshape(add_shape, shape_coords)
176
+ if self._lang == "ch":
177
+ print(f"✅ 添加形状: {add_shape}")
178
+ else:
179
+ print(f"✅ Add shape: {add_shape}")
180
+ else:
181
+ turtle.addshape(add_shape)
182
+ if self._lang == "ch":
183
+ print(f"✅ 添加图片形状: {add_shape}")
184
+ else:
185
+ print(f"✅ Add image shape: {add_shape}")
186
+ except Exception as e:
187
+ if self._lang == "ch":
188
+ print(f"❌ 添加形状失败: {e}")
189
+ else:
190
+ print(f"❌ Adding shape failed: {e}")
191
+ def set_icon(self, icon_path):
192
+ """
193
+ 设置窗口图标(按操作系统自动适配)。
194
+ Set window icon (auto‑adapt per OS).
195
+ 功能 / Function:
196
+ - Windows 使用 .ico 图标
197
+ - macOS 优先使用 .icns,其次 .png
198
+ - Linux 使用 .png 图标
199
+ - 非支持系统自动跳过
200
+ 示例 / Example:
201
+ pen.set_icon("pen.ico") # Windows
202
+ pen.set_icon("pen.icns") # macOS
203
+ pen.set_icon("pen.png") # Linux / macOS
204
+ 注意 / Notes:
205
+ ⚠️ 图标路径必须是字符串
206
+ ⚠️ 文件必须真实存在
207
+ ⚠️ 不同系统对图标格式有不同要求
208
+ 如果设置失败,不会崩溃,只会打印提示。
209
+ If setting fails, it will not crash; only a warning is printed.
210
+ """
211
+ system = platform.system()
212
+ # ========= Windows =========
213
+ if system == "Windows":
214
+ if not isinstance(icon_path, str):
215
+ if self._lang == "ch":
216
+ print("❌ 图标路径必须是字符串")
217
+ else:
218
+ print("❌ Icon path must be a string")
219
+ return
220
+ if not icon_path.lower().endswith(".ico"):
221
+ if self._lang == "ch":
222
+ print("❌ Windows 要求图标为 .ico 格式")
223
+ else:
224
+ print("❌ Windows requires .ico icon format")
225
+ return
226
+ if not os.path.exists(icon_path):
227
+ if self._lang == "ch":
228
+ print(f"❌ 找不到图标文件:{icon_path}")
229
+ else:
230
+ print(f"❌ Icon file not found: {icon_path}")
231
+ return
232
+ try:
233
+ self.screen._root.iconbitmap(icon_path)
234
+ except Exception:
235
+ if self._lang == "ch":
236
+ print("⚠️ 设置图标失败")
237
+ else:
238
+ print("⚠️ Failed to set icon")
239
+ # ========= macOS =========
240
+ elif system == "Darwin":
241
+ if not isinstance(icon_path, str):
242
+ if self._lang == "ch":
243
+ print("❌ 图标路径必须是字符串")
244
+ else:
245
+ print("❌ Icon path must be a string")
246
+ return
247
+ # macOS 推荐 .icns,但也支持 .png
248
+ if not (icon_path.lower().endswith(".icns") or icon_path.lower().endswith(".png")):
249
+ if self._lang == "ch":
250
+ print("⚠️ macOS 建议使用 .icns 或 .png 图标")
251
+ else:
252
+ print("⚠️ macOS recommends .icns or .png icon format")
253
+ if not os.path.exists(icon_path):
254
+ if self._lang == "ch":
255
+ print(f"❌ 找不到图标文件:{icon_path}")
256
+ else:
257
+ print(f"❌ Icon file not found: {icon_path}")
258
+ return
259
+ try:
260
+ img = turtle.getscreen()._root.tk.call(
261
+ "image", "create", "photo", "-file", icon_path
262
+ )
263
+ turtle.getscreen()._root.iconphoto(True, img)
264
+ except Exception:
265
+ if self._lang == "ch":
266
+ print("⚠️ macOS 设置图标失败")
267
+ else:
268
+ print("⚠️ Failed to set icon on macOS")
269
+ # ========= Linux =========
270
+ elif system == "Linux":
271
+ if not isinstance(icon_path, str):
272
+ if self._lang == "ch":
273
+ print("❌ 图标路径必须是字符串")
274
+ else:
275
+ print("❌ Icon path must be a string")
276
+ return
277
+ if not icon_path.lower().endswith(".png"):
278
+ if self._lang == "ch":
279
+ print("⚠️ Linux 建议使用 .png 图标")
280
+ else:
281
+ print("⚠️ Linux recommends .png icon format")
282
+ if not os.path.exists(icon_path):
283
+ if self._lang == "ch":
284
+ print(f"❌ 找不到图标文件:{icon_path}")
285
+ else:
286
+ print(f"❌ Icon file not found: {icon_path}")
287
+ return
288
+ try:
289
+ img = turtle.getscreen()._root.tk.call(
290
+ "image", "create", "photo", "-file", icon_path
291
+ )
292
+ turtle.getscreen()._root.iconphoto(True, img)
293
+ except Exception:
294
+ if self._lang == "ch":
295
+ print("⚠️ Linux 设置图标失败")
296
+ else:
297
+ print("⚠️ Failed to set icon on Linux")
298
+ # ========= 其他系统 =========
299
+ else:
300
+ if self._lang == "ch":
301
+ print("⚠️ 当前系统不支持设置窗口图标")
302
+ else:
303
+ print("⚠️ Current OS does not support setting window icon")
304
+ def pen_forward(self, distance):
305
+ """
306
+ 让画笔向前移动指定距离。
307
+ Move the pen forward by a given distance.
308
+ 参数 / Parameters:
309
+ distance (int/float): 移动距离,如 '100'、'50.5'
310
+ Moving distance, e.g. '100', '50.5'
311
+ 功能 / Function:
312
+ - 沿当前朝向向前画线
313
+ Draw a line forward in the current heading
314
+ 示例 / Example:
315
+ pen.pen_forward(100)
316
+ pen.pen_forward(75.5)
317
+ """
318
+ self.t.forward(distance)
319
+ def pen_backward(self, distance):
320
+ """
321
+ 让画笔向后移动指定距离。
322
+ Move the pen backward by a given distance.
323
+ 参数 / Parameters:
324
+ distance (int/float): 移动距离,如 '100'、'50.5'
325
+ Moving distance, e.g. '100', '50.5'
326
+ 功能 / Function:
327
+ - 沿当前朝向反方向画线
328
+ Draw a line backward from the current heading
329
+ 示例 / Example:
330
+ pen.pen_backward(100)
331
+ """
332
+ self.t.backward(distance)
333
+ def pen_left(self, angle):
334
+ """
335
+ 让画笔向左(逆时针)旋转指定角度。
336
+ Turn the pen left (counterclockwise) by a given angle.
337
+ 参数 / Parameters:
338
+ angle (int/float): 旋转角度,如 '90'、'45.5'
339
+ Turning angle, e.g. '90', '45.5'
340
+ 功能 / Function:
341
+ - 逆时针改变画笔朝向
342
+ Change pen heading counterclockwise
343
+ 示例 / Example:
344
+ pen.pen_left(90)
345
+ """
346
+ self.t.left(angle)
347
+ def pen_right(self, angle):
348
+ """
349
+ 让画笔向右(顺时针)旋转指定角度。
350
+ Turn the pen right (clockwise) by a given angle.
351
+ 参数 / Parameters:
352
+ angle (int/float): 旋转角度,如 '90'、'45.5'
353
+ Turning angle, e.g. '90', '45.5'
354
+ 功能 / Function:
355
+ - 顺时针改变画笔朝向
356
+ Change pen heading clockwise
357
+ 示例 / Example:
358
+ pen.pen_right(90)
359
+ """
360
+ self.t.right(angle)
361
+ def pen_goto(self, x, y):
362
+ """
363
+ 将画笔移动到指定坐标,不更改朝向。
364
+ Move the pen to a given coordinate without changing heading.
365
+ 参数 / Parameters:
366
+ x (int/float): 横坐标,如 '0'、'-100'
367
+ X coordinate, e.g. '0', '-100'
368
+ y (int/float): 纵坐标,如 '0'、'150'
369
+ Y coordinate, e.g. '0', '150'
370
+ 功能 / Function:
371
+ - 移动到 (x, y),路径是否画线取决于画笔状态
372
+ Move to (x, y); whether a line is drawn depends on pen state
373
+ 示例 / Example:
374
+ pen.pen_goto(100, 50)
375
+ pen.pen_goto(-50, -80)
376
+ """
377
+ self.t.goto(x, y)
378
+ def pen_home(self):
379
+ """
380
+ 将画笔移回原点 (0,0),并将朝向重置为 0 度(向右)。
381
+ Move the pen to the origin (0,0) and reset heading to 0° (facing right).
382
+ 功能 / Function:
383
+ - 回到原点,朝向归正
384
+ Return to origin and reset heading
385
+ 示例 / Example:
386
+ pen.pen_home()
387
+ """
388
+ self.t.home()
389
+ def pen_setheading(self, to_angle):
390
+ """
391
+ 设置画笔的朝向角度。
392
+ Set the pen's absolute heading angle.
393
+ 参数 / Parameters:
394
+ to_angle (int/float): 目标角度,如 '0'(右)、'90'(上)、'180'(左)
395
+ Target angle, e.g. '0' (right), '90' (up), '180' (left)
396
+ 功能 / Function:
397
+ - 设置绝对朝向(0 度为向右,逆时针增加)
398
+ Set absolute heading (0° = right, increases counterclockwise)
399
+ 示例 / Example:
400
+ pen.pen_setheading(90)
401
+ pen.pen_setheading(180)
402
+ """
403
+ self.t.setheading(to_angle)
404
+ def pen_clear(self):
405
+ """
406
+ 清空画布上的所有绘图,但保留画笔状态。
407
+ Clear all drawings on the canvas while keeping pen state.
408
+ 功能 / Function:
409
+ - 清除图形,不重置位置、颜色、速度等属性
410
+ Erase drawings without resetting position, color, speed, etc.
411
+ 示例 / Example:
412
+ pen.pen_clear()
413
+ """
414
+ self.t.clear()
415
+ def pen_reset(self, keep_shape=False, keep_bg=False):
416
+ """
417
+ 重置画布与画笔状态。
418
+ Reset the canvas and pen state.
419
+ 参数 / Parameters:
420
+ keep_shape (bool): 是否保留画笔形状,如 'True'、'False'
421
+ Whether to keep the pen shape
422
+ keep_bg (bool): 是否保留背景颜色或图片,如 'True'、'False'
423
+ Whether to keep background color or image
424
+ 功能 / Function:
425
+ - 清空画布并恢复画笔到初始状态
426
+ Clear canvas and restore pen to initial state
427
+ - 可选保留形状、背景
428
+ Optionally keep shape and background
429
+ 示例 / Example:
430
+ pen.pen_reset()
431
+ pen.pen_reset(keep_shape=True, keep_bg=True)
432
+ """
433
+ current_shape = None
434
+ current_bgcolor = None
435
+ current_bgpic = None
436
+ if keep_shape:
437
+ current_shape = self.t.shape()
438
+ if keep_bg:
439
+ current_bgcolor = turtle.bgcolor()
440
+ current_bgpic = turtle.bgpic()
441
+ self.t.clear()
442
+ self.t.penup()
443
+ self.t.goto(0, 0)
444
+ self.t.setheading(0)
445
+ self.t.pendown()
446
+ self.t.pencolor("black")
447
+ self.t.pensize(1)
448
+ self.t.speed(1)
449
+ self.t.fillcolor("")
450
+ if keep_shape:
451
+ self.t.shape(current_shape)
452
+ else:
453
+ self.t.shape("classic")
454
+ if not keep_bg:
455
+ turtle.bgcolor("white")
456
+ turtle.bgpic(None)
457
+ else:
458
+ turtle.bgcolor(current_bgcolor)
459
+ if current_bgpic:
460
+ turtle.bgpic(current_bgpic)
461
+ def pen_pos(self):
462
+ """
463
+ 获取画笔当前坐标。
464
+ Get the current position of the pen.
465
+ 返回 / Returns:
466
+ (float, float): 当前坐标 (x, y)
467
+ Current coordinate (x, y)
468
+ 功能 / Function:
469
+ - 查询画笔位置
470
+ Query pen position
471
+ 示例 / Example:
472
+ x, y = pen.pen_pos()
473
+ print(x, y)
474
+ """
475
+ return self.t.pos()
476
+ def pen_save_state(self):
477
+ """
478
+ 保存当前画笔的完整状态。
479
+ Save the complete current state of the pen.
480
+ 返回 / Returns:
481
+ dict: 包含位置、速度、朝向、颜色、画笔状态等的字典
482
+ Dictionary containing position, speed, heading, colors, pen state, etc.
483
+ 功能 / Function:
484
+ - 记录画笔当前状态,便于后续恢复
485
+ Record current pen state for later restoration
486
+ 示例 / Example:
487
+ state = pen.pen_save_state()
488
+ """
489
+ return {
490
+ 'pos': self.t.pos(),
491
+ 'speed': self.t.speed(),
492
+ 'heading': self.t.heading(),
493
+ 'color': self.t.pencolor(),
494
+ 'fillcolor': self.t.fillcolor(),
495
+ 'pensize': self.t.pensize(),
496
+ 'isdown': self.t.isdown()
497
+ }
498
+ def pen_restore_state(self, state):
499
+ """
500
+ 恢复之前保存的画笔状态。
501
+ Restore a previously saved pen state.
502
+ 参数 / Parameters:
503
+ state (dict): pen_save_state() 返回的字典
504
+ Dictionary returned by pen_save_state()
505
+ 功能 / Function:
506
+ - 将画笔恢复到保存时的状态
507
+ Restore pen to its saved state
508
+ 示例 / Example:
509
+ pen.pen_restore_state(state)
510
+ """
511
+ if state is None:
512
+ return
513
+
514
+ def safe_color(c):
515
+ if c is None or c == "":
516
+ return c
517
+ return c
518
+
519
+ t = self.t
520
+ t.penup()
521
+ t.goto(state['pos'])
522
+ t.setheading(state['heading'])
523
+ t.speed(state['speed'])
524
+ t.pensize(state['pensize'])
525
+ t.pencolor(safe_color(state['color']))
526
+ t.fillcolor(safe_color(state['fillcolor']))
527
+
528
+ if state['isdown']:
529
+ t.pendown()
530
+ else:
531
+ t.penup()
532
+
533
+ def pen_tracer(self, on=True):
534
+ """
535
+ 开启或关闭动画效果。
536
+ Turn animation on or off.
537
+ 参数 / Parameters:
538
+ on (bool): 是否开启动画,'True' 开启,'False' 关闭
539
+ Whether to enable animation
540
+ 功能 / Function:
541
+ - 关闭动画可大幅提升复杂图形的绘制速度
542
+ Disabling animation greatly improves drawing speed for complex graphics
543
+ 示例 / Example:
544
+ pen.pen_tracer(False) # 关闭动画
545
+ pen.pen_tracer(True) # 开启动画
546
+ """
547
+ turtle.tracer(on)
548
+ def pen_update(self):
549
+ """
550
+ 手动刷新画布,配合 pen_tracer(False) 使用。
551
+ Manually update the canvas, used together with pen_tracer(False).
552
+ 功能 / Function:
553
+ - 在关闭动画后,强制刷新画面
554
+ Force‑refresh the canvas after animation is disabled
555
+ 示例 / Example:
556
+ pen.pen_tracer(False)
557
+ pen.draw_circle(100)
558
+ pen.pen_update()
559
+ """
560
+ turtle.update()
561
+ def pen_write(self, text, align="center", font=("Arial", 12, "normal")):
562
+ """
563
+ 在画笔当前位置书写文字。
564
+ Write text at the pen's current position.
565
+ 参数 / Parameters:
566
+ text (str): 要书写的文字,如 'Hello PythonPen'
567
+ Text to write
568
+ align (str): 对齐方式,如 'left'、'center'、'right'
569
+ Alignment mode
570
+ font (tuple): 字体设置,如 ('Arial', 12, 'normal')
571
+ Font configuration
572
+ 功能 / Function:
573
+ - 在当前位置输出文字
574
+ Render text at the current position
575
+ 示例 / Example:
576
+ pen.pen_write("Hello", align="center", font=("Arial", 16, "bold"))
577
+ """
578
+ self.t.write(text, align=align, font=font)
579
+ def pen_stamp(self):
580
+ """
581
+ 在当前位置盖一个“印章”(画笔形状的拷贝)。
582
+ Stamp a copy of the pen shape at the current position.
583
+ 返回 / Returns:
584
+ int: 印章的唯一 ID,可用于后续清除
585
+ Unique stamp ID for later removal
586
+ 功能 / Function:
587
+ - 在画布上留下画笔形状的印记
588
+ Leave a permanent impression of the pen shape
589
+ 示例 / Example:
590
+ stamp_id = pen.pen_stamp()
591
+ """
592
+ return self.t.stamp()
593
+ def pen_clear_stamp(self, stamp_id=None):
594
+ """
595
+ 清除印章。
596
+ Clear stamps.
597
+ 参数 / Parameters:
598
+ stamp_id (int): 指定要清除的印章 ID(由 pen_stamp() 返回)
599
+ Specific stamp ID returned by pen_stamp()
600
+ None 表示清除所有印章
601
+ None means clear all stamps
602
+ 功能 / Function:
603
+ - 清除指定印章或全部印章
604
+ Remove a specific stamp or all stamps
605
+ 示例 / Example:
606
+ stamp_id = pen.pen_stamp()
607
+ pen.pen_clear_stamp(stamp_id)
608
+ pen.pen_clear_stamp() # 清除全部
609
+ """
610
+ if stamp_id is None:
611
+ self.t.clearstamps()
612
+ else:
613
+ self.t.clearstamp(stamp_id)
614
+ def pen_num_input(self, title, prompt, default=None, minval=None, maxval=None):
615
+ """
616
+ 弹出数值输入对话框,获取用户输入的数字。
617
+ Pop up a number input dialog and get a numeric input.
618
+ 参数 / Parameters:
619
+ title (str): 对话框标题,如 '输入半径'
620
+ Dialog title
621
+ prompt (str): 提示文字,如 '请输入圆的半径'
622
+ Prompt text
623
+ default (float): 默认值,如 '50.0'
624
+ Default value
625
+ minval (float): 最小值,如 '10.0'
626
+ Minimum allowed value
627
+ maxval (float): 最大值,如 '200.0'
628
+ Maximum allowed value
629
+ 返回 / Returns:
630
+ float: 用户输入的数值
631
+ Number entered by the user
632
+ 示例 / Example:
633
+ r = pen.pen_num_input("输入半径", "请输入圆的半径:", 50, 10, 200)
634
+ """
635
+ result = turtle.numinput(title, prompt, default, minval, maxval)
636
+ if result is None:
637
+ if self._lang == "ch":
638
+ print("ℹ️ 用户取消了输入")
639
+ else:
640
+ print("ℹ️ User cancelled input")
641
+ return result
642
+ def pen_text_input(self, title, prompt):
643
+ """
644
+ 弹出文本输入对话框,获取用户输入的字符串。
645
+ Pop up a text input dialog and get a text input.
646
+ 参数 / Parameters:
647
+ title (str): 对话框标题,如 '输入名字'
648
+ Dialog title
649
+ prompt (str): 提示文字,如 '请输入你的名字'
650
+ Prompt text
651
+ 返回 / Returns:
652
+ str: 用户输入的文本;若取消则返回 None
653
+ Text entered by the user; None if cancelled
654
+ 示例 / Example:
655
+ name = pen.pen_text_input("名字", "请输入你的名字:")
656
+ """
657
+ return turtle.textinput(title, prompt)
658
+ def pen_set_title(self, title):
659
+ """
660
+ 设置 Turtle 窗口的标题。
661
+ Set the Turtle window title.
662
+ 参数 / Parameters:
663
+ title (str): 窗口标题,如 '我的绘图作品'
664
+ Window title
665
+ 功能 / Function:
666
+ - 修改窗口顶部显示的文字
667
+ Change the text shown at the top of the window
668
+ 示例 / Example:
669
+ pen.pen_set_title("PythonPen 绘图")
670
+ """
671
+ turtle.title(title)
672
+ def pen_delay(self, seconds):
673
+ """
674
+ 让程序暂停(休眠)指定时间。
675
+ Pause (sleep) the program for a given time.
676
+ 参数 / Parameters:
677
+ seconds (int/float): 暂停时间(秒),如 '1'、'0.5'
678
+ Pause duration in seconds
679
+ 功能 / Function:
680
+ - 常用于控制动画节奏或观察绘制过程
681
+ Often used to control animation timing or observe drawing
682
+ 示例 / Example:
683
+ pen.pen_delay(1)
684
+ pen.pen_delay(0.5)
685
+ """
686
+ time.sleep(seconds)
687
+ def show_detailed_time(self):
688
+ """
689
+ 在控制台打印当前详细时间信息。
690
+ Print detailed current time information to the console.
691
+ 功能 / Function:
692
+ - 显示年月日、时分秒、星期、年度第几天
693
+ Show year, month, day, time, weekday, and day of year
694
+ 示例 / Example:
695
+ pen.show_detailed_time()
696
+ """
697
+ t = time.localtime()
698
+ if self._lang == "ch":
699
+ print(time.strftime("📅 %Y年%m月%d日 %H:%M:%S\n星期:%w 年度第%j天", t))
700
+ else:
701
+ print(time.strftime("📅 %Y‑%m‑%d %H:%M:%S\nWeek:%w Day:%j", t))
702
+ def set_color_mode(self, mode=255):
703
+ """
704
+ 设置 Turtle 的颜色模式。
705
+ Set Turtle color mode.
706
+ 参数 / Parameters:
707
+ mode (int/float): 颜色模式,'255' 或 '1.0'
708
+ Color mode, '255' or '1.0'
709
+ 功能 / Function:
710
+ - 切换 RGB 取值范围
711
+ Switch RGB value range
712
+ 示例 / Example:
713
+ pen.set_color_mode(255)
714
+ pen.set_color_mode(1.0)
715
+ """
716
+ if mode in [255, 1.0]:
717
+ turtle.colormode(mode)
718
+ else:
719
+ if self._lang == "ch":
720
+ print("错误: 颜色模式必须是 255 或 1.0")
721
+ else:
722
+ print("Error: Color mode must be 255 or 1.0")
723
+ def get_color_mode(self):
724
+ """
725
+ 获取当前颜色模式。
726
+ Get the current color mode.
727
+ 返回 / Returns:
728
+ int/float: 当前颜色模式,'255' 或 '1.0'
729
+ 功能 / Function:
730
+ - 查询当前 RGB 取值范围
731
+ Query current RGB value range
732
+ 示例 / Example:
733
+ mode = pen.get_color_mode()
734
+ """
735
+ try:
736
+ self.t.pencolor(255, 0, 0)
737
+ return 255
738
+ except turtle.TurtleGraphicsError:
739
+ return 1.0
740
+
741
+ def random_color(self, color_type="all"):
742
+ """
743
+ 随机返回一个颜色名称。
744
+ Return a random color name.
745
+ 参数 / Parameters:
746
+ color_type (str): 颜色分组,如 'all'、'dark'、'light'、'bright'、'pastel'
747
+ 返回 / Returns:
748
+ str: 颜色名称,如 'red'
749
+ 功能 / Function:
750
+ - 从指定颜色组中随机取色
751
+ Pick a random color from the specified group
752
+ 示例 / Example:
753
+ pen.random_color()
754
+ pen.random_color('dark')
755
+ """
756
+ color_groups = {
757
+ "all": [
758
+ "red", "green", "blue", "yellow", "orange", "purple", "pink", "brown",
759
+ "black", "white", "gray", "grey",
760
+ "crimson", "maroon", "darkred", "firebrick", "indianred", "lightcoral",
761
+ "salmon", "darksalmon", "lightsalmon", "tomato", "orangered",
762
+ "lime", "forestgreen", "seagreen", "mediumseagreen", "springgreen",
763
+ "mediumspringgreen", "palegreen", "lightgreen", "darkgreen", "greenyellow",
764
+ "chartreuse", "lawngreen", "limegreen",
765
+ "cyan", "aqua", "lightcyan", "paleturquoise", "aquamarine", "turquoise",
766
+ "mediumturquoise", "darkturquoise", "cadetblue", "steelblue", "lightsteelblue",
767
+ "powderblue", "lightblue", "skyblue", "lightskyblue", "deepskyblue",
768
+ "dodgerblue", "cornflowerblue", "mediumslateblue", "royalblue", "navy",
769
+ "darkblue", "mediumblue", "midnightblue",
770
+ "gold", "lightyellow", "lemonchiffon", "lightgoldenrodyellow", "papayawhip",
771
+ "moccasin", "peachpuff", "palegoldenrod", "khaki", "darkkhaki",
772
+ "coral", "darkorange", "lightsalmon",
773
+ "lavender", "thistle", "plum", "violet", "orchid", "fuchsia", "magenta",
774
+ "mediumorchid", "mediumpurple", "blueviolet", "darkviolet", "darkorchid",
775
+ "darkmagenta", "purple", "indigo",
776
+ "pink", "lightpink", "hotpink", "deeppink", "palevioletred", "mediumvioletred",
777
+ "brown", "saddlebrown", "sienna", "chocolate", "peru", "sandybrown",
778
+ "burlywood", "tan", "rosybrown", "wheat",
779
+ "white", "snow", "honeydew", "mintcream", "azure", "aliceblue", "ghostwhite",
780
+ "whitesmoke", "seashell", "beige", "oldlace", "floralwhite", "ivory",
781
+ "antiquewhite", "linen", "lavenderblush", "mistyrose", "gainsboro",
782
+ "lightgray", "silver", "darkgray", "dimgray", "lightslategray", "slategray",
783
+ "darkslategray",
784
+ "goldenrod", "darkgoldenrod", "olive", "olivedrab", "yellowgreen",
785
+ "darkolivegreen", "mediumaquamarine", "darkseagreen", "lightseagreen",
786
+ "darkcyan", "teal"
787
+ ],
788
+ "dark": [
789
+ "red", "green", "blue", "yellow", "orange", "purple", "pink", "brown", "black",
790
+ "crimson", "maroon", "darkred", "firebrick", "orangered",
791
+ "forestgreen", "seagreen", "darkgreen", "limegreen",
792
+ "navy", "darkblue", "mediumblue", "midnightblue", "royalblue",
793
+ "darkorange", "gold", "coral",
794
+ "darkviolet", "darkmagenta", "purple", "indigo",
795
+ "deeppink", "mediumvioletred",
796
+ "brown", "saddlebrown", "sienna", "chocolate",
797
+ "darkgoldenrod", "olive", "darkolivegreen", "darkcyan", "teal"
798
+ ],
799
+ "light": [
800
+ "white", "lightcoral", "lightsalmon", "palegreen", "lightgreen",
801
+ "lightcyan", "paleturquoise", "aquamarine", "lightblue", "skyblue",
802
+ "lightskyblue", "lightyellow", "lemonchiffon", "lavender", "thistle",
803
+ "lightpink", "pink", "wheat", "beige", "peachpuff", "moccasin",
804
+ "papayawhip", "mistyrose", "lavenderblush", "aliceblue", "mintcream"
805
+ ],
806
+ "bright": [
807
+ "red", "lime", "blue", "yellow", "orange", "purple", "pink",
808
+ "cyan", "aqua", "springgreen", "chartreuse", "lawngreen",
809
+ "dodgerblue", "fuchsia", "magenta", "hotpink", "deeppink",
810
+ "gold", "coral", "tomato", "orangered", "greenyellow"
811
+ ],
812
+ "pastel": [
813
+ "lightcoral", "lightsalmon", "palegreen", "lightcyan",
814
+ "paleturquoise", "lightblue", "skyblue", "lightyellow",
815
+ "lavender", "thistle", "lightpink", "wheat", "beige",
816
+ "peachpuff", "moccasin", "papayawhip", "mistyrose"
817
+ ],
818
+ }
819
+ if color_type not in color_groups:
820
+ color_type = "all"
821
+ colors = color_groups[color_type]
822
+ return random.choice(colors)
823
+ def random_int(self, min_val, max_val):
824
+ """
825
+ 生成一个指定范围内的随机整数。
826
+ Generate a random integer within a given range.
827
+ 参数 / Parameters:
828
+ min_val (int): 最小值,如 '1'
829
+ max_val (int): 最大值,如 '10'
830
+ 返回 / Returns:
831
+ int: 随机整数
832
+ 示例 / Example:
833
+ num = pen.random_int(1, 10)
834
+ """
835
+ return random.randint(min_val, max_val)
836
+ def random_float(self, min_val, max_val, digit=2):
837
+ """
838
+ 生成一个指定范围内的随机浮点数。
839
+ Generate a random float within a given range.
840
+ 参数 / Parameters:
841
+ min_val (float): 最小值,如 '0.0'
842
+ max_val (float): 最大值,如 '1.0'
843
+ digit (int): 小数位数,如 '2'
844
+ 返回 / Returns:
845
+ float: 随机浮点数
846
+ 示例 / Example:
847
+ val = pen.random_float(0.0, 1.0, 3)
848
+ """
849
+ return round(random.uniform(min_val, max_val), digit)
850
+ def random_choice(self, seq, n=1):
851
+ """
852
+ 从序列中随机选择元素。
853
+ Randomly choose elements from a sequence.
854
+ 参数 / Parameters:
855
+ seq (list/tuple/str): 输入序列,如 [1,2,3]、'abc'
856
+ n (int): 选择数量,如 '1'
857
+ 返回 / Returns:
858
+ list: 随机选择的结果列表
859
+ 示例 / Example:
860
+ items = pen.random_choice([1,2,3,4], 2)
861
+ """
862
+ return [random.choice(seq) for _ in range(n)]
863
+ def random_shuffled(self, seq):
864
+ """
865
+ 随机打乱序列(原地打乱)。
866
+ Randomly shuffle a sequence in place.
867
+ 参数 / Parameters:
868
+ seq (list): 要打乱的列表,如 [1,2,3,4]
869
+ List to shuffle
870
+ 返回 / Returns:
871
+ list: 打乱后的列表
872
+ Shuffled list
873
+ 示例 / Example:
874
+ items = pen.random_shuffle([1,2,3,4])
875
+ 注意 / Note:
876
+ ⚠️ 本方法返回新列表,不修改原序列。
877
+ 标准库 random.shuffle() 为原地修改并返回 None。
878
+ This method returns a new list and does not modify the original sequence.
879
+ The standard library random.shuffle() shuffles in place and returns None.
880
+ """
881
+ temp = list(seq)
882
+ random.shuffle(temp)
883
+ return temp
884
+ def screen_exitonclick(self):
885
+ """
886
+ 点击窗口后退出程序。
887
+ Exit the program when the screen is clicked.
888
+ 功能 / Function:
889
+ - 等待用户点击画布,然后关闭窗口并退出
890
+ Wait for a click on the canvas, then close the window and exit
891
+ 示例 / Example:
892
+ pen.screen_exitonclick()
893
+ """
894
+ turtle.exitonclick()
895
+ def screen_mainloop(self):
896
+ """
897
+ 进入主循环,保持窗口打开。
898
+ Enter the main loop and keep the window open.
899
+ 功能 / Function:
900
+ - 程序运行结束后,窗口不会自动关闭
901
+ Keep the window open after the program ends
902
+ 示例 / Example:
903
+ pen.screen_mainloop()
904
+ """
905
+ turtle.mainloop()
906
+ def screen_bye(self):
907
+ """
908
+ 礼貌地关闭 Turtle 窗口。
909
+ Politely close the Turtle window.
910
+ 功能 / Function:
911
+ - 执行清理并关闭绘图窗口
912
+ Perform cleanup and close the drawing window
913
+ 示例 / Example:
914
+ pen.screen_bye()
915
+ """
916
+ turtle.bye()
917
+ def draw_circle(self, radius, angle=360, start_pos=None, color="black", fill=False):
918
+ """
919
+ 绘制圆形或圆弧。
920
+ Draw a circle or arc.
921
+ 参数 / Parameters:
922
+ radius (int/float): 半径,如 '100'
923
+ angle (int): 角度,'360' 为整圆,'180' 为半圆
924
+ start_pos (tuple): 起始坐标 (x, y),可选
925
+ color (str): 颜色,如 'red'
926
+ fill (bool): 是否填充
927
+ 示例 / Example:
928
+ pen.draw_circle(100)
929
+ pen.draw_circle(80, angle=180, fill=True)
930
+ """
931
+ state = self.pen_save_state()
932
+ self._reset_pen()
933
+ self.t.penup()
934
+ if start_pos:
935
+ self.t.goto(start_pos)
936
+ self.t.pendown()
937
+ self.t.pencolor(color)
938
+ if fill:
939
+ self.t.fillcolor(color)
940
+ self.t.begin_fill()
941
+ self.t.circle(radius, angle)
942
+ if fill:
943
+ self.t.end_fill()
944
+ self.pen_restore_state(state)
945
+ def draw_square(self, side_length, start_pos=None, color="black", fill=False):
946
+ """
947
+ 绘制正方形。
948
+ Draw a square.
949
+ 参数 / Parameters:
950
+ side_length (int/float): 边长,如 '100'
951
+ start_pos (tuple): 起始坐标 (x, y),可选
952
+ color (str): 颜色,如 'blue'
953
+ fill (bool): 是否填充
954
+ 示例 / Example:
955
+ pen.draw_square(100)
956
+ pen.draw_square(80, fill=True)
957
+ """
958
+ self.draw_rectangle(side_length, side_length, start_pos, color, fill)
959
+ def draw_rectangle(self, length, width, start_pos=None, color="black", fill=False):
960
+ """
961
+ 绘制长方形。
962
+ Draw a rectangle.
963
+ 参数 / Parameters:
964
+ length (int/float): 长,如 '200'
965
+ width (int/float): 宽,如 '100'
966
+ start_pos (tuple): 起始坐标 (x, y),可选
967
+ color (str): 颜色,如 'blue'
968
+ fill (bool): 是否填充
969
+ 示例 / Example:
970
+ pen.draw_rectangle(200, 100)
971
+ pen.draw_rectangle(120, 80, fill=True, color='orange')
972
+ """
973
+ state = self.pen_save_state()
974
+ self._reset_pen()
975
+ self.t.penup()
976
+ if start_pos:
977
+ self.t.goto(start_pos)
978
+ self.t.pendown()
979
+ self.t.pencolor(color)
980
+ if fill:
981
+ self.t.fillcolor(color)
982
+ self.t.begin_fill()
983
+ for _ in range(2):
984
+ self.t.forward(length)
985
+ self.t.right(90)
986
+ self.t.forward(width)
987
+ self.t.right(90)
988
+ if fill:
989
+ self.t.end_fill()
990
+ self.pen_restore_state(state)
991
+ def draw_equilateral_triangle(self, side_length, start_pos=None, color="black", fill=False):
992
+ """
993
+ 绘制等边三角形。
994
+ Draw an equilateral triangle.
995
+ 参数 / Parameters:
996
+ side_length (int/float): 边长,如 '100'
997
+ start_pos (tuple): 起始坐标 (x, y),可选
998
+ color (str): 颜色,如 'green'
999
+ fill (bool): 是否填充
1000
+ 示例 / Example:
1001
+ pen.draw_equilateral_triangle(100)
1002
+ pen.draw_equilateral_triangle(80, fill=True)
1003
+ """
1004
+ self.draw_polygon(3, side_length, start_pos, color, fill)
1005
+ def draw_isosceles_triangle(self, legs, base, start_pos=None, color="black", fill=False):
1006
+ """
1007
+ 绘制等腰三角形。
1008
+ Draw an isosceles triangle.
1009
+ 参数 / Parameters:
1010
+ legs (int/float): 腰长,如 '100'
1011
+ base (int/float): 底边长,如 '120'
1012
+ start_pos (tuple): 起始坐标 (x, y),可选
1013
+ color (str): 颜色,如 'purple'
1014
+ fill (bool): 是否填充
1015
+ 示例 / Example:
1016
+ pen.draw_isosceles_triangle(100, 120)
1017
+ pen.draw_isosceles_triangle(90, 100, fill=True)
1018
+ 注意 / Note:
1019
+ ⚠️ 底边长度不能大于两腰之和,否则无法构成三角形。
1020
+ The base cannot be longer than the sum of the two legs.
1021
+ """
1022
+ state = self.pen_save_state()
1023
+ if base / 2 > legs:
1024
+ if self._lang == "ch":
1025
+ print("❌ 错误:底边不能大于两腰之和,无法构成三角形")
1026
+ print("📌 示例:pen.draw_isosceles_triangle(100, 120)")
1027
+ else:
1028
+ print("❌ Error: base cannot be longer than the sum of the two legs")
1029
+ print("📌 Example: pen.draw_isosceles_triangle(100, 120)")
1030
+ self.pen_restore_state(state)
1031
+ return
1032
+ self._reset_pen()
1033
+ self.t.penup()
1034
+ if start_pos:
1035
+ self.t.goto(start_pos)
1036
+ self.t.pendown()
1037
+ self.t.pencolor(color)
1038
+ if fill:
1039
+ self.t.fillcolor(color)
1040
+ self.t.begin_fill()
1041
+ base_angle = math.degrees(math.acos((base / 2) / legs))
1042
+ self.t.forward(base)
1043
+ self.t.left(180 - base_angle)
1044
+ self.t.forward(legs)
1045
+ self.t.left(2 * base_angle)
1046
+ self.t.forward(legs)
1047
+ if fill:
1048
+ self.t.end_fill()
1049
+ self.pen_restore_state(state)
1050
+ def draw_polygon(self, sides, side_length, start_pos=None, color="black", fill=False):
1051
+ """
1052
+ 绘制正多边形。
1053
+ Draw a regular polygon.
1054
+ 参数 / Parameters:
1055
+ sides (int): 边数,如 '3'(三角形)、'6'(六边形)
1056
+ side_length (int/float): 边长,如 '100'
1057
+ start_pos (tuple): 起始坐标 (x, y),可选
1058
+ color (str): 颜色,如 'green'
1059
+ fill (bool): 是否填充
1060
+ 示例 / Example:
1061
+ pen.draw_polygon(6, 80)
1062
+ pen.draw_polygon(8, 60, fill=True, color='gold')
1063
+ """
1064
+ state = self.pen_save_state()
1065
+ self._reset_pen()
1066
+ self.t.penup()
1067
+ if start_pos:
1068
+ self.t.goto(start_pos)
1069
+ self.t.pendown()
1070
+ self.t.pencolor(color)
1071
+ if fill:
1072
+ self.t.fillcolor(color)
1073
+ self.t.begin_fill()
1074
+ angle = 360 / sides
1075
+ for _ in range(sides):
1076
+ self.t.forward(side_length)
1077
+ self.t.right(angle)
1078
+ if fill:
1079
+ self.t.end_fill()
1080
+ self.pen_restore_state(state)
1081
+ def draw_star(self, points=5, outer_radius=100, inner_radius=None,
1082
+ start_pos=None, color="black", fill=False):
1083
+ """
1084
+ 绘制正多角星(五角星、六角星等)。
1085
+ Draw a regular star polygon (5‑pointed star, 6‑pointed star, etc.).
1086
+ 参数 / Parameters:
1087
+ points (int): 角的数量,如 5(五角星)、6(六角星)
1088
+ outer_radius (int/float): 外半径(星角尖端到中心的距离)
1089
+ inner_radius (int/float): 内半径(星角凹处到中心的距离),可选
1090
+ start_pos (tuple): 起始坐标 (x, y),可选
1091
+ color (str): 画笔颜色,如 'gold'
1092
+ fill (bool): 是否填充
1093
+ 示例 / Examples:
1094
+ pen.draw_star(points=5, outer_radius=120, color="gold", fill=True)
1095
+ pen.draw_star(points=6, outer_radius=100, color="purple")
1096
+ 注意 / Note:
1097
+ ⚠️ 当前算法仅对奇数角星(points 为奇数)效果正确。
1098
+ 偶数角星(如六角星)建议使用组合图形实现。
1099
+ Current algorithm only works correctly for odd‑numbered stars.
1100
+ For even‑numbered stars (e.g. hexagram), use composite shapes.
1101
+ """
1102
+ if points % 2 == 0:
1103
+ if self._lang == "ch":
1104
+ print("⚠️ 提示:当前算法仅支持奇数角星,偶数角星效果可能不符合预期")
1105
+ print("📌 建议:使用组合图形绘制六角星等偶数角星")
1106
+ else:
1107
+ print("⚠️ Note: current algorithm only works correctly for odd‑numbered stars")
1108
+ print("📌 Suggestion: use composite shapes for even‑numbered stars")
1109
+ self.pen_restore_state(state)
1110
+ return
1111
+ state = self.pen_save_state()
1112
+ self._reset_pen()
1113
+ t = self.t
1114
+ if inner_radius is None:
1115
+ inner_radius = outer_radius * 0.381966
1116
+ t.penup()
1117
+ if start_pos:
1118
+ t.goto(start_pos)
1119
+ else:
1120
+ t.goto(0, 0)
1121
+ t.setheading(90)
1122
+ t.forward(outer_radius)
1123
+ t.setheading(180 - (180 / points))
1124
+ t.pendown()
1125
+ t.pencolor(color)
1126
+ if fill:
1127
+ t.fillcolor(color)
1128
+ t.begin_fill()
1129
+ outer_turn = 180 - (360.0 / points)
1130
+ inner_turn = 180 + (360.0 / points)
1131
+ for _ in range(points):
1132
+ t.forward(outer_radius)
1133
+ t.right(outer_turn)
1134
+ t.forward(inner_radius)
1135
+ t.left(inner_turn)
1136
+ if fill:
1137
+ t.end_fill()
1138
+ self.pen_restore_state(state)
1139
+ def draw_python_logo(self, start_pos=None):
1140
+ """
1141
+ 绘制 Python Logo。
1142
+ Draw the Python logo.
1143
+ 参数 / Parameters:
1144
+ start_pos (tuple): 起始坐标 (x, y),可选
1145
+ 若提供,会将整个 Logo 平移到该位置附近
1146
+ 功能 / Function:
1147
+ - 蓝色蛇身 + 黄色蛇身,经典 Python Logo
1148
+ - 白色眼睛
1149
+ - "Python" 文字(蓝+黄)
1150
+ 示例 / Example:
1151
+ pen.draw_python_logo()
1152
+ pen.draw_python_logo(start_pos=(-100, 0))
1153
+ """
1154
+ state = self.pen_save_state()
1155
+ old_cmode = self.get_color_mode()
1156
+ self.set_color_mode(255)
1157
+
1158
+ t = self.t
1159
+ offset_x = start_pos[0] if start_pos else 0
1160
+ offset_y = start_pos[1] if start_pos else 0
1161
+
1162
+ def o(x, y):
1163
+ return x + offset_x, y + offset_y
1164
+
1165
+ t.speed(10)
1166
+ t.pensize(3)
1167
+
1168
+ # ============ 蓝色区域 ============
1169
+ t.penup()
1170
+ t.goto(*o(-100, 105))
1171
+ t.pencolor(54, 110, 157)
1172
+ t.fillcolor(54, 110, 157)
1173
+ t.begin_fill()
1174
+ t.goto(*o(-125, -115))
1175
+ t.pendown()
1176
+ t.setheading(90)
1177
+ t.forward(55)
1178
+ t.circle(-50, 90)
1179
+ t.forward(190)
1180
+ t.circle(50, 90)
1181
+ t.forward(100)
1182
+ t.circle(85, 90)
1183
+ t.forward(100)
1184
+ t.circle(85, 90)
1185
+ t.forward(30)
1186
+ t.left(90)
1187
+ t.forward(150)
1188
+ t.setheading(270)
1189
+ t.forward(20)
1190
+ t.right(90)
1191
+ t.forward(220)
1192
+ t.circle(50, 90)
1193
+ t.forward(105)
1194
+ t.circle(50, 90)
1195
+ t.forward(50)
1196
+ t.left(90)
1197
+ t.end_fill()
1198
+
1199
+ # ============ 蓝色眼睛 ============
1200
+ t.fillcolor(255, 255, 255)
1201
+ t.penup()
1202
+ t.goto(*o(-25, 155))
1203
+ t.pencolor(255, 255, 255)
1204
+ t.pendown()
1205
+ t.begin_fill()
1206
+ t.circle(20, 360)
1207
+ t.end_fill()
1208
+
1209
+ # ============ 黄色区域 ============
1210
+ t.penup()
1211
+ t.goto(*o(185, 80))
1212
+ t.pencolor(255, 212, 69)
1213
+ t.fillcolor(255, 212, 69)
1214
+ t.pendown()
1215
+ t.begin_fill()
1216
+ t.setheading(270)
1217
+ t.forward(55)
1218
+ t.circle(-50, 90)
1219
+ t.forward(190)
1220
+ t.circle(50, 90)
1221
+ t.forward(100)
1222
+ t.circle(85, 90)
1223
+ t.forward(100)
1224
+ t.circle(85, 90)
1225
+ t.forward(30)
1226
+ t.left(90)
1227
+ t.forward(150)
1228
+ t.right(90)
1229
+ t.forward(20)
1230
+ t.right(90)
1231
+ t.forward(220)
1232
+ t.circle(50, 90)
1233
+ t.forward(105)
1234
+ t.circle(50, 90)
1235
+ t.forward(50)
1236
+ t.end_fill()
1237
+
1238
+ # ============ 黄色眼睛 ============
1239
+ t.fillcolor(255, 255, 255)
1240
+ t.penup()
1241
+ t.goto(*o(90, -180))
1242
+ t.pencolor(255, 255, 255)
1243
+ t.pendown()
1244
+ t.begin_fill()
1245
+ t.circle(20, 360)
1246
+ t.end_fill()
1247
+
1248
+ # ============ Python 文字(固定字号) ============
1249
+ t.pensize(80)
1250
+ t.pencolor(54, 105, 157)
1251
+ t.penup()
1252
+ t.goto(*o(230, 150))
1253
+ t.pendown()
1254
+ t.write("Pyt", font=("Arial", 25, "bold"))
1255
+
1256
+ t.pencolor(255, 212, 69)
1257
+ t.penup()
1258
+ t.goto(*o(280, 150))
1259
+ t.pendown()
1260
+ t.write("hon", font=("Arial", 25, "bold"))
1261
+
1262
+ t.pensize(1)
1263
+ self.set_color_mode(old_cmode)
1264
+ self.pen_restore_state(state)
1265
+ def draw_colorful_spiral(self, turns=5, step=2, start_pos=None):
1266
+ """
1267
+ 绘制彩色螺旋线。
1268
+ Draw a colorful spiral.
1269
+ 参数 / Parameters:
1270
+ turns (int): 螺旋圈数,如 '5'
1271
+ step (int): 每次前进增量,如 '2'
1272
+ start_pos (tuple): 起始坐标 (x, y),可选
1273
+ 功能 / Function:
1274
+ - 用随机亮色画一条逐渐放大的螺旋线
1275
+ Draw an expanding spiral with random bright colors
1276
+ 示例 / Example:
1277
+ pen.draw_colorful_spiral(5, 2)
1278
+ pen.draw_colorful_spiral(8, 3, start_pos=(100, 0))
1279
+ """
1280
+ state = self.pen_save_state()
1281
+ self._reset_pen()
1282
+ t = self.t
1283
+ t.penup()
1284
+ if start_pos:
1285
+ t.goto(start_pos)
1286
+ else:
1287
+ t.goto(0, 0)
1288
+ t.pendown()
1289
+ t.speed(0)
1290
+
1291
+ d = random.randint(50, 10000)
1292
+ r = 0.5
1293
+ colors = [
1294
+ '#FF403F', '#FF7F23', '#FFD602',
1295
+ '#7FFF01', '#1D90FF', '#1874CD', '#9B30FF'
1296
+ ]
1297
+
1298
+ for i in range(700):
1299
+ t.pencolor(colors[i % 7])
1300
+ t.forward(r)
1301
+ t.right(d)
1302
+ r += 1
1303
+
1304
+ self.pen_restore_state(state)
1305
+ def draw_rainbow(self, radius=300, center=None):
1306
+ """
1307
+ 绘制彩虹(七条同心圆弧)。
1308
+ Draw a rainbow (seven concentric arcs).
1309
+ 参数 / Parameters:
1310
+ radius (int/float): 最外层半径,如 '300'
1311
+ center (tuple): 圆心坐标 (x, y),可选,默认 (0, ‑radius)
1312
+ 功能 / Function:
1313
+ - 用红橙黄绿蓝靛紫七色画同心圆弧
1314
+ Draw concentric arcs in red, orange, yellow, green, blue, indigo, violet
1315
+ 示例 / Example:
1316
+ pen.draw_rainbow()
1317
+ pen.draw_rainbow(radius=400)
1318
+ """
1319
+ state = self.pen_save_state()
1320
+ self._reset_pen()
1321
+ t = self.t
1322
+ t.penup()
1323
+
1324
+ if center:
1325
+ cx, cy = center
1326
+ else:
1327
+ cx, cy = 0, -radius * 0.6
1328
+
1329
+ pen_width = max(radius // 20, 6)
1330
+ t.pensize(pen_width)
1331
+
1332
+ rainbow_colors = [
1333
+ "red", "orange", "yellow", "green",
1334
+ "blue", "indigo", "violet"
1335
+ ]
1336
+
1337
+ for i, color in enumerate(rainbow_colors):
1338
+ r = radius - i * pen_width
1339
+ t.goto(cx, cy + r)
1340
+ t.setheading(0)
1341
+ t.pencolor(color)
1342
+ t.pendown()
1343
+ t.circle(r, 180)
1344
+ t.penup()
1345
+
1346
+ t.pensize(1)
1347
+ self.pen_restore_state(state)
1348
+
1349
+ def draw_maze(self, rows=10, cols=10, cell_size=20):
1350
+ """
1351
+ 绘制随机迷宫(递归回溯算法)。
1352
+ Draw a random maze using recursive backtracking.
1353
+ 参数 / Parameters:
1354
+ rows (int): 迷宫行数,如 '10'
1355
+ cols (int): 迷宫列数,如 '10'
1356
+ cell_size (int): 每个格子的像素大小,如 '20'
1357
+ 功能 / Function:
1358
+ - 使用递归回溯算法生成随机迷宫
1359
+ Generate a random maze using recursive backtracking
1360
+ - 画出迷宫墙壁
1361
+ Draw maze walls
1362
+ 示例 / Example:
1363
+ pen.draw_maze()
1364
+ pen.draw_maze(rows=15, cols=15, cell_size=15)
1365
+ 注意 / Note:
1366
+ ⚠️ 当 rows 或 cols 过大(如 >25)时,可能触发递归深度超限。
1367
+ 建议合理控制迷宫尺寸。
1368
+ Large mazes (e.g. >25) may exceed Python recursion limit.
1369
+ Keep maze size reasonable.
1370
+ """
1371
+ if rows * cols > 400:
1372
+ if self._lang == "ch":
1373
+ print("⚠️ 警告:迷宫尺寸过大,可能导致递归深度超限")
1374
+ print("📌 建议:rows × cols 不超过 400")
1375
+ else:
1376
+ print("⚠️ Warning: large maze may exceed recursion limit")
1377
+ print("📌 Suggestion: keep rows × cols <= 400")
1378
+
1379
+ state = self.pen_save_state()
1380
+ self._reset_pen()
1381
+ t = self.t
1382
+ t.speed(0)
1383
+ t.pensize(2)
1384
+ t.pencolor("black")
1385
+
1386
+ maze = [[1 for _ in range(cols * 2 + 1)] for _ in range(rows * 2 + 1)]
1387
+
1388
+ def carve(x, y):
1389
+ maze[y][x] = 0
1390
+ directions = [(0, -2), (2, 0), (0, 2), (-2, 0)]
1391
+ random.shuffle(directions)
1392
+ for dx, dy in directions:
1393
+ nx, ny = x + dx, y + dy
1394
+ if 0 <= nx < cols * 2 + 1 and 0 <= ny < rows * 2 + 1 and maze[ny][nx] == 1:
1395
+ maze[y + dy // 2][x + dx // 2] = 0
1396
+ carve(nx, ny)
1397
+
1398
+ try:
1399
+ carve(1, 1)
1400
+ except RecursionError:
1401
+ if self._lang == "ch":
1402
+ print("❌ 迷宫生成失败,递归深度超出限制,请减小行列数")
1403
+ else:
1404
+ print("❌ Maze generation failed, recursion depth exceeded, reduce rows/cols")
1405
+ self.pen_restore_state(state)
1406
+ return
1407
+
1408
+ maze[1][0] = 0
1409
+ maze[rows * 2 - 1][cols * 2] = 0
1410
+
1411
+ t.penup()
1412
+ for y in range(rows * 2 + 1):
1413
+ for x in range(cols * 2 + 1):
1414
+ if maze[y][x] == 1:
1415
+ t.goto(
1416
+ -cols * cell_size + x * cell_size // 2,
1417
+ rows * cell_size - y * cell_size // 2
1418
+ )
1419
+ t.pendown()
1420
+ t.begin_fill()
1421
+ for _ in range(4):
1422
+ t.forward(cell_size // 2)
1423
+ t.right(90)
1424
+ t.end_fill()
1425
+ t.penup()
1426
+
1427
+ self.pen_restore_state(state)
1428
+ def draw_random_art(self, count=6, max_size=120):
1429
+ """
1430
+ 绘制一个"艺术画廊"(随机图形集合)。
1431
+ Draw an art gallery (collection of random shapes).
1432
+ 参数 / Parameters:
1433
+ count (int): 图形数量,如 '6'
1434
+ max_size (int): 最大图形尺寸,如 '120'
1435
+ 功能 / Function:
1436
+ - 在画布上随机位置绘制多种彩色图形
1437
+ Draw multiple colorful shapes at random positions
1438
+ 示例 / Example:
1439
+ pen.draw_random_art()
1440
+ pen.draw_random_art(count=9, max_size=100)
1441
+ """
1442
+ state = self.pen_save_state()
1443
+ self._reset_pen()
1444
+ t = self.t
1445
+ t.speed(0)
1446
+ for _ in range(count):
1447
+ x = random.randint(-350, 350)
1448
+ y = random.randint(-250, 250)
1449
+ sides = random.randint(3, 8)
1450
+ size = random.randint(30, max_size)
1451
+ color = self.random_color("pastel")
1452
+ t.penup()
1453
+ t.goto(x, y)
1454
+ t.pendown()
1455
+ t.pencolor(color)
1456
+ t.fillcolor(color)
1457
+ t.begin_fill()
1458
+ angle = 360 / sides
1459
+ for _ in range(sides):
1460
+ t.forward(size)
1461
+ t.right(angle)
1462
+ t.end_fill()
1463
+ self.pen_restore_state(state)
1464
+
1465
+ def drawing_challenge(self, lang=None):
1466
+ """
1467
+ 随机生成一个绘图挑战题目。
1468
+ Generate a random drawing challenge.
1469
+ 参数 / Parameters:
1470
+ lang (str): 语言,"ch"中文 / "en"英文;None 使用对象自身 _lang
1471
+ 功能 / Function:
1472
+ - 在控制台打印一个创意绘图任务
1473
+ Print a creative drawing task to the console
1474
+ 示例 / Example:
1475
+ pen.drawing_challenge()
1476
+ pen.drawing_challenge(lang="en")
1477
+ """
1478
+ challenges = {
1479
+ "ch": [
1480
+ "🎨 挑战:用 3 种颜色画一座房子",
1481
+ "🎨 挑战:画一个彩虹螺旋",
1482
+ "🎨 挑战:用星星拼一个圆形",
1483
+ "🎨 挑战:画一个对称图案",
1484
+ "🎨 挑战:用迷宫困住一只乌龟",
1485
+ "🎨 挑战:画一个月亮和星星的夜空",
1486
+ "🎨 挑战:画一朵多瓣的花朵",
1487
+ "🎨 挑战:只用三角形拼出动物",
1488
+ "🎨 挑战:画一个不断变大的正方形方阵",
1489
+ "🎨 挑战:画波浪海岸线",
1490
+ "🎨 挑战:画雪花,要六条分支",
1491
+ "🎨 挑战:画出你名字的艺术字体",
1492
+ "🎨 挑战:画太阳,外圈要有光芒",
1493
+ "🎨 挑战:画螺旋正方形,一圈比一圈大",
1494
+ "🎨 挑战:只用圆形画出一张笑脸",
1495
+ "🎨 挑战:画梯田一样阶梯图案",
1496
+ "🎨 挑战:画风车,4片叶片",
1497
+ "🎨 挑战:画一条彩色的小蛇",
1498
+ "🎨 挑战:画棋盘格子图案",
1499
+ "🎨 挑战:画出五瓣的梅花",
1500
+ "🎨 挑战:画五角星花环",
1501
+ "🎨 挑战:画起伏的小山",
1502
+ ],
1503
+ "en": [
1504
+ "🎨 Challenge: Draw a house using 3 colors",
1505
+ "🎨 Challenge: Draw a rainbow spiral",
1506
+ "🎨 Challenge: Arrange stars into a circle",
1507
+ "🎨 Challenge: Create a symmetrical pattern",
1508
+ "🎨 Challenge: Trap a turtle in a maze",
1509
+ "🎨 Challenge: Draw a night sky with moon and stars",
1510
+ "🎨 Challenge: Draw a multi‑petal flower",
1511
+ "🎨 Challenge: Make an animal only with triangles",
1512
+ "🎨 Challenge: Draw growing square grid",
1513
+ "🎨 Challenge: Draw wavy coastline",
1514
+ "🎨 Challenge: Draw 6‑point snowflake",
1515
+ "🎨 Challenge: Draw fancy art of your name",
1516
+ "🎨 Challenge: Draw sun with shining rays",
1517
+ "🎨 Challenge: Draw expanding square spiral",
1518
+ "🎨 Challenge: Draw smiley only with circles",
1519
+ "🎨 Challenge: Draw terrace‑like steps",
1520
+ "🎨 Challenge: Draw a 4‑bladed windmill",
1521
+ "🎨 Challenge: Draw a colorful little snake",
1522
+ "🎨 Challenge: Draw checkerboard grid",
1523
+ "🎨 Challenge: Draw five‑petal plum blossom",
1524
+ "🎨 Challenge: Make wreath with five‑point stars",
1525
+ "🎨 Challenge: Draw rolling hills",
1526
+ ]
1527
+ }
1528
+ use_lang = lang if lang is not None else self._lang
1529
+ if use_lang not in ["ch", "en"]:
1530
+ use_lang = self._lang
1531
+ print(random.choice(challenges[use_lang]))
1532
+
1533
+ def help(self):
1534
+ """
1535
+ 打印 Python Pen 帮助文档。
1536
+ Print the Python Pen help documentation.
1537
+ """
1538
+ if self._lang == "ch":
1539
+ print(f"""
1540
+ 🎨 Python Pen 绘图库 - 帮助文档 v{python_pen.__version__}
1541
+
1542
+ 📋 数学常量:
1543
+ self.E, self.I, self.PI, self.PHI, self.SQRT2
1544
+
1545
+ 🎨 基础控制:
1546
+ bg, style, set_icon, lang
1547
+
1548
+ 🚀 画笔移动:
1549
+ pen_forward, pen_backward, pen_left, pen_right
1550
+ pen_goto, pen_home, pen_setheading
1551
+
1552
+ 📍 画布与状态:
1553
+ pen_clear, pen_reset, pen_pos
1554
+ pen_save_state, pen_restore_state
1555
+ pen_tracer, pen_update
1556
+
1557
+ 🖊️ 文本与交互:
1558
+ pen_write, pen_stamp, pen_clear_stamp
1559
+ pen_num_input, pen_text_input
1560
+ pen_set_title, pen_delay
1561
+
1562
+ 🌈 时间与颜色:
1563
+ show_detailed_time, set_color_mode, get_color_mode
1564
+ random_color, random_int, random_float
1565
+ random_choice, random_shuffle
1566
+
1567
+ ▣ 窗口控制:
1568
+ screen_exitonclick, screen_mainloop, screen_bye
1569
+
1570
+ 🔺 基础图形:
1571
+ draw_circle, draw_square, draw_rectangle
1572
+ draw_equilateral_triangle, draw_isosceles_triangle
1573
+ draw_polygon
1574
+
1575
+ 🔷 高级图形:
1576
+ draw_star, draw_python_logo
1577
+ draw_colorful_spiral, draw_rainbow
1578
+ draw_maze, draw_random_art
1579
+
1580
+ 🎯 工具与扩展:
1581
+ drawing_challenge, help
1582
+ """)
1583
+ else:
1584
+ print(f"""
1585
+ 🎨 Python Pen Drawing Library - Help v{python_pen.__version__}
1586
+
1587
+ 📋 Math Constants:
1588
+ self.E, self.I, self.PI, self.PHI, self.SQRT2
1589
+
1590
+ 🎨 Basic Control:
1591
+ bg, style, set_icon, lang
1592
+
1593
+ 🚀 Pen Movement:
1594
+ pen_forward, pen_backward, pen_left, pen_right
1595
+ pen_goto, pen_home, pen_setheading
1596
+
1597
+ 📍 Canvas & State:
1598
+ pen_clear, pen_reset, pen_pos
1599
+ pen_save_state, pen_restore_state
1600
+ pen_tracer, pen_update
1601
+
1602
+ 🖊️ Text & Interaction:
1603
+ pen_write, pen_stamp, pen_clear_stamp
1604
+ pen_num_input, pen_text_input
1605
+ pen_set_title, pen_delay
1606
+
1607
+ 🌈 Time & Color:
1608
+ show_detailed_time, set_color_mode, get_color_mode
1609
+ random_color, random_int, random_float
1610
+ random_choice, random_shuffle
1611
+
1612
+ ▣ Window Control:
1613
+ screen_exitonclick, screen_mainloop, screen_bye
1614
+
1615
+ 🔺 Basic Shapes:
1616
+ draw_circle, draw_square, draw_rectangle
1617
+ draw_equilateral_triangle, draw_isosceles_triangle
1618
+ draw_polygon
1619
+
1620
+ 🔷 Advanced Shapes:
1621
+ draw_star, draw_python_logo
1622
+ draw_colorful_spiral, draw_rainbow
1623
+ draw_maze, draw_random_art
1624
+
1625
+ 🎯 Utilities:
1626
+ drawing_challenge, help
1627
+ """)
1628
+ if "PythonPen" not in sys.modules:
1629
+ sys.modules["PythonPen"] = sys.modules[__name__]
1630
+ # End of PythonPen core module