python 小球碰撞游戏

2023-02-14,,,

#小球和挡板要自己找照片,放在一个单独文件夹,音乐也是一样的
import pygame pygame.init()#游戏资源加载
a = 700#x轴为700
b = 800#y抽为800
sceeen = pygame.display.set_mode((a,b))#创建游戏窗口
image_ball = pygame.image.load("../image/ball.gif")#加载小球
image_ball_1 = pygame.image.load("../image/123.png")#添加挡板
font = pygame.font.SysFont("kaiti", 30)#添加字体
image_ball_rect_2 = image_ball_1.get_rect()
image_ball_rect = image_ball.get_rect()#获取矩形框
yyue= pygame.mixer.music.load("../image/Saiakoup - Crilwa.mp3")#添加背景音乐
pygame.mixer.music.play(-1)#播放音乐
still = False
key = True#如果key 为假 就结束循环
x=1
y=1
number=0
while key:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
key = False
break
if event.type == pygame.QUIT:
pygame.quit()
break # 控制小球方向键盘控制
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if x > 0:
x -= 1
if x < 0:
x += 1
if event.key == pygame.K_RIGHT:
x = x+1 if x >= 0 else x-1 if event.key == pygame.K_UP:
y = y + 1 if y >= 0 else y-1
if event.key == pygame.K_DOWN:
if y > 0:
y -= 1
if y < 0:
y += 1
if event.type == pygame.MOUSEMOTION:
if event.buttons[0] == 1:
image_ball_rect = image_ball_rect.move(event.pos[0]-image_ball_rect.x, event.pos[1]-image_ball_rect.y) image_ball_rect_2[0] = event.pos[0]
image_ball_rect_2[1] = b -90#设置挡板位置高度
sceeen.fill((255,182,193))#背景颜色 #内部逻辑
image_ball_rect = image_ball_rect.move(x, y)
if image_ball_rect.left < 0 or image_ball_rect.right > a:
x = -x
if image_ball_rect.top < 0 or image_ball_rect.bottom > b:
y = -y if not still:
image_ball_rect = image_ball_rect.move(x, y) if pygame.Rect.colliderect(image_ball_rect_2, image_ball_rect) and image_ball_rect.bottom - image_ball_rect_2.top <= 1:
y = -y
number+=1
sceeen.blit(image_ball,image_ball_rect)#更新小球
sceeen.blit(image_ball_1, image_ball_rect_2)
image_font = font.render("分为:%s" % number, True, (0, 0, 0))
sceeen.blit(image_font, (10, 10))#计分器的位置
pygame.display.update()#更新画面
#退出游戏
pygame.quit()

python 小球碰撞游戏的相关教程结束。

《python 小球碰撞游戏.doc》

下载本文的Word格式文档,以方便收藏与打印。