一小段完整的pygame程序

本文介绍了一个使用Python和Pygame库实现的简易2D游戏示例,玩家通过键盘操作角色移动并尝试触碰游戏中的球体以触发爆炸效果得分。游戏设有边界检测和计分系统,最终显示总得分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pygame
import random
pygame.init()

#Window setup
size = [400, 300]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

#player position
x = size[0] / 2
y = size[1] / 2

#ball position
ballX = random.randrange(0, size[0])
ballY = random.randrange(0, size[1])

#goal position
goalX = size[0]/2 - 10
goalY = size[1]/2 - 10
goalW = 20
goalH = 20

#pointes
points = 0
point = 0
pointX = 0

#colors
red = pygame.color.Color('#FF8080')
blue = pygame.color.Color('#8080FF')
white = pygame.color.Color('#FFFFFF')
black = pygame.color.Color('#000000')

def CheckOffScreenX(x):
    if x > size[0]:
        x = 0
    elif x < 0:
        x = size[0]
    return x

def CheckOffScreenY(y):
    if y > size[1]:
        y = 0
    elif y < 0:
        y = size[1]
    return y

def checkTouching():
    """Causes a small explosion if the players are touching"""
    global x
    global ballX
    global y
    global ballY

    #check if player and ball are touching
    if -10 < y - ballY < 10 and -10 < x - ballX <10:
        #draw an explosion
        pygame.draw.circle(screen, white, [x, y], 15)

        xDiff = x - ballX
        yDiff = y - ballY

        #check if ball is on edge of screen
        if ballX == 0:
            xDiff -= 5
        elif ballX == size[0]:
            xDiff += 5
        if ballY == 0:
            yDiff -= 5
        elif ballY == size[1]:
            yDiff += 5

        #move the ball and player
        x += yDiff * 3
        ballX -= xDiff * 3

        y += yDiff * 3
        ballY -= yDiff * 3

#Game loop
done = False

#get current time
timeStart = pygame.time.get_ticks()

while not done:
    screen.fill(black)

    #Draw the goal
    pygame.draw.rect(screen, white, (goalX, goalY, goalW, goalH))

    #check ball is in goal
    if goalX <= ballX <= goalX + goalH and goalY <= ballY <= goalY + goalH:
        points += 1
        ballX = random.randrange(0, size[0])
        ballY = random.randrange(0, size[1]) 

    #draw points 
    for point in range(points):
        pointX = 0 + point*5
    pygame.draw.rect(screen, white, (pointX, 3, 4, 7))

    keys = pygame.key.get_pressed()

    #player movement
    if keys[pygame.K_w]:
        y -= 1

    if keys[pygame.K_s]:
        y += 1

    if keys[pygame.K_a]:
        x -= 1

    if keys[pygame.K_d]:
        x += 1

    #check off screen
    x = CheckOffScreenX(x)
    y = CheckOffScreenY(y)
    ballX = CheckOffScreenX(ballX)
    ballY = CheckOffScreenY(ballY)

    #draw player
    pygame.draw.circle(screen, red, [x,y], 6)

    #check if player is touching the ball
    checkTouching()

    #draw ball
    pygame.draw.circle(screen, blue, [ballX, ballY], 6)

    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        clock.tick(72)

        #Check elapsed time
        timeNow = pygame.time.get_ticks()
        if timeNow - timeStart >= 60000:
            done = True

pygame.quit()

#print on shell window
print "Total Points:" + str(points)
print "Remaining time:" + str(timeNow - timeStart)
### 使用 Pygame 播放音乐的实现方法 在 Python 中,Pygame 是一个功能强大的库,可以用来开发游戏和处理多媒体内容。要实现音乐播放功能,可以使用 Pygame 的混音器模块(`pygame.mixer`)。以下是完整的代码示例以及详细说明: ```python import pygame # 初始化 Pygame 和混音器模块 pygame.init() pygame.mixer.init() # 加载音乐文件(确保文件格式为 WAV 或 OGG,避免 MP3 不兼容问题) music_file = "example_music.wav" # 替换为实际的音乐文件路径 pygame.mixer.music.load(music_file) # 加载音乐文件 # 设置音量(范围为 0.0 到 1.0 的浮点数) pygame.mixer.music.set_volume(0.5) # 设置音量为 50% # 播放音乐(loops 参数控制播放次数,-1 表示无限循环) pygame.mixer.music.play(loops=-1) # 创建一个窗口以保持程序运行(可选) screen = pygame.display.set_mode((200, 100)) # 创建一个小窗口 pygame.display.set_caption("Music Player") # 设置窗口标题 # 主循环:监听退出事件 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: # 如果用户点击关闭按钮 running = False # 停止音乐并退出程序 pygame.mixer.music.stop() pygame.quit() ``` #### 代码说明 1. **初始化模块**:`pygame.init()` 初始化所有 Pygame 模块,而 `pygame.mixer.init()` 仅初始化混音器模块[^2]。 2. **加载音乐文件**:使用 `pygame.mixer.music.load()` 方法加载音乐文件。注意,某些平台(如 Ubuntu)可能不支持 MP3 文件,推荐使用 WAV 或 OGG 格式[^2]。 3. **设置音量**:通过 `pygame.mixer.music.set_volume()` 方法调整音量,值的范围是 0.0(静音)到 1.0(最大音量)[^2]。 4. **播放音乐**:调用 `pygame.mixer.music.play()` 方法开始播放音乐。参数 `loops` 决定播放次数,`-1` 表示无限循环[^2]。 5. **事件监听**:通过主循环监听用户的操作,例如关闭窗口时停止音乐并退出程序[^3]。 #### 注意事项 - 音乐文件路径需要根据实际情况修改,确保文件存在且格式兼容。 - 如果需要支持多种音频格式(如 MP3),可以考虑使用第三方库(如 `pydub` 或 `simpleaudio`)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值