【问题标题】:Opening a pygame file in main from another file (mygame)从另一个文件(mygame)在 main 中打开一个 pygame 文件
【发布时间】:2017-08-05 05:29:13
【问题描述】:

所以我试图通过import mygame打开我的游戏文件,但它似乎不起作用'这是代码(我将在代码后解释更多)

import mygame
'''THI IS THE MAIN FILE'''
print("hello")
while True:

    ui = input(">>")
    if 'hello' in ui:
        print("hi!")
    if 'how are you' in ui:
        print("im fine")
    if 'game' in ui:
        mygame() 
        '''open the game'''

这是 mygame 文件(只是随机复制了一个小的 pygame 代码,因为我只想了解这是否真的可以做到)

import pygame as p,random
q=p.display
T=16
b=q.set_mode([256]*2).fill
l=[]
d=a=x=1
c=p.event.get
def mygame():
    while not(x&528or x in l):
     l=l[a!=x:]+[x]
     while a&528or a in l:a=random.randrange(512)
     b(0);[b(99,(o%T*T,o/32*T,T,T))for o in l+[a]];q.flip();p.time.wait(99);D=d
     for e in c(2):
      v=e.key-272;n=((v&2)-1)*[1,32][v<3]
      if-n-D and 0<v<5:d=n
     c();x+=d

结论:如果触发器('game')在主输入中,我只想开始游戏,但在这种情况下,当我运行主时,游戏首先在没有触发器的情况下打开。 这是包含 pygame.init() 的另一种类型的 pygame(也比上一种更容易理解)

import sys, random, time, pygame
from pygame.locals import *

def gameg():
     pygame.init()
     font1 = pygame.font.Font(None, 24)
     screen = pygame.display.set_mode((600, 500))
     pygame.display.set_caption("Bomb Catching Game")
     pygame.mouse.set_visible(False)
     game_over = True
     lives = 3
     score = 0
     game_over = True
     mouse_x = mouse_y = 0
     lead_x = 0
     pos_x = 300
     pos_y = 460
     bomb_x = random.randint(0, 500)
     bomb_y = -50
     vel_y = 0.3
     white = 255, 255, 255
     red = 220, 50, 50
     yellow = 230, 230, 50
     black = 0, 0, 0
     def print_text(font, x, y, text, color=(255, 255, 255)):
          screen = pygame.display.set_mode((600, 500))
          imgText = font.render(text, True, color)
          screen.blit(imgText, (x, y))
     while True:
          for event in pygame.event.get():
               if event.type == QUIT:
                    sys.exit()
               elif event.type == MOUSEMOTION:
                    mouse_x, mouse_y = event.pos
                    move_x, move_y = event.rel
               elif event.type == MOUSEBUTTONUP:
                    if game_over:
                         game_over = False
                         lives = 3
                         score = 0


          keys = pygame.key.get_pressed()
          if keys[K_ESCAPE]:
               sys.exit()
          if keys[pygame.K_LEFT]:
               lead_x -= 1
          if keys[pygame.K_RIGHT]:
               lead_x += 1


          screen.fill((0, 0, 100))

          if game_over:
               print_text(font1, 100, 200, "<CLICK TO PLAY>")
          else:
               #move the bomb
               bomb_y += vel_y

               #has the player missed the bomb?
               if bomb_y > 500:
                    bomb_x = random.randint(0, 500)
                    bomb_y = -50
                    lives -= 1
                    if lives == 0:
                         game_over = True
               #see if player has caught the bomb
               elif bomb_y > pos_y:
                    if bomb_x > pos_x and bomb_x < pos_x + 120:
                         score += 10
                         bomb_x = random.randint(0, 500)
                         bomb_y = -50

               #draw the bomb
               pygame.draw.circle(screen, black, (bomb_x-4, int(bomb_y)-4), 30, 0)
               pygame.draw.circle(screen, yellow, (bomb_x, int(bomb_y)), 30, 0)

               #set basket position
               pos_x = lead_x
               if pos_x < 0:
                    pos_x = 0
               elif pos_x > 500:
                    pos_x = 500
               #draw the basket
               pygame.draw.rect(screen, black, (pos_x-4, pos_y-4, 120, 40), 0)
               pygame.draw.rect(screen, red, (pos_x, pos_y, 120, 40), 0)

          #print # of lives
          print_text(font1, 0, 0, "LIVES: " + str(lives))

          #print scores
          print_text(font1, 500, 0, "SCORE: " + str(score))

          pygame.display.update()

【问题讨论】:

    标签: python function module pygame


    【解决方案1】:

    这两个 python 代码似乎都有一些问题。

    在您的 mygame.py 中,您正在调用 q.set_mode([256]*2).fill ,这会打开一个新窗口。这是在模块级别,因此当您调用模块或运行python文件时它会直接运行。

    在您的其他文件(您要从中运行游戏)中,以下代码 -

    if 'game' in ui:
        mygame() 
        '''open the game'''
    

    实际上尝试直接调用模块mygame,而不是函数'mygame()inside the modulemygame, for that you need to do -mygame.mygame()`。


    对您的代码进行一些简单的更改,以使其正常工作 -

    mygame.py

    import pygame as p,random
    def mygame():
        q=p.display
        T=16
        b=q.set_mode([256]*2).fill
        l=[]
        d=a=x=1
        c=p.event.get
        while not(x&528 or x in l):
            l=l[a!=x:]+[x]
            while a&528 or a in l:
                a=random.randrange(512)
            b(0)
            [b(99,(o%T*T,o/32*T,T,T)) for o in l+[a]]
            q.flip()
            p.time.wait(99)
            D=d
            for e in c(2):
                v=e.key-272
                n=((v&2)-1)*[1,32][v<3]
                if-n-D and 0<v<5:
                    d=n
            c()
            x+=d
        q.quit() #Quit the display at the end of the game.
    

    我对代码做了一些更改 -

    1. 将函数外的所有行添加到mygame() 函数内。
    2. 添加了关闭显示的代码 - q.quit() - 游戏结束后。
    3. 重构代码使其看起来更好一些。

    主要的python代码-

    import mygame
    '''THI IS THE MAIN FILE'''
    print("hello")
    while True:
    
        ui = input(">>")
        if 'hello' in ui:
            print("hi!")
        elif 'how are you' in ui:
            print("im fine")
        elif 'game' in ui:
            '''open the game'''
            mygame.mygame()
        elif 'exit' in ui:
            break
    

    这里几乎没有变化 -

    1. 将函数调用为 - mygame.mygame() - 而不是 mygame()
    2. 添加了elif 块,以优雅地退出游戏。否则,退出区块的唯一方法就是Ctrl+C

    编辑

    在 OP 添加的最新代码示例中,问题出在 print_text() 方法中,由于该行 - screen = pygame.display.set_mode((600, 500)) ,屏幕不断重置。

    我们不需要删除该行即可解决问题。

    【讨论】:

    • 谢谢@Anand S Kumar 我明白了,但是你如何将这个概念实际应用到我刚刚通过编辑我的原始问题发布的其他代码中?我实际上在所有函数上都使用了 def **(): 但是当我调用该函数时游戏是黑屏?为什么会这样以及如何解决?再次感谢!
    • 您能否也添加您用来调用它的代码?
    • 代码实际上与您答案中的主要代码完全相同
    • @ManopPhysics 编辑了答案以包含该内容
    猜你喜欢
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多