pygame躲敌人的游戏
#first.py
# coding=utf-8 import pygame from pygame.locals import * from sys import exit from util import * while True: pygame.init() screen = pygame.display.set_mode((WIDTH, LENGTH)) pygame.display.set_caption('be a man') star = Star([320, 320]) clock = pygame.time.Clock() group = pygame.sprite.Group() count = 0 die = False while not die: count += 1 if count > 100: count = 0 clock.tick(60) screen.fill([0, 0, 0]) screen.blit(star.image, star.rect) enemy_pos = [0, 0] if count % 8 == 0: enemy_pos[0] = randint(0, WIDTH) elif count % 8 == 1: enemy_pos[1] = randint(0, LENGTH) elif count % 8 == 2: enemy_pos = [WIDTH, randint(0, LENGTH)] elif count % 8 == 3: enemy_pos = [randint(0, WIDTH), LENGTH] if enemy_pos != [0, 0]: enemy = Enemy(enemy_pos, star.rect) group.add(enemy) group.update() group.draw(screen) star_down = pygame.sprite.spritecollide(star, group, True) if len(star_down) > 0: die = True pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() if event.type == pygame.KEYDOWN: if event.key in click: click[event.key] = STAR_V elif event.type == pygame.KEYUP: if event.key in click: click[event.key] = 0 star_move(star.rect, star.rect)
# util.py # coding=utf-8 import pygame from pygame.locals import * from random import * from math import sqrt WIDTH = 640 LENGTH = 640 STAR_V = 2.5 click = {pygame.K_LEFT:0, pygame.K_RIGHT:0, pygame.K_UP:0, pygame.K_DOWN:0} ENEMY_SPEED_MIN = 1 ENEMY_SPEED_MAX = 3 class Star(pygame.sprite.Sprite): def __init__(self, pos): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([8, 8]) self.image.fill((255, 255, 0)) self.rect = self.image.get_rect() self.rect.topleft = pos class Enemy(pygame.sprite.Sprite): def __init__(self, enemy_pos, star_pos): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([5, 5]) self.image.fill((255, 255, 255)) self.rect = self.image.get_rect() # 只是图片的大小 self.rect.topleft = enemy_pos # 这才是图片的位置 v = uniform(ENEMY_SPEED_MIN, ENEMY_SPEED_MAX) self.v = v var = sqrt((v ** 2) / ((star_pos[0] - enemy_pos[0]) ** 2 + (star_pos[1] - enemy_pos[1]) ** 2)) x = (star_pos[0] - enemy_pos[0]) * var y = (star_pos[1] - enemy_pos[1]) * var self.v_x = x self.v_y = y def update(self): if self.v == 0: print self self.rect.left += self.v_x self.rect.top += self.v_y if self.rect.left >= WIDTH or self.rect.left <= 0 or self.rect.top >= LENGTH or self.rect.top <= 0: self.kill() def star_move(star_pos, star_rect): star_x = star_pos[0] + click[pygame.K_RIGHT] - click[pygame.K_LEFT] star_y = star_pos[1] + click[pygame.K_DOWN] - click[pygame.K_UP] if star_x < 0: star_pos[0] = 0 elif star_x > WIDTH - star_rect.width: star_pos[0] = WIDTH - star_rect.width else: star_pos[0] = star_x if star_y < 0: star_pos[1] = 0 elif star_y > LENGTH - star_rect.height: star_pos[1] = LENGTH - star_rect.height else: star_pos[1] = star_y