Python 不倒翁代码实现 - 简单易懂教程
不倒翁(也叫不倒立的玩具)是一种可以自己倒立起来的玩具,它的重心位于底部,可以通过调整重心的位置来保持平衡。下面是一个用 Python 实现不倒翁的简单例子:
import pygame
# 初始化pygame
pygame.init()
# 设置窗口大小和标题
screen_width = 400
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('不倒翁')
# 定义不倒翁的属性
x = 200
y = 300
r = 50
dx = 0
dy = 0
g = 0.1
# 绘制不倒翁
def draw():
pygame.draw.circle(screen, (255, 0, 0), (x, y), r)
# 更新不倒翁的位置和速度
def update():
global x, y, dx, dy
x += dx
y += dy
dy += g
# 碰到底部时反弹
if y + r > screen_height:
dy = -dy * 0.8
# 碰到左右边界时反弹
if x - r < 0 or x + r > screen_width:
dx = -dx * 0.8
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新不倒翁的位置和速度
update()
# 绘制不倒翁
screen.fill((255, 255, 255))
draw()
pygame.display.update()
# 退出pygame
pygame.quit()
这段代码使用 Pygame 库来实现游戏窗口和图形绘制,定义了不倒翁的一些属性,包括位置、半径、速度等,并实现了 update()
和 draw()
函数来更新不倒翁的位置和绘制不倒翁。在游戏循环中,不断更新不倒翁的位置和速度,并在屏幕上绘制不倒翁,直到用户关闭窗口。

原文地址: http://www.cveoy.top/t/topic/mPSB 著作权归作者所有。请勿转载和采集!