将pygame转换为exe

时间:2015-01-19 03:17:00

标签: python pygame python-3.3 py2exe cx-freeze

当我尝试使用py2exe将其转换为.exe文件时,它会显示“导入错误,没有名为pygame的模块”。如何将它转换为.exe usin py2exe?如果有人可以帮助我用其他工具转换它,请告诉我。

import pygame
import spritesheet
import os.path
import math
import random
from pygame.locals import *
from SpriteStripAnim import SpriteStripAnim

# Variaveis para a interface com o utilizador
Largura = 800
Altura = 600
pontos = 0
vidas = 5
tempo = 0.5
iniciado = False

#==============================================================================#
#                  Classe para trabalhar com imagens                           #
#==============================================================================#
class ImageInfo:
    def __init__(self, center, size, radius=0, lifespan=None, animated=False):
        self.center = center
        self.size = size
        self.radius = radius
        self.lifespan = lifespan if lifespan else float('inf')
        self.animated = animated

    def get_center(self):
        return self.center

    def get_size(self):
        return self.size

    def get_radius(self):
        return self.radius

    def get_lifespan(self):
        return self.lifespan

    def get_animated(self):
        return self.animated


# Definir o caminho actual
main_dir = os.path.split(os.path.abspath(__file__))[0]

# Funcao auxiliar para o carregamento de imagens
def carregar_imagem(file):
    "carregar uma imagem, e prepara-la para o jogo"
    file = os.path.join(main_dir, 'art', file)
    try:
        surface = pygame.image.load(file)
    except pygame.error:
        raise SystemExit('Nao foi possivel carregar a imagem "%s" %s' % (file, pygame.get_error()))
    return surface.convert_alpha()

# Funcao auxiliar para o carregamento de sons
def carregar_som(file):
    file = os.path.join(main_dir, 'audio', file)
    sound = pygame.mixer.Sound(file)
    return sound


# Funcoes auxiliares para lidar com as tranformacoes
def angle_to_vector(ang):
    return [math.cos(ang), math.sin(ang)] 

def dist(p, q):
    return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)  

def rot_center(image, angle):
    """Rodar uma imagem enquanto conserva o centro e o tamanho da imagem"""
    orig_rect = image.get_rect()
    rot_image = pygame.transform.rotate(image, angle)
    rot_rect = orig_rect.copy()
    rot_rect.center = rot_image.get_rect().center
    rot_image = rot_image.subsurface(rot_rect).copy()
    return rot_image


#==============================================================================#
#                              Classe Nave                                     #
#==============================================================================#
class Nave:
    def __init__(self, pos, vel, angle, image, info):
        self.pos = [pos[0], pos[1]]
        self.vel = [vel[0], vel[1]]
        self.thrust = False
        self.angle = angle
        self.angle_vel = 0
        self.images = image
        self.image = self.images[0]
        self.image_width = self.image.get_width()
        self.image_height = self.image.get_height()
        self.original = self.image
        self.image_center = info.get_center()
        self.image_size = info.get_size()
        self.radius = info.get_radius()
        self.rect = self.image.get_rect()
        self.center_pos = [(self.pos[0] + self.image_width / 2), (self.pos[1] + self.image_height / 2)]

    def get_position(self):
        return self.pos

    def get_radius(self):
        return self.radius

    def turn(self, direction):
        self.angle_vel = direction

    def move(self, thrust):
        self.thrust = thrust
        if self.thrust:
            ship_thrust_sound.play(-1)
        else:
            ship_thrust_sound.stop()

    def shoot(self):
        global missile_group
        base_missle_speed = 6
        frente = angle_to_vector(math.radians(self.angle))
        vel = [0, 0]
        vel[0] = self.vel[0] + frente[0] * base_missle_speed
        vel[1] = self.vel[1] + -frente[1] * base_missle_speed

        pos = [0, 0]
        pos[0] = self.pos[0] + (self.radius + 5 + self.image_width / 2 * frente[0])
        pos[1] = self.pos[1] + (self.radius + 5 + self.image_height / 2 * -frente[1])

        a_missile = Sprite(pos, vel, 0, 0, missile_image, missile_info, missile_sound)
        missile_group.add(a_missile)

    def draw(self, tela):
        if self.thrust:
            self.original = self.images[1]
        else:
            self.original = self.images[0]

        tela.blit(self.image, self.pos)

    def update(self):
        #Actualizar posicao
        self.pos[0] += self.vel[0]
        self.pos[1] += self.vel[1]
        self.center_pos = [(self.pos[0] + self.image_width / 2), (self.pos[1] + self.image_height / 2)]

        # Actualizacao do atrito
        c = 0.015
        self.vel[0] *= (1 - c)
        self.vel[1] *= (1 - c)

        # Envolvimento do ecra
        if self.pos[1] + self.image_height <= self.radius:  
            self.pos[1] = self.pos[1] % Altura + self.image_height
        if self.pos[1] >= Altura:
            self.pos[1] = self.pos[1] % Altura - self.image_height

        if self.pos[0] + self.image_width <= 0:  
            self.pos[0] = self.pos[0] % Largura + self.image_width
        if self.pos[0] >= Largura:
            self.pos[0] = self.pos[0] % Largura - self.image_width

        # Acelerando para a frente
        frente = angle_to_vector(math.radians(self.angle))
        if self.thrust:
            self.vel[0] += frente[0] * 0.1
            self.vel[1] += -frente[1] * 0.1
        self.angle += self.angle_vel
        self.image = rot_center(self.original, self.angle)

