每日小游戏-创新互联
import random
import pygame
from pygame.locals import *
# 初始化初始化所有导入的PyGame模块
pygame.init()
# 设置游戏窗口宽高
W_WIDTH = 400
W_HEIGHT = 750
# 创建游戏窗口
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((200, 200, 200))
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, 20, 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:
# 设置游戏的帧速,每秒为100帧
clock.tick(100)
# 获取按键事件
pressed_keys = pygame.key.get_pressed()
# 绘制背景
screen.blit(background, (1, 1))
# 绘制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()
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
网站标题:每日小游戏-创新互联
URL链接:http://scyanting.com/article/edddh.html