美文网首页
pygame入门实例:简单的弹球游戏

pygame入门实例:简单的弹球游戏

作者: 顺子_aba3 | 来源:发表于2021-09-30 10:40 被阅读0次
  • 效果图如下:


    弹球游戏
  • 源代码如下:

import pygame
import random

pygame.init()

screen = pygame.display.set_mode((600, 480))
pygame.display.set_caption('弹球')
clock = pygame.time.Clock()  # 频率时钟

speed = 2  # 小球速度控制参数
x, y = speed, speed

ball = pygame.Rect((0, 0), (10, 10))  # 小球的位置区
ball.center = random.randint(10, 500), random.randint(10, 300)

board = pygame.Rect((0, 0), (60, 10))  # 弹板的位置区

pygame.mouse.set_visible(False)

r = True
while r:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            r = False

    if ball.bottom>473:  # 小球下方出界,游戏结束
        r = False
    if ball.colliderect(board):  # 小球碰到弹板,垂直方向速度变为负数
        y = -speed
    if ball.right > 600:  # 小球右边碰撞,水平方向速度变为负数
        x = -speed
    if ball.top <= 0:  # 小球左边碰撞,垂直方向速度变为正数
        y = speed
    if ball.left <= 0:  # 小球左边碰撞,水平方向速度变为正数
        x = speed
    ball.move_ip(x, y)  # 增量移动小球的位置控制区
    board.center = pygame.mouse.get_pos()[0], 475  # 设置弹板的位置控制区

    clock.tick(50)  # 每秒30次

    screen.fill((255, 255, 255))  # 重画屏幕,白色背景
    pygame.draw.circle(screen, (255, 11, 122), ball.center, 10)  # 屏幕上在小球位置区画球
    pygame.draw.rect(screen, (5, 5, 5), board)  # 屏幕上在弹板位置区画弹板

    pygame.display.update()

pygame.quit()

相关文章

网友评论

      本文标题:pygame入门实例:简单的弹球游戏

      本文链接:https://www.haomeiwen.com/subject/yvqenltx.html