【学习记录】PYGAME实现打砖块游戏

资源下载:

https://github.com/Apress/python-pygame-raspberry-pi-game-dev-2e/tree/master/projects/bricks

代码展示:

from turtle import back
import pygame,os,sys
from pygame.locals import *


pygame.init()
fpsClock = pygame.time.Clock()

mainSurface = pygame.display.set_mode((800,600))
pygame.display.set_caption('Bricks')
black = pygame.Color(0,0,0)

'''bat init''' 
bat = pygame.image.load('bat.png')
playerY = 540
batRect = bat.get_rect()
mousex,mousey = (0,playerY)

''' ball init''' 
ball = pygame.image.load('ball.png')
ballRect = ball.get_rect()
ballStartY = 200
ballSpeed  = 3
ballServed = False
bx,by = (24,ballStartY)
sx,sy = (ballSpeed,ballSpeed)
ballRect.topleft = (bx,by)

''' brick init'''
brick  = pygame.image.load('brick.png')
bricks = []
for y in range(5):
    brickY = (y*24) +100
    for x in range(10):
        brickX = (x*31) +245
        width = brick.get_width()
        height = brick.get_height()
        rect = Rect(brickX,brickY,width,height)
        bricks.append(rect)


while True:
    mainSurface.fill(black)

    '''brick draw'''
    for b in bricks:
        mainSurface.blit(brick,b)

    '''bat and ball draw'''
    mainSurface.blit(bat,batRect)
    mainSurface.blit(ball,ballRect)
    
    '''events'''
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == MOUSEMOTION:
            mousex,mousey = event.pos
            if (mousex < 800 -55):
                batRect.topleft = (mousex,playerY)
            else:
                batRect.topleft = (800-55,playerY)
        elif event.type == MOUSEBUTTONUP and not ballServed:
            ballServed = True


    '''main game logic'''
    if ballServed:
        bx += sx
        by += sy
        ballRect.topleft = (bx,by)
    if (by <= 0):
        by = 0
        sy *= -1

    if (bx <= 0):
        bx = 0
        sx *= -1
    if (bx >= 800 -8):
        bx = 800 -8
        sx *= -1
    
    if (by >= 600 -8):
        ballServed = False
        bx,by = (24,ballStartY)
        ballSpeed = 3
        sx,sy = (ballSpeed,ballSpeed)
        ballRect.topleft=(bx,by)

    if ballRect.colliderect(batRect):
        by = playerY - 8
        sy *= -1



    '''collision detection'''
    # batHitIndex = batRect.collidelist(ballRect)
    # if batHitIndex:
    #     by += 1
    #     print('touch')
    
    brickHitIndex = ballRect.collidelist(bricks)
    if brickHitIndex >= 0:
        hb = bricks[brickHitIndex]
        mx = bx +4
        my = by+4
        if mx > hb.x + hb.width or mx< hb.x:
            sx *= -1
        else:
            sy *= -1
        del (bricks[brickHitIndex])
    
    pygame.display.update()
    fpsClock.tick(30)
    

实现截图:

参考:

