-
效果圖如下:
彈球游戲 源代碼如下:
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)) # 小球的位置區(qū)
ball.center = random.randint(10, 500), random.randint(10, 300)
board = pygame.Rect((0, 0), (60, 10)) # 彈板的位置區(qū)
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ōu)樨摂? y = -speed
if ball.right > 600: # 小球右邊碰撞,水平方向速度變?yōu)樨摂? x = -speed
if ball.top <= 0: # 小球左邊碰撞,垂直方向速度變?yōu)檎龜? y = speed
if ball.left <= 0: # 小球左邊碰撞,水平方向速度變?yōu)檎龜? x = speed
ball.move_ip(x, y) # 增量移動小球的位置控制區(qū)
board.center = pygame.mouse.get_pos()[0], 475 # 設置彈板的位置控制區(qū)
clock.tick(50) # 每秒30次
screen.fill((255, 255, 255)) # 重畫屏幕,白色背景
pygame.draw.circle(screen, (255, 11, 122), ball.center, 10) # 屏幕上在小球位置區(qū)畫球
pygame.draw.rect(screen, (5, 5, 5), board) # 屏幕上在彈板位置區(qū)畫彈板
pygame.display.update()
pygame.quit()
