import pygame
from pygame.locals import *
import sys
import random
# 定义常量
WIDTH = 640
HEIGHT = 480
FPS = 30
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 初始化游戏
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("点方块游戏")
clock = pygame.time.Clock()
# 定义地鼠类
class Mouse(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((50, 50))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.center = (x, y)
self.speed = random.randint(1, 5)
def update(self):
self.rect.y += self.speed
if self.rect.y > HEIGHT:
self.reset()
def reset(self):
self.rect.y = -50
self.rect.x = random.randint(0, WIDTH - 50)
self.speed = random.randint(1, 5)
# 创建地鼠
all_sprites = pygame.sprite.Group()
mice = pygame.sprite.Group()
for _ in range(10):
mouse = Mouse(random.randint(0, WIDTH - 50), random.randint(0, HEIGHT - 50))
all_sprites.add(mouse)
mice.add(mouse)
# 游戏循环
running = True
score = 0
font = pygame.font.Font(None, 36)
while running:
# 处理游戏中的事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
hit_mice = [mouse for mouse in mice if mouse.rect.collidepoint(pos)]
for mouse in hit_mice:
score += 1
all_sprites.remove(mouse)
mice.remove(mouse)
# 更新地鼠位置
all_sprites.update()
# 绘制游戏界面
screen.fill(BLACK)
all_sprites.draw(screen)
text = font.render("Score: {}".format(score), True, WHITE)
screen.blit(text, (10, 10))
pygame.display.flip()
# 设置帧率
clock.tick(FPS)
# 退出游戏
pygame.quit()
sys.exit()
《祝你点的开心》
(此方块是从上到下移动,点一下加一分,没点到不扣分)
(下一个游戏:篮球游戏)