繁体   English   中英

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

[英]Why does my Python pygame program close immediately after launch?

我正在尝试使用 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()

这个问题是在我添加了碰撞函数并在主游戏循环中实现后出现的,但我无法弄清楚它有什么问题。

这是我唯一看到循环停止的地方:

if collision(playerPosition, enemyPosition):
        gameOver = True

所以我预测你的玩家和敌人在重生时会发生碰撞。 为了确定,我建议打印玩家和敌人的位置,看看他们是否确实发生了碰撞。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM