import random
import pygame
from pygame.locals import *
# 初始化初始化所有導(dǎo)入的PyGame模塊
pygame.init()
# 設(shè)置游戲窗口寬高
W_WIDTH = 400
W_HEIGHT = 750
# 創(chuàng)建游戲窗口
screen = pygame.display.set_mode((W_WIDTH, W_HEIGHT))
# 設(shè)置窗口標題
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):
? """設(shè)置只能左右移動"""
? 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()
# 創(chuàng)建游戲背景 Surface
background = pygame.Surface((W_WIDTH, W_HEIGHT))
background.fill((0, 0, 0))
# 創(chuàng)建users 玩家Group 以及 enemys 敵人Group
enemys = pygame.sprite.Group()
users = pygame.sprite.Group()
player = Player()
users.add(player)
# 設(shè)置自定義事件
ADDENEMY = USEREVENT + 1
# 設(shè)置定時器每250ms生成一次自定義事件
pygame.time.set_timer(ADDENEMY, 250)
running = True
# 控制游戲執(zhí)行的速度
clock = pygame.time.Clock()
while running:
? # 設(shè)置游戲的幀速,每秒為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()
? # 監(jiān)聽事件
? 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()
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