6434| 6
|
[项目分享] 啊啊啊啊啊啊啊啊啊啊啊啊!!好闲呐!!!!!1! |
import random import pygame,time from pygame.locals import * # 初始化初始化所有导入的PyGame模块 pygame.init() q = 0 # 设置游戏窗口宽高 W_WIDTH = 400 W_HEIGHT = 600 # 创建游戏窗口 screen = pygame.display.set_mode((W_WIDTH, W_HEIGHT)) # 设置窗口标题 pygame.display.set_caption("别碰我!") class Player(pygame.sprite.Sprite): """玩家类""" def __init__(self): super(Player, self).__init__() self.surf = pygame.Surface((25, 25)) self.surf.fill((255, 255, 255)) self.rect = self.surf.get_rect(x=int(W_WIDTH / 2), y=50) def update(self, keys): """设置只能左右移动""" if keys[K_LEFT]: self.rect.move_ip((-5, 0)) self.rect.left = 0 if self.rect.left <= 0 else self.rect.left if keys[K_RIGHT]: self.rect.move_ip((5, 0)) self.rect.right = W_WIDTH if self.rect.right >= W_WIDTH else self.rect.right class Enemy(pygame.sprite.Sprite): """敌人类""" def __init__(self): super(Enemy, self).__init__() self.surf = pygame.Surface((25, 25)) self.surf.fill((68, 236, 44)) self.rect = self.surf.get_rect(x=random.randint(0, W_WIDTH), y=W_HEIGHT) self.speed = random.randint(5, 10) def update(self): self.rect.move_ip((0, -self.speed)) if self.rect.bottom <= 0: self.kill() # 创建游戏背景 Surface background = pygame.Surface((W_WIDTH, W_HEIGHT)) background.fill((0, 0, 0)) # 创建users 玩家Group 以及 enemys 敌人Group enemys = pygame.sprite.Group() users = pygame.sprite.Group() player = Player() users.add(player) # 设置自定义事件 ADDENEMY = USEREVENT + 1 # 设置定时器每250ms生成一次自定义事件 pygame.time.set_timer(ADDENEMY, 250) running = True # 控制游戏执行的速度 clock = pygame.time.Clock() while running: # 设置游戏的帧速,每秒为60帧 clock.tick(60) # 获取按键事件 pressed_keys = pygame.key.get_pressed() # 绘制背景 screen.blit(background, (0, 0)) # 绘制users Group for user in users: screen.blit(user.surf, user.rect) player.update(pressed_keys) # 绘制enemys Group for enemy in enemys: screen.blit(enemy.surf, enemy.rect) enemy.update() # 监听事件 for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False elif event.type == QUIT: running = False elif event.type == ADDENEMY: new_enemy = Enemy() enemys.add(new_enemy) # print(enemys) # 碰撞检测 if pygame.sprite.spritecollideany(player, enemys): player.kill() print("GAME OVER!!!!") running = False # 更新屏幕 pygame.display.flip() |
© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed