为什么我的Python pygame程序启动后立即关闭?

时间:2019-04-18 17:31:57

标签: python python-3.x pygame

我正在尝试使用Pygame制作游戏。但是程序启动后立即关闭。

我按照YT的教程进行操作,并完全复制了该函数,但仍然出现错误。


代码如下:

import pygame
import sys
import random as rd

pygame.init()

width = 800
height = 600

red = (255, 0, 0)
black = (0, 0, 0)
blue = (0, 0, 255)

playerPosition = [400, 500]
playerSize = 35

enemySize = 50
enemyPosition = [rd.randint(0, width - enemySize), 0]
enemySpeed = 10

screen = pygame.display.set_mode((width, height))
title = pygame.display.set_caption("Dodge Game by Ishak")


def collision(playerPosition, enemyPosition):
    playerX = playerPosition[0]  # player x coordinate
    playerY = playerPosition[1]  # player y coordinate

    enemyX = enemyPosition[0]  # enemy x coordinate
    enemyY = enemyPosition[1]  # enemy y coordinate

    if (enemyX >= playerX and enemyX < (playerX + playerSize)) or (playerX >= enemyX and playerX < (enemyX + enemySize)):
        if (enemyY >= playerY and enemyY < (playerY + playerSize)) or (playerY >= enemyY and playerY < (enemyY + enemySize)):
            return False
    return True


clock = pygame.time.Clock()

gameOver = False
# game loop
while not gameOver:

    # QUIT
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    # keyboard
    if event.type == pygame.KEYDOWN:

        x = playerPosition[0]
        y = playerPosition[1]

        if event.key == pygame.K_RIGHT:
            x += 13
        elif event.key == pygame.K_LEFT:
            x -= 13

        playerPosition = [x, y]

    if enemyPosition[1] >= 0 and enemyPosition[1] < height:
        enemyPosition[1] += enemySpeed
    else:
        enemyPosition[0] = rd.randint(0, width - enemySize)  # sets a random postion of the enemy
        enemyPosition[1] = 0

    if collision(playerPosition, enemyPosition):
        gameOver = True

    screen.fill(black)

    pygame.draw.rect(screen, red, (playerPosition[0], playerPosition[1], playerSize, playerSize))  # player shape
    pygame.draw.rect(screen, blue, (enemyPosition[0], enemyPosition[1], enemySize, enemySize))  # enemy shape

    clock.tick(30)

    pygame.display.update()

在我添加了碰撞功能并在主游戏循环中实现了该功能后,便出现了此问题,但我无法弄清它到底出了什么问题。

1 个答案:

答案 0 :(得分:3)

这是我看到循环停止的唯一位置:

if collision(playerPosition, enemyPosition):
        gameOver = True

因此,我可以预测玩家和敌人在生成时会发生碰撞。为了确定起见,我建议打印玩家和敌人的位置,以查看它们是否确实发生冲突。