首先我创建一个矩形并将它放在屏幕中央
第二,我想按一个键来显示这个矩形
当我执行 bullet.bullet_move(setting)
和 bullet.draw_bullet(setting)
时没有任何反应
代码如下:
#! /usr/bin/python
import pygame as p
import sys
class Setting():
def __init__(self,width,height):
self.w=width
self.h=height
self.flag=p.RESIZABLE
self.color=(255,255,255)
self.speed=1
self.screen=p.display.set_mode((self.w,self.h),self.flag)
p.display.set_caption("Bullet")
self.bullet_s=1
self.bullet_w=100
self.bullet_h=300
self.bullet_c=(0,0,0)
class Bullet(p.sprite.Sprite):
def __init__(self,setting):
super().__init__()
self.screen_rect=setting.screen.get_rect()
self.screen_center=self.screen_rect.center
self.bullet=""
self.bullet.center=self.screen_center
self.color=setting.bullet_c
self.speed=setting.bullet_s
# self.centery=float(self.bullet.centery)
def bullet_move(self,setting):
for event in p.event.get():
if event.type == p.QUIT:
sys.exit()
elif event.type == p.KEYDOWN:
if event.key ==p.K_UP:
self.bullet=p.Rect((0,0),(setting.bullet_w,setting.bullet_h))
self.bullet.center=self.screen_center
# self.y -= self.speed
# self.bullet.y=self.y
def draw_bullet(self,setting):
p.draw.rect(setting.screen,self.color,self.bullet)
def game():
p.init()
setting=Setting(1200,800)
bullet=Bullet(setting)
while True:
bullet.bullet_move(setting)
setting.screen.fill((255,0,0))
bullet.draw_bullet(setting)
p.display.flip()
game()
最佳答案
bullet_move
是进行事件处理的错误位置。删除它!
class Bullet(p.sprite.Sprite):
def __init__(self,setting):
super().__init__()
self.screen_rect=setting.screen.get_rect()
self.screen_center=self.screen_rect.center
self.bullet=p.Rect((0,0),(setting.bullet_w,setting.bullet_h))
self.bullet.center=self.screen_center
self.color=setting.bullet_c
self.speed=setting.bullet_s
self.centery=float(self.bullet.centery)
def bullet_move(self,setting):
self.bullet.y -= self.speed
def draw_bullet(self,setting):
p.draw.rect(setting.screen,self.color,self.bullet)
创建一个项目符号列表 (bullets = []
) 并在按下 UP 时产生一个新的项目符号。创建一个项目符号并将其.append
到bullets
。可以在 for
循环中移动 (bullet_move
) 和绘制 (draw_bullet
) 子弹:
def game():
p.init()
setting=Setting(1200,800)
bullets = []
while True:
for event in p.event.get():
if event.type == p.QUIT:
sys.exit()
elif event.type == p.KEYDOWN:
if event.key == p.K_UP:
bullets.append(Bullet(setting))
for bullet in bullets:
bullet.bullet_move(setting)
setting.screen.fill((255,0,0))
for bullet in bullets:
bullet.draw_bullet(setting)
p.display.flip()
或者使用 pygame.sprite.Group
:
def game():
p.init()
setting=Setting(1200,800)
bullets = p.sprite.Group()
while True:
for event in p.event.get():
if event.type == p.QUIT:
sys.exit()
elif event.type == p.KEYDOWN:
if event.key == p.K_UP:
bullets.add(Bullet(setting))
# [...]
关于Python Pygame 按键创建矩形或任意图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58985625/