Python 将pygame转换为exe

Python 将pygame转换为exe,python,pygame,python-3.3,py2exe,cx-freeze,Python,Pygame,Python 3.3,Py2exe,Cx Freeze,当我尝试用py2exe将其转换为.exe文件时,它会显示“导入错误,没有名为pygame的模块”。如何使用py2exe将其转换为.exe?如果有人能帮我用其他工具转换,请告诉我 import pygame import spritesheet import os.path import math import random from pygame.locals import * from SpriteStripAnim import SpriteStripAnim # Variaveis pa

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

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]
导入pygame
导入spritesheet
导入操作系统路径
输入数学
随机输入
从pygame.locals导入*
从SpriteStripAnim导入SpriteStripAnim
#Variaveis para接口com o utilizador
拉古拉=800
阿尔图拉=600
庞托斯=0
vidas=5
节奏=0.5
iniciado=假
#==============================================================================#
#帕拉特拉巴尔哈尔科姆图像类#
#==============================================================================#
类别图像信息:
定义初始(自身、中心、大小、半径=0、寿命=无、动画=假):
self.center=中心
self.size=大小
自半径=半径
self.lifespan=生命周期浮动时的寿命('inf')
self.animated=已设置动画
def get_中心(自我):
返回自我中心
def get_大小(自身):
返回自身大小
def get_半径(自身):
返回自半径
def get_寿命(自我):
回归自我寿命
def设置动画(自):
返回自我动画
#卡米尼奥定义
main_dir=os.path.split(os.path.abspath(_文件__))[0]
#图像辅助功能
def carregar_图像(文件):
“carregar uma imagem,e prepara la para o jogo”
file=os.path.join(主目录'art',文件)
尝试:
surface=pygame.image.load(文件)
除了pygame.error:
raise SystemExit('Nao foi possivel CAREGAR a imagem”%s“%s%”(文件,pygame.get_error())
返回曲面。转换_alpha()
#家庭辅助服务
def carregar_som(文件):
file=os.path.join(主目录'audio',文件)
sound=pygame.mixer.sound(文件)
回音
#功能辅助激光雷达组件作为变换器
def角度到矢量(ang):
return[math.cos(ang)、math.sin(ang)]
def区(p,q):
返回math.sqrt((p[0]-q[0])**2+(p[1]-q[1])**2)
def旋转中心(图像、角度):
“Rodar uma imagem enquanto conserva o centro e o tamanho da imagem”
orig_rect=image.get_rect()
rot_image=pygame.transform.rotate(图像,角度)
rot_rect=orig_rect.copy()
rot_rect.center=rot_image.get_rect().center
rot_image=rot_image.subground(rot_rect.copy())
返回rot_图像
#==============================================================================#
#高级中堂#
#==============================================================================#
班级中堂:
定义初始(自身、位置、水平、角度、图像、信息):
self.pos=[pos[0],pos[1]]
self.vel=[vel[0],vel[1]]
自我推力=错误
自我角度=角度
自转角水平=0
self.images=图像
self.image=self.images[0]
self.image\u width=self.image.get\u width()
self.image\u height=self.image.get\u height()
self.original=self.image
self.image\u center=info.get\u center()
self.image\u size=info.get\u 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_位置(自身):
返回self.pos
def get_半径(自身):
返回自半径
def转向(自转向):
自转角水平=方向
def移动(自动、推力):
自推力=推力
如果自推:
船舶推力声音。播放(-1)
其他:
船舶推力声音。停止()
def喷射(自):
全球导弹小组
基本导弹速度=6
frente=角度到向量(数学弧度(自角度))
水平=[0,0]
等级[0]=自身等级[0]+法语[0]*基本导弹速度
等级[1]=自我等级[1]+-法语[1]*基本速度
pos=[0,0]
pos[0]=self.pos[0]+(self.radius+5+self.image\u width/2*frente[0])
位置[1]=self.pos[1]+(self.radius+5+self.image\u height/2*-frente[1])
a_飞弹=精灵(位置、音量、0、0、飞弹图像、飞弹信息、飞弹声音)
导弹组。添加(a导弹)
def提取(自我,影视处):
如果自推:
self.original=self.images[1]
其他:
self.original=self.images[0]
tela.blit(self.image,self.pos)
def更新(自我):
#萨尔波西科酒店
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)]
#阿蒂托扎曹酒店
c=0.015
self.vel[0]*=(1-c)
self.vel[1]*=(1-c)
#埃克拉恩沃维门托酒店
如果self.pos[1]+self.image\u height=Altura:
self.pos[1]=self.pos[1]%Altura-self.image\u高度
如果self.pos[0]+self.image\u width=Largura:
self.pos[0]=self.pos[0]%Largura-self.image\u宽度
#阿塞莱兰多·帕拉特
frente=角度到向量(数学弧度(自角度))
如果自推:
self.vel[0]+=frente[0]*0.1
self.vel[1]+=-frente[1]*0.1
自转角+=自转角水平
self.image=旋转中心(self.original,self.angle)
#==============================================================================#
#雪碧#
#==============================================================================#
类精灵:
定义初始(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
自转角水平=ang水平
self.image=image
自我原创