pip install pygame
import pygame
import sys
import math
# 初始化 pygame
pygame.init()
# 游戏窗口的宽度和高度
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
FPS = 60
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("跳绳游戏")
# 设置时钟
clock = pygame.time.Clock()
# 绳子的参数
rope_length = 300
rope_speed = 5
angle = 0
# 玩家参数
player_size = 40
player_x = WINDOW_WIDTH // 2
player_y = WINDOW_HEIGHT - 100
player_color = BLACK
player_jump = False
player_jump_count = 0
def draw_rope(angle):
rope_x = WINDOW_WIDTH // 2
rope_y = WINDOW_HEIGHT // 2
end_x = rope_x + rope_length * math.cos(angle)
end_y = rope_y + rope_length * math.sin(angle)
pygame.draw.line(screen, RED, (rope_x, rope_y), (end_x, end_y), 5)
def draw_player(x, y):
pygame.draw.rect(screen, player_color, (x - player_size // 2, y - player_size // 2, player_size, player_size))
def main():
global angle, player_y, player_jump, player_jump_count
game_active = True
while game_active:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not player_jump:
player_jump = True
# 更新绳子的角度
angle += rope_speed * 0.01
if angle > 2 * math.pi:
angle -= 2 * math.pi
# 控制玩家的跳跃
if player_jump:
if player_jump_count >= -10:
neg = 1
if player_jump_count < 0:
neg = -1
player_y -= (player_jump_count ** 2) * 0.4 * neg
player_jump_count -= 1
else:
player_jump = False
player_jump_count = 10
player_y = WINDOW_HEIGHT - 100
# 检查是否与绳子碰撞
rope_x = WINDOW_WIDTH // 2
rope_y = WINDOW_HEIGHT // 2
end_x = rope_x + rope_length * math.cos(angle)
end_y = rope_y + rope_length * math.sin(angle)
if (player_x - player_size // 2 < end_x < player_x + player_size // 2) and \
(player_y - player_size // 2 < end_y < player_y + player_size // 2):
print("游戏结束!")
pygame.quit()
sys.exit()
# 填充背景色
screen.fill(WHITE)
# 绘制绳子和玩家
draw_rope(angle)
draw_player(player_x, player_y)
# 刷新屏幕
pygame.display.flip()
clock.tick(FPS)
if __name__ == "__main__":
main()
代码说明
- 初始化和设置: 初始化
pygame
并创建一个窗口。 - 绘制绳子:
draw_rope()
函数用于绘制旋转的绳子。 - 绘制玩家:
draw_player()
函数绘制玩家的矩形表示。 - 游戏循环:
- 更新绳子的角度。
- 处理玩家的跳跃逻辑。
- 检测玩家是否与绳子碰撞。
- 刷新屏幕,绘制游戏内容。
扩展功能
- 碰撞检测改进: 增强玩家与绳子的碰撞检测逻辑,以更真实地处理碰撞。
- 跳跃计时器: 添加计时器来限制玩家跳跃的频率。
- 得分系统: 实现得分系统,根据玩家成功跳过绳子的次数进行计分。
- 难度设置: 增加游戏难度选项,例如调整绳子的旋转速度或增加障碍物。