import pygame from pygame.locals import * import time import random import sys import os pygame.init() canvas = pygame.display.set_mode((1000,625)) pygame.display.set_caption("打砖块") class Ball(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image=pygame.image.load("ball.png") self.image=pygame.transform.scale(self.image,(50,50)) self.rect=self.image.get_rect() position=[100,100] self.rect.center=position self.speed=[-1,-1] def xianshi(self): canvas.blit(self.image,self.rect) def move(self): self.rect=self.rect.move(self.speed) def hit(self): if self.rect.top<=0 : self.speed[1]=-self.speed[1] self.rect=self.rect.move(self.speed) if self.rect.left<=0 or self.rect.right>=1000: self.speed[0]=-self.speed[0] self.rect=self.rect.move(self.speed) class Enemy(pygame.sprite.Sprite): def __init__(self,pos): pygame.sprite.Sprite.__init__(self) self.image=pygame.image.load("enemy.png") self.image=pygame.transform.scale(self.image,(50,30)) self.rect=self.image.get_rect() self.rect.center=pos def xianshi(self): canvas.blit(self.image,self.rect) def move(self): self.rect=self.rect.move(self.speed) bj=pygame.sprite.Group() banlist=[(50,50),(150,50),(250,50),(350,50),(450,50),(550,50),(650,50),(750,50),(850,50),(950,50), (50,100),(150,100),(250,100) , (350,100),(450,100),(550,100),(650,100),(750,100),(850,100),(950,100), (50,150),(150,150),(250,150) , (350,150),(450,150),(550,150),(650,150),(750,150),(850,150),(950,150), (50,200),(150,200),(250,200) , (350,200),(450,200),(550,200),(650,200),(750,200),(850,200),(950,200), (50,250),(150,250),(250,250) , (350,250),(450,250),(550,250),(650,250),(750,250),(850,250),(950,250), ] for i in range(50): enemy = Enemy(banlist[i]) bj.add(enemy) class Ban(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image=pygame.image.load("1.png") self.image=pygame.transform.scale(self.image,(200,20)) self.rect=self.image.get_rect() self.rect.center=(500,610) def xianshi(self): canvas.blit(self.image,self.rect) ban=Ban() def handleEvent(): for event in pygame.event.get(): if event.type == QUIT : pygame.quit() sys.exit() ball=Ball() score=0 lenl = 0 while True: canvas.fill((255, 255, 255)) ball.xianshi() ball.move() ball.hit() ban.xianshi() for e in bj: e.xianshi() keys=pygame.key.get_pressed() if keys[K_LEFT]: ban.rect.left -= 2 if ban.rect.left <= 0: ban .rect.left = 0 if keys[K_RIGHT]: ban.rect.left += 2 if ban.rect.right >= 1000: ban.rect.right = 1000 if pygame.sprite.collide_rect(ball,ban): ball.speed[1] = random.randint(-2,-1) lenl +=1 if pygame.sprite.spritecollide(ball,bj,1): score+=1 font = pygame.font.SysFont("kaiti", 40) text = font.render("分数:" +str(score)+"能量"+str(lenl),True,(0,0,0)) canvas.blit(text, (0,0)) handleEvent() pygame.display.update()标签:python,self,50,pygame,砖块,250,image,rect From: https://blog.csdn.net/rhz20131230/article/details/144276581