#==============================================================================#
#                              Classe Sprite                                   #
#==============================================================================#
class Sprite:
    def __init__(self, pos, vel, ang, ang_vel, image, info, sound=None, strip=None):
        self.pos = [pos[0], pos[1]]
        self.vel = [vel[0], vel[1]]
        self.angle = ang
        self.angle_vel = ang_vel
        self.image = image
        self.original = self.image
        self.image_width = self.image.get_width()
        self.image_height = self.image.get_height()
        self.image_center = info.get_center()
        self.image_size = info.get_size()
        self.radius = info.get_radius()
        self.lifespan = info.get_lifespan()
        self.animated = info.get_animated()
        self.center_pos = [(self.pos[0] + self.image_width / 2), (self.pos[1] + self.image_height / 2)]
        self.age = 0
        if strip:
            self.strip = strip
            self.strip.iter()
        if sound:
            sound.stop()
            sound.play()

    def get_position(self):
        return self.pos


    def get_radius(self):
        return self.radius

    def collide(self, other_object):
        distance = dist(self.center_pos, other_object.center_pos)

        if distance > self.radius + other_object.get_radius():
            return False
        elif distance < self.radius + other_object.get_radius():
            return True

    def draw(self, tela):
        if self.animated:
            self.image = self.strip.next()
            tela.blit(self.image, self.pos)
        else:
            tela.blit(self.image, self.pos)

    def update(self):
        # Determinando a posicao
        self.pos[0] += self.vel[0]
        self.pos[1] += self.vel[1]
        self.age += 1
        self.center_pos = [(self.pos[0] + self.image_width / 2), (self.pos[1] + self.image_height / 2)]

        # Envolvimento do ecra
        if self.pos[1] + self.image_height <= self.radius:
            self.pos[1] = self.pos[1] % Altura + self.image_height
        if self.pos[1] >= Altura:
            self.pos[1] = self.pos[1] % Altura - self.image_height

        if self.pos[0] + self.image_width <= 0:
            self.pos[0] = self.pos[0] % Largura + self.image_width
        if self.pos[0] >= Largura:
            self.pos[0] = self.pos[0] % Largura - self.image_width

        #Actualizacao do Angulo e da imagem
        self.angle += self.angle_vel
        self.image = rot_center(self.original, self.angle)

        # Verificando a vida util
        if self.age < self.lifespan:
            return False
        else:
            return True

