import pygame
import sys
from pygame.locals import *
class Ball(pygame.sprite.Sprite):
def __init__(self,image,position,speed):
pygame.sprite.Sprite.__init__(self) #初始化
self.image = pygame.image.load(image)#获得图片
self.image.set_colorkey((255,255,255))
self.rect = self.image.get_rect() #获得图片矩形
self.rect.left,self.rect.top = position #确定位置
self.speed = speed #获得方向
self.mask = pygame.mask.from_surface(self.image)
def mo(self):
self.rect = self.rect.move(self.speed)
class Ban(pygame.sprite.Sprite):
def __init__(self,image,position):
pygame.sprite.Sprite.__init__(self) #初始化
self.image = pygame.image.load(image)#获得图片
self.rect = self.image.get_rect() #获得图片矩形
self.rect.left,self.rect.top = position #确定位置
self.speed = [0,0] #获得方向
def tz(self):
self.rect = self.rect[0]-75,self.rect[1]-15
#定义
ball_image = "资源\\球.bmp"
ban_image = "资源\\板.bmp"
size = w,h = 600,400
im = pygame.image.load("资源\\背景.bmp")
#初始化 pygame
pygame.init()
#创建指定大小的窗口
screen = pygame.display.set_mode(size)
#设置窗口标题
pygame.display.set_caption("第一个游戏")
ball = Ball(ball_image,(350,250),[2,2])
ban = Ban(ban_image,(0,225))
group = pygame.sprite.Group()
group.add(ban)
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if pygame.sprite.spritecollide(ball,group,False,pygame.sprite.collide_mask):
ball.speed[0] = -ball.speed[0]
ball.speed[1] = -abs(-ball.speed[1])
if ball.rect.left < 0 or ball.rect.right > w:
ball.speed[0] = -ball.speed[0]
if ball.rect.top < 0 or ball.rect.bottom > h:
ball.speed[1] = -ball.speed[1]
ban.rect = pygame.mouse.get_pos()
ban.tz()
ball.mo()
screen.blit(im,(0,0))
screen.blit(ban.image,ban.rect)
screen.blit(ball.image,ball.rect)
#更新界面
pygame.display.flip()
#延时 10ms
pygame.time.delay(10)
这是代码
新建压缩(zipped)文件夹.zip
(3.89 KB, 下载次数: 4)
这是资源
路过的拿走
我想让ball碰到棕色关闭游戏
|