《Python, Pygame, and Raspberry Pi Game Development by Sloan Kelly》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
抱歉,我是一个语言模型,不能实际运行程序。但是,我可以提供下面的代码和说明供您参考。 首先,需要导入pygame和其他必要的库: ```python import pygame import random ``` 接下来,需要定义一些常量和变量: ```python # 窗口大小 WINDOW_WIDTH = 800 WINDOW_HEIGHT = 600 # 砖块大小 BRICK_WIDTH = 60 BRICK_HEIGHT = 20 # 砖块行数和列数 BRICK_ROWS = 5 BRICK_COLS = 10 # 球的大小和速度 BALL_RADIUS = 10 BALL_SPEED = 5 # 板子的大小和速度 PADDLE_WIDTH = 100 PADDLE_HEIGHT = 10 PADDLE_SPEED = 5 # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # 初始化pygame pygame.init() # 创建窗口 window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) # 设置窗口标题 pygame.display.set_caption('打砖块') # 加载字体 font = pygame.font.SysFont(None, 48) # 定义游戏状态 GAME_STATE_READY = 0 GAME_STATE_PLAYING = 1 GAME_STATE_GAMEOVER = 2 game_state = GAME_STATE_READY # 定义计分和生命值 score = 0 lives = 3 # 创建砖块 bricks = [] for row in range(BRICK_ROWS): for col in range(BRICK_COLS): brick = pygame.Rect(col * BRICK_WIDTH, row * BRICK_HEIGHT + 50, BRICK_WIDTH, BRICK_HEIGHT) bricks.append(brick) # 创建球和板子 ball = pygame.Rect(WINDOW_WIDTH // 2 - BALL_RADIUS, WINDOW_HEIGHT // 2 - BALL_RADIUS, BALL_RADIUS * 2, BALL_RADIUS * 2) paddle = pygame.Rect(WINDOW_WIDTH // 2 - PADDLE_WIDTH // 2, WINDOW_HEIGHT - PADDLE_HEIGHT - 10, PADDLE_WIDTH, PADDLE_HEIGHT) # 设置球的速度和方向 ball_speed_x = BALL_SPEED ball_speed_y = -BALL_SPEED ``` 然后,需要定义一些函数来处理游戏逻辑: ```python def draw_ball(): pygame.draw.circle(window, WHITE, (ball.x + BALL_RADIUS, ball.y + BALL_RADIUS), BALL_RADIUS) def draw_paddle(): pygame.draw.rect(window, WHITE, paddle) def draw_bricks(): for brick in bricks: pygame.draw.rect(window, GREEN, brick) def draw_score(): score_text = font.render('Score: ' + str(score), True, WHITE) window.blit(score_text, (10, 10)) def draw_lives(): lives_text = font.render('Lives: ' + str(lives), True, WHITE) window.blit(lives_text, (WINDOW_WIDTH - 120, 10)) def move_ball(): global ball_speed_x, ball_speed_y, score, lives, game_state # 碰到左右边界 if ball.left < 0 or ball.right > WINDOW_WIDTH: ball_speed_x = -ball_speed_x # 碰到上边界 if ball.top < 0: ball_speed_y = -ball_speed_y # 碰到板子 if ball.colliderect(paddle): ball_speed_y = -BALL_SPEED ball_speed_x = random.randint(-BALL_SPEED, BALL_SPEED) # 碰到砖块 for brick in bricks: if ball.colliderect(brick): bricks.remove(brick) ball_speed_y = -ball_speed_y score += 10 # 球掉落到底部 if ball.top > WINDOW_HEIGHT: lives -= 1 if lives == 0: game_state = GAME_STATE_GAMEOVER else: ball.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2) ball_speed_x = BALL_SPEED ball_speed_y = -BALL_SPEED ball.move_ip(ball_speed_x, ball_speed_y) def move_paddle(): keys = pygame.key.get_pressed() # 左右移动板子 if keys[pygame.K_LEFT] and paddle.left > 0: paddle.move_ip(-PADDLE_SPEED, 0) if keys[pygame.K_RIGHT] and paddle.right < WINDOW_WIDTH: paddle.move_ip(PADDLE_SPEED, 0) def show_message(message): message_text = font.render(message, True, WHITE) message_rect = message_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)) window.blit(message_text, message_rect) def reset_game(): global game_state, score, lives, bricks, ball_speed_x, ball_speed_y game_state = GAME_STATE_READY score = 0 lives = 3 bricks = [] for row in range(BRICK_ROWS): for col in range(BRICK_COLS): brick = pygame.Rect(col * BRICK_WIDTH, row * BRICK_HEIGHT + 50, BRICK_WIDTH, BRICK_HEIGHT) bricks.append(brick) ball.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2) ball_speed_x = BALL_SPEED ball_speed_y = -BALL_SPEED ``` 最后,需要在主循环中调用这些函数: ```python while True: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if game_state == GAME_STATE_READY: game_state = GAME_STATE_PLAYING elif game_state == GAME_STATE_GAMEOVER: reset_game() # 清空屏幕 window.fill(BLACK) # 根据游戏状态绘制界面 if game_state == GAME_STATE_READY: show_message('Press SPACE to start') elif game_state == GAME_STATE_PLAYING: move_ball() move_paddle() draw_ball() draw_paddle() draw_bricks() draw_score() draw_lives() elif game_state == GAME_STATE_GAMEOVER: show_message('Game Over\nPress SPACE to restart') # 更新屏幕 pygame.display.update() ``` 这就是一个简单的打砖块游戏。您可以根据需要修改其中的细节和功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值