Skip to content

Latest commit

 

History

History
100 lines (73 loc) · 2.91 KB

677-1011623-龟兔赛跑_图形音乐效果.sy.md

File metadata and controls

100 lines (73 loc) · 2.91 KB

图片描述

图片描述

import pygame
import sys

# 初始化 Pygame
pygame.init()

# 设置窗口大小
win_width, win_height = 800, 600
win = pygame.display.set_mode((win_width, win_height))

# 加载图片
turtle = pygame.image.load('turtle.png')
rabbit = pygame.image.load('rabbit.png')

# 改变图片尺寸
turtle = pygame.transform.scale(turtle, (80, 60))  # 设置乌龟图片的宽为80像素,高为60像素
rabbit = pygame.transform.scale(rabbit, (80, 60))  # 设置兔子图片的宽为80像素,高为60像素

# 设置初始位置
turtle_x, turtle_y = 0, win_height // 2
rabbit_x, rabbit_y = 0, win_height // 4

# 设置速度
turtle_speed = 2
rabbit_speed = 3

# 设置终点线的位置
finish_line_x = win_width - 100

# 加载音乐
#pygame.mixer.music.load('music.mp3')
#pygame.mixer.music.play(-1)  # 播放音乐,-1表示循环播放

# 加载胜利画面的兔子图片
win_rabbit = pygame.image.load('rabbit.png')
win_rabbit = pygame.transform.scale(win_rabbit, (200, 150))  # 假设我们想要200x150像素的图片

# 设置字体和大小
font = pygame.font.Font(None, 36)  #
win_text = font.render('Rabbit Win!', True, (0, 0, 0))  # 创建文本,黑色的文字

# 计算兔子和文本的位置
win_rabbit_x = (win_width - win_rabbit.get_width()) // 2
win_rabbit_y = (win_height - win_rabbit.get_height()) // 2
win_text_x = (win_width - win_text.get_width()) // 2
win_text_y = win_rabbit_y - win_text.get_height() - 10  # 留出10像素的间隙

# 标记游戏是否结束
game_over = False

# 主循环
while True:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # 如果游戏没有结束,就更新乌龟和兔子的位置
    if not game_over:
        turtle_x += turtle_speed
        rabbit_x += rabbit_speed

        # 画背景色
        win.fill((255, 255, 255))

        # 画跑道
        pygame.draw.line(win, (0, 0, 0), (0, win_height // 2 + 30), (win_width, win_height // 2 + 30))
        pygame.draw.line(win, (0, 0, 0), (0, win_height // 4 - 30), (win_width, win_height // 4 - 30))

        # 画终点线
        pygame.draw.line(win, (255, 0, 0), (finish_line_x, 0), (finish_line_x, win_height), 5)

        # 画乌龟和兔子
        win.blit(turtle, (turtle_x, turtle_y))
        win.blit(rabbit, (rabbit_x, rabbit_y))

        # 检查是否到达终点
        if rabbit_x + rabbit.get_width() > finish_line_x and not game_over:
            game_over = True
    else:
        # 如果兔子赢了,就显示大一点的兔子和胜利的文本
        win.blit(win_rabbit, (win_rabbit_x, win_rabbit_y))
        win.blit(win_text, (win_text_x, win_text_y))

    # 更新窗口
    pygame.display.update()

    # 帧率限制
    pygame.time.Clock().tick(60)