python - 如何删除绘制的子弹并添加图像作为子弹一次发射子弹?
问题描述
我是编码方面的大菜鸟!我实际上有 3 件事要问!我看过一些关于使用 python 制作游戏的教程,并且从中我制作了一个游戏类型的东西!在其中我绘制了要更改为图像的子弹,并且单击即可全部发射!
import pygame
pygame.init()
class projectile(object):
def __init__(self,x,y,radius,color,facing):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.facing = facing
self.vel = 8 * facing
def draw(self,win):
pygame.draw.circle(win, self.color, (self.x,self.y), self.radius)
def redrawGameWindow():
win.blit(bg, (0,0))
man.draw(win)
for bullet in bullets:
bullet.draw(win)
pygame.display.update()
#mainloop
man = player(200, 410, 64,64)
bullets = []
run = True
while run:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for bullet in bullets:
if bullet.x < 500 and bullet.x > 0:
bullet.x += bullet.vel
else:
bullets.pop(bullets.index(bullet))
keys = pygame.key.get_pressed()
if keys[pygame.K_c]:
if man.left:
facing = -1
else:
facing = 1
if len(bullets) < 3:
bullets.append(projectile(round(man.x + man.width //2), round(man.y + man.height//2), 6, (0,0,0), facing))
if keys[pygame.K_a] and man.x > man.vel:
man.x -= man.vel
man.left = True
man.right = False
man.standing = False
elif keys[pygame.K_d] and man.x < 500 - man.width - man.vel:
man.x += man.vel
man.right = True
man.left = False
man.standing = False
else:
man.standing = True
man.walkCount = 0
if not(man.isJump):
if keys[pygame.K_SPACE]:
man.isJump = True
if man.left:
facing = -1
else:
facing = 1
man.walkCount = 0
else:
if man.jumpCount >= -8:
neg = 1
if man.jumpCount < 0:
neg = -1
man.y -= (man.jumpCount ** 2) * 0.5 * neg
man.jumpCount -= 1
else:
man.isJump = False
man.jumpCount = 8
redrawGameWindow()
pygame.quit()
解决方案
If you want to fire just 1 bullet when c is pressed, then implement a KEYDOWN
event (see pygame.event
):
while run:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
facing = -1 if man.left else 1
if len(bullets) < 3:
startPos = round(man.x + man.width //2), round(man.y + man.height//2)
bullets.append(projectile(startPos, 6, (0,0,0), facing))
# [...]
# DELETE
#if keys[pygame.K_c]:
# if man.left:
# facing = -1
# else:
# facing = 1
#
# if len(bullets) < 3:
# bullets.append(...)
The state keys[pygame.K_c]
is True
as long the key is hold down. This causes that 1 bullet is fired in every frame as long the key is pressed. The KEYDOWN
event is executed only once when a key is pressed.
推荐阅读
- excel - 基于其他表中多行 SUM 的 DAX 返回值
- r - 绘制 Logit 曲线:xy.coords(x, y) 中的错误:“x”和“y”长度不同
- c# - System.IO.File 不可调用的成员“文件”不能像方法一样使用
- javascript - React:将函数属性传递给纯子组件 - 重新渲染
- django - /admin/login/ 处的 OperationalError 没有这样的表:django_site
- javascript - 不变性应该抛出错误,但它不在字符串中
- php - 如何在 PHP 的 curl 函数中包含“压缩”参数?
- java - Cassandra 不启动:在启动期间遇到:预期变量中的 URI:[cassandra.config]。找到[cassandra.yaml]
- python - 来自 Pandas Dataframe 的 Spacy 训练数据
- c# - LINQ 查询从列表中提取包含任何关键字的所有答案