【问题标题】:Python application doesn't open with Pygame (python3)Python 应用程序无法使用 Pygame (python3) 打开
【发布时间】:2020-10-27 03:14:43
【问题描述】:

我正在尝试使用 Python3 和 Pygame 在我的 Mac 中构建一个蛇游戏,但是当我使用 python3 snakegame.py 运行游戏时,名为 Python 的应用程序只是在桌面上不停地上下跳跃(我假设正在加载打开),但它永远不会打开。我不确定是否必须使用Python Launcher 或其他方式打开它。谢谢!如果您需要,这是我的代码:

import pygame

def drawGrid(w, rows, surface):
    sizeBtwn = w // rows
    x = 0
    y = 0
    for l in range(rows):
        x = x + sizeBtwn
        y = y + sizeBtwn

        pygame.draw.line(surface, (255,255,255), (x,0),(x,w))
        pygame.draw.line(surface, (255,255,255), (0,y),(w,y))

def redrawWindow(surface):
    global rows, width
    surface.fill((0,0,0))
    drawGrid(width,rows, surface)
    pygame.display.update()


def main():
    global width, rows
    width = 500
    rows = 20
    win = pygame.display.set_mode((width, width))
    #s = snake((255, 0, 0), (10, 10))
    flag = True;

    clock = pygame.time.Clock()

    while flag == True:
        pygame.time.delay(50)
        clock.tick(10)
        redrawWindow(win)
    pass

main()

【问题讨论】:

  • 您是否在控制台/终端/cmd.exe 中运行它以查看错误消息?代码在 LINux 上正常工作,因此问题可能出在您的系统上。在某些系统上,如果您没有收到事件,pygame 可能会关闭。
  • 我刚刚在我的 MacOs 终端中运行了它

标签: python python-3.x macos pygame


【解决方案1】:
import pygame
pygame.init()

def drawGrid(w, rows, surface):
    sizeBtwn = w // rows
    x = 0
    y = 0
    for l in range(rows):
        x = x + sizeBtwn
        y = y + sizeBtwn

        pygame.draw.line(surface, (255,255,255), (x,0),(x,w))
        pygame.draw.line(surface, (255,255,255), (0,y),(w,y))

def redrawWindow(surface):
    global rows, width
    surface.fill((0,0,0))
    drawGrid(width,rows, surface)
    pygame.display.update()


def main():
    global width, rows
    width = 500
    rows = 20
    win = pygame.display.set_mode((width, width))
    #s = snake((255, 0, 0), (10, 10))
    flag = True;

    clock = pygame.time.Clock()

    while flag == True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                flag = False
                
        pygame.time.delay(50)
        clock.tick(10)
        redrawWindow(win)
    pass

main()

我已经更新了你的程序,使其能够退出,当我测试它时,窗口没有响应,那是因为你没有检查当前正在发生的事件。所以我添加了一个循环来检查事件,现在你的程序保持响应。

【讨论】:

  • 嘿@RocknRollDelta!感谢您为回答我的问题所做的努力!我试过按照你说的做,但是pygame窗口还是打不开……
  • 嗯,我想我知道你忘记在 pygame 之后添加 pygame.init() 的问题了。
  • 嘿!但是我应该把这个放在哪里?
  • import pygame之后
  • 我这样做了。它第一次告诉我要允许终端打开应用程序,一些偏好。所以我认为它终于奏效了,但它仍然永远在加载。
猜你喜欢
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
  • 2018-11-11
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多