# Verificar colisao
def group_collide(group, other_object):
    for elem in set(group):
        if elem.collide(other_object):
            an_explosion = Sprite(elem.get_position(), [0, 0], 0, 0, explosion_image, explosion_info, explosion_sound,
                                  explosion_sheet)
            explosion_group.add(an_explosion)
            group.remove(elem)
            return True
    else:
        return False

# Verificar colisao da bala com o asteroide
def group_group_collide(group1, group2):
    score_add = 0
    for elem in set(group1):
        if group_collide(group2, elem):
            group1.remove(elem)
            score_add += 5
    return score_add


def process_sprite_group(group, tela):
    for elem in set(group):
        elem.draw(tela)
        is_old = elem.update()
        if is_old:
            group.remove(elem)


def score_to_range():
    global pontos
    if pontos < 50:
        return 1
    elif pontos >= 50 and pontos < 100:
        return 2
    elif pontos >= 100:
        return 4
    else:
        return 5


# Manipulador do temporizador que gera uma rocha
def rock_spawner():
    global rock_group, iniciado, nave, pontos
    rang = score_to_range()
    if len(rock_group) < 5 and iniciado:
        vel = [0, 0]
        vel[0] = random.randrange(-(rang), rang + 1)
        vel[1] = random.randrange(-(rang), rang + 1)
        x = random.randrange(0, 800)
        y = random.randrange(0, 600)

        ang = (random.randrange(-5, 11))

        a_rock = Sprite([x, y], vel, 0, ang, asteroid_image, asteroid_info)
        distance = dist(nave.get_position(), a_rock.get_position())
        if distance > 100:
            rock_group.add(a_rock)


def restart():
    global rock_group, iniciado
    iniciado = False
    for elem in set(rock_group):
        rock_group.discard(elem)


def click(pos):
    global iniciado, vidas, pontos
    center = [Largura / 2, Altura / 2]
    size = splash_info.get_size()
    inwidth = (center[0] - size[0] / 2) < pos[0] < (center[0] + size[0] / 2)
    inheight = (center[1] - size[1] / 2) < pos[1] < (center[1] + size[1] / 2)
    vidas = 5
    pontos = 0
    if (not iniciado) and inwidth and inheight:
        soundtrack.stop()
        soundtrack.play()
        iniciado = True

