本文介绍了Pygame - 尝试射击时崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 Python 并想用 Pygame 练习.我目前使用 Python 3.6.5 并在 Atom 1.27.2 中运行代码并安装了 atom-runner 包.我一直在关注 Youtube 上 Pygame 的 KidsCanCode 教程.

I am trying to learn Python and wanted to practice with Pygame. I am currently using Python 3.6.5 and running the code in Atom 1.27.2 and installed the atom-runner package. I have been following the KidsCanCode tutorial for Pygame on Youtube.

我想更改代码,所以我不只是复制教程.目前一切正常,直到我试图从我的船上产生一颗子弹.子弹应该从左到右,从屏幕左侧的船中产生.程序加载后,所有船只都按预期移动并发生碰撞,但是当我点击空格键时,游戏崩溃并显示以下错误:

I wanted to change the code around so I am not just copying the tutorial. At the moment everything works until I try to spawn a bullet from my ship. The bullet is supposed to go from the left to right, spawning from the ship on the left side of the screen. Once the program loads all ships are moving as expected with collisions working, however when I hit space bar the game crashes with the following error:

TypeError: add() argument after * must be an iterable, not int

我认为这与我的 player.shoot 功能有关,但如果我删除该功能并尝试在下面生成子弹...

I thought it has to do with my player.shoot function but if I remove the function and try to spawn the bullet under...

if event.key == pg.K_SPACE:

还是不行.

我有与视频中的代码类似的代码,但它似乎仍然不起作用.也许这与我对子弹的 .rect 位置有关,但在这一点上我不太确定.任何帮助将不胜感激.

I have the code similar to the code on the video but it still doesn't seem to work. Maybe it has to do with my .rect positions for the bullet, but at this point I am not really sure. Any help would be appreciated.

import pygame as pg
import random
import os

WIDTH = 1200
HEIGHT = 700
FPS = 60

#-----define colors-----
WHITE = (255,255,255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# set up assets folders
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, 'graphics')

pg.init()
pg.mixer.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption('First Game')
clock = pg.time.Clock()

# ------Load graphics-------------
player_img = pg.image.load(os.path.join(img_folder, 'blueship1.png')).convert()
enemy1_img = pg.image.load(os.path.join(img_folder, 'enemy1.png')).convert()


# ------------ Sprite for the player---------
class Player(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.transform.scale(player_img, (80, 60))
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()
        self.rect.midleft =  (0, HEIGHT / 2)
        self.speedx = 0
        self.speedy = 0

    def update(self):
        self.rect.x += self.speedx
        self.speedy = 0
        keystate = pg.key.get_pressed()
        if keystate[pg.K_UP]:
            self.speedy = -5
        if keystate[pg.K_DOWN]:
            self.speedy = 5
        self.rect.y += self.speedy
        if self.rect.bottom > HEIGHT:
            self.rect.bottom = HEIGHT
        if self.rect.top < 0:
            self.rect.top = 0

    def shoot(self):
        laser = laser1(self.rect.midright, self.rect.centery)
        all_sprites.add(laser)
        lasers.add(laser)

class Enemy1(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.transform.scale(enemy1_img, (80, 60))
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()
        self.rect.y = random.randrange(HEIGHT - self.rect.height)
        self.rect.x = random.randrange(WIDTH + 40, WIDTH + 100)
        self.speedx = random.randrange(-8, -1)
    def update(self):
        self.rect.x += self.speedx
        if self.rect.right < 0:
            self.rect.y = random.randrange(HEIGHT - self.rect.height)
            self.rect.x = random.randrange(WIDTH + 40, WIDTH + 100)
            self.speedx = random.randrange(-8, -1)

class laser1(pg.sprite.Sprite):
    def __int__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((10, 5))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.centery = y
        self.rect.left = x
        self.speedx = 15

    def update(self):
        self.rect.x += self.speedx
        #kill at right side of screen
        if self.rect.left > WIDTH:
            self.kill()

#  ---initializes pygame and creates window---
all_sprites = pg.sprite.Group()
mobs = pg.sprite.Group()
lasers = pg.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(8):
    m = Enemy1()
    all_sprites.add(m)
    mobs.add(m)

# --------------Game loop-----------------

running = True
while running:
    # ------keep loop running at right speed-----
    clock.tick(FPS)
    # ------Process input (events)--------
    for event in pg.event.get():
        #check for closing window
        if event.type == pg.QUIT:
            running = False
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_SPACE:
                player.shoot()

    # ----------Update---------------
    all_sprites.update()

    # --------------Checking for Collisions----------------
    hits = pg.sprite.spritecollide(player, mobs, False)
    if hits:
        running = False

    # ---------Draw / render----------------
    screen.fill(BLACK)
    all_sprites.draw(screen)
    # flip after drawing
    pg.display.flip()

推荐答案

该问题是由拼写错误引起的.构造函数的名称是 __init__ 而不是 __int__

The issue is caused by a typo. The name of the constructor is __init__ rather than __int__

def __init__(self, x, y):

这篇关于Pygame - 尝试射击时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:53