草庐IT

Python 3.3 pygame 1.9.2a0(64 位)图形窗口显示第一个图像但随后卡住

coder 2024-06-19 原文

在教室 PC 上使用 Python 2.7.3 和 Pygame,我使用命令提示符窗口(与用户交互)和图形窗口(显示静止的 .png 文件,例如电影中的照片)。游戏运行成功。

现在我想在我自己的 Windows 7 64 位 PC 上运行和增强游戏。我下载了 Python 版本 3.3.5 和 pygame-1.9.2a0.win-amd64-py3.3.exe。然后我对我的游戏代码做了两处更改,以从 Python 2.7.3 调整到 Python 3.3.5 环境: (1) 从“raw_input()”命令中删除“raw_”; (2) 删除了第一行,讲师告诉我们要使用该行,以便 Python 2.6 像以后的版本一样运行:“from future import division, absolute_import, print_function, unicode_literals”。

现在,在我的电脑上,命令提示符窗口和音频都可以正常工作。 pygame 图形窗口仅显示第一个 .png 图像。窗口顶部(pygame Logo 旁边)立即显示“(无响应)”。没有错误消息。感谢您的任何帮助。

代码如下:

# Import common modules
import pygame, pygame.mixer, os
from pygame.locals import *

# Initialize pygame, window and sound mixer
pygame.init()
screen = pygame.display.set_mode((600,450))
pygame.display.set_caption('Greatest Movie Lines')
pygame.mouse.set_visible(0)
pygame.mixer.init()

# Create and display background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))
screen.blit(background, (0,0)) 

# Initialize variables that will persist through entire game
gameRunning = True  
roundsCompleted = 0
totalRoundsAvailable = 5   
scoreSoFar = 0
quitOrContinue = 'Try another movie line?  Type y or n: '

def beginGame():
    titleDisplay = pygame.image.load('titleSlide.png')
    titleDisplay = pygame.transform.scale(titleDisplay, (600, 450))
    screen.blit(titleDisplay, (0,0)) 
    pygame.display.flip()
    sound = pygame.mixer.music.load('20fox-fanfare-w-cinemascope-ext_anewman.mp3')
    pygame.mixer.music.play()
    print('First, move the photo window rightwards and make this black window')
    print('smaller so that you can see both windows completely (no overlap).')
    print(     )
    doneFixingWindow = input('When done repositioning windows, hit enter here.')

    howToPlay = pygame.image.load('howToPlay.png')
    howToPlay = pygame.transform.scale(howToPlay, (600, 450))
    screen.blit(howToPlay, (0,0)) 
    pygame.display.flip()

    print(     )
    print('Read the instructions at right.')
    doneFixingWindow = input('Then hit enter to play!')
    print(     )

def endGame():
    endDisplay = pygame.image.load('ending.png')
    endDisplay = pygame.transform.scale(endDisplay, (600, 450))
    screen.blit(endDisplay, (0,0)) 
    pygame.display.flip()
    sound = pygame.mixer.music.load('warnerbros_fanfare.mp3')
    pygame.mixer.music.play()
    print('    ')
    print('Game over.  Thank you for playing.')
    raw_input('Hit enter to exit the game.')


def playRound(cumScoreLastRound,roundsDone):
    # Initialize variables and constants used in the game rounds
    hintUsed = False
    guessOrHint = 'Would you like to (g)uess or get a(h)int first? Type g or h:  ' 
    requestGuess = 'Guess the movie line (no commas):  '
    noKeywordsMatched = "Sorry, your guess didn't match any keywords."
    oneKeywordMatched = 'Not bad.  You got one keyword right:'
    twoKeywordsMatched = 'Pretty good!  You got two keywords right:'
    threeKeywordsMatched = 'Great! You got all three keywords:'

    # Load variables specific to this round
    fo = open("quoteData.csv","r")
    movieData = fo.readlines()
    line = movieData[roundsDone + 1]
    movie = line.split(",")
    droodle = pygame.image.load(movie[3])
    droodle = pygame.transform.scale(droodle, (600, 450))
    hint = movie[4]
    keyword1 = movie[5]
    keyword2 = movie[6]
    keyword3 = movie[7]
    answer = pygame.image.load (movie[8])
    answer = pygame.transform.scale(answer, (600, 450))

    # Initialize counters specific to this round
    keywordMatches = 0                                                  
    keyword1Yes = ' '
    keyword2Yes = ' '
    keyword3Yes = ' '   

    # Display this round's droodle 
    screen.blit(droodle, (0, 0))
    pygame.display.flip()
    print()
    print('Here is the droodle portraying a famous movie line.')

    # Give user option of hint before guessing
    playerChoice = input(guessOrHint)

    while playerChoice != 'g' and playerChoice != 'h':   # Ensure valid selection
            print('    ')
        print('Not a valid selection')
        playerChoice = input(guessOrHint)

    if playerChoice == 'h':     # Display hint if player chooses to see one
        print('    ')
        print('Hint: ',hint)
        hintUsed = True

    # Solicit and evaluate the player's guess   
    print(   )
    guess = str.lower(input(requestGuess))              

    guessParsed = guess.split() # Determine which keywords match, if any
        if word == keyword1:
            keyword1Yes = keyword1
            keywordMatches = keywordMatches + 1
        if word == keyword2:
            keyword2Yes = keyword2
            keywordMatches = keywordMatches + 1
        if word == keyword3:
            keyword3Yes = keyword3
            keywordMatches = keywordMatches + 1

    # Display and play the correct answer
    screen.blit(answer, (0, 0))
    pygame.display.flip()
    if roundsDone == 0:
        sound = pygame.mixer.Sound('casab.wav') 
        sound.play()
    elif roundsDone == 1:
        sound = pygame.mixer.Sound('oz6.wav')   
        sound.play()
    elif roundsDone == 2:
        sound = pygame.mixer.music.load('WaterfrontClass.mp3')
        pygame.mixer.music.play()       
    elif roundsDone == 3:
        sound = pygame.mixer.Sound('offer.wav') 
        sound.play()
    else:
        sound = pygame.mixer.Sound('gwtw.wav')      
        sound.play()

    # Calculate score for this round and new total score
    if keywordMatches == 0:
        scoreThisRound = 0
    if keywordMatches == 1:
        scoreThisRound = 25
    if keywordMatches == 2:
        scoreThisRound = 50
    if keywordMatches == 3:
        scoreThisRound = 100
    if hintUsed == True:
        scoreThisRound = scoreThisRound - 20
    newCumScore = cumScoreLastRound + scoreThisRound


    # Display player's result, score for round, and cumulative score
    print('    ')
    if keywordMatches == 0:
        print(noKeywordsMatched, keyword1Yes, keyword2Yes, keyword3Yes)
    if keywordMatches == 1:
        print(oneKeywordMatched, keyword1Yes, keyword2Yes, keyword3Yes)
    if keywordMatches == 2:
        print(twoKeywordsMatched, keyword1Yes, keyword2Yes, keyword3Yes)
    if keywordMatches == 3:
        print(threeKeywordsMatched, keyword1Yes, keyword2Yes, keyword3Yes)
    print('Your score for this round is ', scoreThisRound)
    print( 'Your new total score is ', newCumScore)

    return newCumScore

while gameRunning:      

    # To begin game, display title page and instructions
    if roundsCompleted == 0:
        beginGame()

    # Play the round 
    scoreSoFar = playRound(scoreSoFar,roundsCompleted)

    # Check to see if any rounds left to be played
    roundsCompleted = roundsCompleted + 1
    if roundsCompleted == totalRoundsAvailable: 
       # End game if no rounds left to play
        print()
        input('That was our last quote.  Hit enter to exit the game.')
        endGame()
        gameRunning = False

    # Ask player whether to continue 
    else:
        print('    ')
        playerContinue = input(quitOrContinue)

        while playerContinue != 'y' and playerContinue != 'n':  # Ensure valid selection
        print('    ')
        print('Not a valid selection')
        playerContinue = input(quitOrContinue)

        if playerContinue == 'n':    # End game if player wants to quit
            endGame()
            gameRunning = False

pygame.quit()

最佳答案

PyGame 是一个事件驱动的系统。如果您不使用其内部事件循环来驱动您的游戏,您仍然需要让它偶尔花一些时间来处理内部事件,例如移动或调整窗口大小。有一个专门用于此的功能:pygame.event.pump .

我认为,如果您在代码中的几个地方调用该函数(可能就在您在控制台上收集输入之前或之后),您可以让您的屏幕响应。

关于Python 3.3 pygame 1.9.2a0(64 位)图形窗口显示第一个图像但随后卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22626471/

有关Python 3.3 pygame 1.9.2a0(64 位)图形窗口显示第一个图像但随后卡住的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  5. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  6. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  7. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  8. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  9. ruby-on-rails - Rails - 从另一个模型中创建一个模型的实例 - 2

    我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案

  10. ruby - 用 Ruby 编写一个简单的网络服务器 - 2

    我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b

随机推荐