#==============================================================================#
#                             Menu Principal                                   #
#==============================================================================#
def main():
    # Iniciar o pygame
    pygame.init()
    tela = pygame.display.set_mode((Largura, Altura))
    pygame.display.set_caption('Rice Rocks')

    # Carregar os graficos
    ship_info = ImageInfo([45, 45], [90, 90], 35)
    ship_sheet = spritesheet.spritesheet('art/double_ship.png')
    ship_images = ship_sheet.images_at(((0, 0, 90, 90), (90, 0, 90, 90)), colorkey=(255, 255, 255))

    global explosion_info
    explosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True)
    global explosion_image, explosion_sheet
    explosion_sheet = SpriteStripAnim('art/explosion_alpha.png', (0, 0, 128, 128), 24, (255, 255, 255), True, 2)
    explosion_sheet.iter()
    explosion_image = explosion_sheet.next()

    global splash_info
    splash_info = ImageInfo([200, 150], [400, 300])
    global splash_image
    splash_image = carregar_imagem('splash.png')

    global asteroid_info
    asteroid_info = ImageInfo([45, 45], [90, 90], 40)
    global asteroid_image
    asteroid_image = carregar_imagem('asteroid_blue.png')

    global missile_info
    missile_info = ImageInfo([5, 5], [10, 10], 3, 50)
    global missile_image
    missile_image = carregar_imagem('shot2.png')

    # Caregar os sons
    global ship_thrust_sound, missile_sound, explosion_sound, soundtrack
    soundtrack = carregar_som('music.ogg')
    soundtrack.set_volume(0.5)
    missile_sound = carregar_som('shoot.wav')
    ship_thrust_sound = carregar_som('thrust.wav')
    ship_thrust_sound.set_volume(0.05)
    explosion_sound = carregar_som('explode.wav')
    explosion_sound.set_volume(0.05)

    # Inicializar a nave e outros objectos
    global nave
    nave = Nave([Largura / 2, Altura / 2], [0, 0], 0, ship_images, ship_info)
    global rock_group, missile_group, explosion_group
    explosion_group = set([])
    rock_group = set([])
    missile_group = set([])

    # Carregar o background
    debris_info = ImageInfo([320, 240], [640, 480])
    background = carregar_imagem('nebula_blue.f2014.png')
    debris_image = carregar_imagem('debris2_blue.png')

    # Inicializar a fonte e cores dos objectos, utilizando a fonte predefinida do pygame
    fontObj = pygame.font.Font(None, 50)
    white_color = pygame.Color(255, 255, 255)

    # Inicializar os objectos do jogo
    clock = pygame.time.Clock()
    pygame.time.set_timer(USEREVENT + 1, 1000)

    # Ciclo do jogo
    while 1:
        clock.tick(60)
        # Event listener
        for evento in pygame.event.get():
            if evento.type == QUIT:
                return
            if evento.type == USEREVENT + 1:
                rock_spawner()

            # Registar os controles do jogo
            if evento.type == KEYDOWN and evento.key == K_RIGHT:
                nave.turn(-5)
            if evento.type == KEYDOWN and evento.key == K_LEFT:
                nave.turn(5)
            if evento.type == KEYDOWN and evento.key == K_UP:
                nave.move(True)
            if evento.type == KEYUP and evento.key == K_UP:
                nave.move(False)
            if evento.type == KEYUP and evento.key == K_RIGHT:
                nave.turn(0)
            if evento.type == KEYUP and evento.key == K_LEFT:
                nave.turn(0)
            if evento.type == KEYUP and evento.key == K_ESCAPE:
                return
            if evento.type == KEYUP and evento.key == K_SPACE:
                nave.shoot()
            if evento.type == pygame.MOUSEBUTTONUP:
                click(pygame.mouse.get_pos())

        # Registar os controles do jogo
        nave.update()

        # Verificar colisoes com a nave
        global pontos, vidas
        if group_collide(rock_group, nave):
            vidas -= 1
        pontos += group_group_collide(missile_group, rock_group)

        # Desenhar tudo
        # Desenhar e animar o fundo
        global tempo
        tempo += 1
        wtime = (tempo / 4) % Largura
        tela.blit(background, (0, 0))
        tela.blit(debris_image, ((wtime - Largura / 2) - 320, (Altura / 2) - 240))
        tela.blit(debris_image, ((wtime + Largura / 2) - 320, (Altura / 2) - 240))

        nave.draw(tela)
        process_sprite_group(missile_group, tela)
        process_sprite_group(explosion_group, tela)
        process_sprite_group(rock_group, tela)

        # Desenhar os pontos e as vidas na camada mais externa
        tela.blit(fontObj.render("Pontos: %d" % pontos, True, white_color), (0, 0))
        tela.blit(fontObj.render("Vidas: %d" % vidas, True, white_color), (620, 0))

        # Desenhar a tela inicial se o jogo nao estiver funcionando
        if not iniciado:
            tela.blit(splash_image,
                        (Largura / 2 - (splash_info.get_size()[0] / 2), Altura / 2 - (splash_info.get_size()[1] / 2)))

        pygame.display.flip()
        if vidas == 0:
            restart()


print("Se voce esta, vendo isso, e porque o pygame foi importado com sucesso")

if __name__ == '__main__': main()][1]

2 个答案:

答案 0 :(得分:0)

以下错误:

  

“导入错误,没有名为pygame的模块”

发生

是因为您没有安装(或安装不正确)pygame模块。

如果您使用的是Python 3.3,那么您应该使用pygame 3.3。 MSI安装程序位于Bitbucket

答案 1 :(得分:0)

对python 2.7使用python 2.7和pygame。另请参阅pygame2exe的文档而不是普通的py2exe。它对我来说效果更好。 http://www.pygame.org/wiki/Pygame2exe?parent=CookBook