- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
碰撞检测在我的游戏中有效,但我似乎找不到任何方法来增加每次子弹碰撞时移除的分数计数器。
[相关代码]
[类项目符号]
def collide(self, spriteGroup):
return pygame.sprite.spritecollide(self, spriteGroup, False)
[类对手]
def collide(self, spriteGroup):
return pygame.sprite.spritecollide(self, spriteGroup, True)
[全局]
all_sprites_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()
player = Agent()
all_sprites_list.add(player)
opponent = Opponent()
all_sprites_list.add(opponent)
[内部游戏循环]
bullet = Bullet()
Agent()
Opponent()
bullet_list.add(opponent)
# Call the update() method on all the sprites
all_sprites_list.update()
for b in bullet_list:
bullet_list.remove(b)#Otherwise it'll detect itself
b.collide(bullet_list)
bullet_list.add(b)
[Attempts] 我已经尝试将 collide 方法制作成一个 if 语句并将 1 添加到 player.score 然后返回当前代码中显示的相同内容但它开始每次添加超过 1一颗子弹与对手相撞。我还在游戏循环中尝试了相同的方法,在 b.collide(bullet_list) 上使用 if 语句,但在打印 player.score 时也返回了数字流。我尝试搜索 .collide 返回的内容,但我只能发现它被用在诸如 pygame.sprite.collide_rect 之类的命令中。我使用了 .collide,因为它在 this tutorial 中使用过。 .有没有其他方法可以做到这一点,还是我使用的命令有误?
[游戏代码]
import pygame
import time
import random
from pygame.locals import *
pygame.init()
display_width = 1002
display_height = 720
black = (0,0,0)
white = (255,255,255)
blue = (53,155,255)
gameDisplay = pygame.display.set_mode((display_width,display_height)) #creates surface/ display
clock = pygame.time.Clock() #sets a clock
bulletpicture = pygame.image.load("bullet.png")
bullet_width = 12
bullet_height = 5
blob_width = 51
blob_height = 51
class Agent(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("blob2.png").convert()
self.image.set_colorkey(white)
self.rect = self.image.get_rect()
self.score = 0
self.previous_time = pygame.time.get_ticks()
self.speed = 5
def update(self):
""" Update the player's position. """
self.movex = 0
self.movey = 0
keystate = pygame.key.get_pressed()
#set boundaries:
if self.rect.y < 0:
self.rect.y = 0
if self.rect.y > display_height - blob_height:
self.rect.y = display_height - blob_height
if self.rect.x < 0:
self.rect.x = 0
if self.rect.x > 401 - blob_width:
self.rect.x = 401 - blob_width
#player movements
if keystate[pygame.K_a]:
self.movex = -self.speed
elif keystate[pygame.K_d]:
self.movex = self.speed
if keystate[pygame.K_w]:
self.movey = -self.speed
elif keystate[pygame.K_s]:
self.movey = self.speed
if keystate[pygame.K_SPACE]:
self.shoot()
self.rect.x += self.movex
self.rect.y += self.movey
def shoot(self):
# to tell the bullet where to spawn
current_time = pygame.time.get_ticks()
# ready to fire when 500 ms have passed.
if current_time - self.previous_time > 500:
self.previous_time = current_time
all_sprites_list.add(bullet)
bullet_list.add(bullet)
class Bullet(pygame.sprite.Sprite):
""" This class represents the bullet . """
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()
self.image = pygame.image.load("bullet.png").convert()
self.image.set_colorkey(white)
self.rect = self.image.get_rect()
self.rect.x = player.rect.x + 20
self.rect.y = player.rect.y + 20
def update(self):
""" Move the bullet. """
self.rect.x += 5
def collide(self, spriteGroup):
return pygame.sprite.spritecollide(self, spriteGroup, False)
class Opponent(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("blob2.png").convert()
self.image.set_colorkey(white)
self.rect = self.image.get_rect()
self.velocity = [3, 3]
self.rect.x = display_width/1.2
self.rect.y = display_height/1.2
self.previous_time = pygame.time.get_ticks()
self.bullet_lst = []
self.lives = 3
def update(self):
self.rect.x += self.velocity[0]
self.rect.y += self.velocity[1]
if self.rect.x + blob_width > display_width or self.rect.x < 601:
self.velocity[0] = -self.velocity[0]
if self.rect.y + blob_height > display_height or self.rect.y < 0:
self.velocity[1] = -self.velocity[1]
for b in range(len(self.bullet_lst)):
self.bullet_lst[b][0] -= 6
for bullet in self.bullet_lst:
if bullet[0] < 0:
self.bullet_lst.remove(bullet)
current_time = pygame.time.get_ticks()
# ready to fire when 500 ms have passed.
if current_time - self.previous_time > 600:
self.previous_time = current_time
self.bullet_lst.append([self.rect.x + 25, self.rect.y + 24])
def collide(self, spriteGroup):
return pygame.sprite.spritecollide(self, spriteGroup, True)
all_sprites_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()
player = Agent()
all_sprites_list.add(player)
opponent = Opponent()
all_sprites_list.add(opponent)
done = False
while not done:
x = (display_width * 0.08)
y = (display_height * 0.2)
# --- Event Processing
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic
bullet = Bullet()
Agent()
Opponent()
bullet_list.add(opponent)
# Call the update() method on all the sprites
all_sprites_list.update()
for b in bullet_list:
bullet_list.remove(b)#Otherwise it'll detect itself
b.collide(bullet_list)
bullet_list.add(b)
# Calculate mechanics for each bullet
for bullet in bullet_list:
# Remove the bullet if it flies up off the screen
if bullet.rect.x > 1010:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
# --- Draw a frame
# Clear the screen
gameDisplay.fill(blue)
# Draw all the spites
all_sprites_list.draw(gameDisplay)
for bullet in opponent.bullet_lst:
gameDisplay.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0))
if bullet[0] + bullet_width < player.rect.x + blob_width and bullet[0] > player.rect.x:
if bullet[1] > player.rect.y and bullet[1] < player.rect.y + blob_height or bullet[1] + bullet_height > player.rect.y and bullet[1] + bullet_height < player.rect.y + blob_height:
opponent.bullet_lst.remove(bullet)
opponent.lives -= 1
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 20 frames per second
clock.tick(60)
最佳答案
使用 pygame.sprite.spritecollide
查看哪些子弹与对手相撞:collided_bullets = pygame.sprite.spritecollide(opponent, bullet_list, True)
.它返回一个碰撞子弹列表,您可以使用 for 循环对其进行迭代以增加分数并减少生命(每个碰撞子弹一次)。
编辑:如果对手应该被移除并且同时有很多对手,最好使用 pygame.sprite.groupcollide
。并将对手组和子弹组作为参数传递。 groupcollide
返回一个字典,其中碰撞的对手作为键,列表中的子弹作为值。一旦lives
对手的用完了,kill
调用方法将其从 all_sprites
中删除和 opponent
团体。
这是一个最小的完整示例:
import pygame
pygame.init()
display_width = 1002
display_height = 720
blue = (53,155,255)
gameDisplay = pygame.display.set_mode((display_width,display_height))
clock = pygame.time.Clock()
bulletpicture = pygame.Surface((12, 5))
bulletpicture.fill((20, 30, 20))
class Bullet(pygame.sprite.Sprite):
"""This class represents the bullet."""
def __init__(self, pos):
super().__init__()
self.image = bulletpicture
self.rect = self.image.get_rect(center=pos)
def update(self):
"""Move the bullet."""
self.rect.x += 5
# Remove the bullet if it flies up off the screen
if self.rect.x > display_width+12:
self.kill() # Remove the sprite from all sprite groups.
class Opponent(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((30, 50))
self.image.fill((250, 130, 20))
self.rect = self.image.get_rect()
self.rect.x = display_width/1.2
self.rect.y = display_height/1.2
self.lives = 3
def update(self):
if self.lives <= 0:
self.kill() # Remove the sprite from all sprite groups.
all_sprites_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()
opponents = pygame.sprite.Group()
opponent = Opponent()
all_sprites_list.add(opponent)
opponents.add(opponent)
score = 0
done = False
while not done:
# --- Event Processing
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# Click a mouse button to instantiate a bullet.
bullet = Bullet(event.pos)
bullet_list.add(bullet)
all_sprites_list.add(bullet)
# --- Game logic
# Call the update() method on all the sprites.
all_sprites_list.update()
# Check which bullets have collided with the opponents.
collided_opponents = pygame.sprite.groupcollide(opponents, bullet_list, False, True)
for opponent, bullets in collided_opponents.items():
for bullet in bullets:
score += 1 # Increment the score.
opponent.lives -= 1 # Decrement the lives.
pygame.display.set_caption(str(score))
# --- Draw a frame
gameDisplay.fill(blue)
all_sprites_list.draw(gameDisplay)
pygame.display.flip()
clock.tick(60)
关于python - Pygame 在使用 .collide() 时增加玩家分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49707919/
我有一个 freelook 相机,并添加了 Cinemachine Collider 的扩展。我已将场景中的所有结构设置到 CameraCollider 层中,在扩展的障碍物检测下的“碰撞”选项中选择
我做了一些研究,但找不到最有效的答案,盒对撞机 2D 还是圆形对撞机 2D? 有this question很快就得到了一个很好的答案,其中说最快的是球体对撞机,其次是胶囊对撞机,然后是盒子对撞机,但我
我有两个 ImageView,我想知道是否有任何方法可以编写某种 if 语句来检查两个图像是否相互“碰撞”,谢谢。 最佳答案 你可以通过制作两类玩家来做到这一点 public class Player
所以我一直在使用 VideoJS 设置自己的流媒体页面,我现在想要的只是并排聊天,在本例中是一个 Twitch 聊天 iframe。 This is what I have now . 问题是聊天框下
在 2D 游戏中,我的功能是检测 Sprite 是否位于圆圈范围内。但是,它没有这样做。 下面的代码简单地遍历了构成圆轮廓的所有点(每个点都有一个 x 和 y 坐标)。然后它将圆分成 4 个大小相等的
我在使用“Unity in Action”一书时偶然发现了一个问题。在第 3 章结束时,您将了解简单 fps 游戏的基础知识。它基本上是一个简单而小的水平的播放器(连接到它的相机),它只存在于形成墙壁
我正在尝试制作一款类似打砖 block 的游戏,但现在我遇到了碰撞问题。像往常一样,积木是矩形(在我的例子中是正方形),球是圆形,所以都是关于轴对齐的边界框。 到目前为止,我已经掌握了简单的碰撞检测算
团结 我创建了两个碰撞器效果,并希望它们在相互碰撞时可以发挥某些作用。但我不知道如何制作两个粒子对撞机。如何让火与水相撞,水能灭火。感谢帮助!!!! 最佳答案 来自文档 ( http://docs.u
谁能告诉我如何设置壁对撞机?我已经使用 OBJ 文件为墙壁设置了一个房间。非常感谢。 最佳答案 看看 Don McCurdy 的“Walls”示例的源代码: https://sandbox.donmc
我正在为 WCF 服务构建自定义 UserNamePasswordValidator。我正在将服务与 Autofac + WCF/ Multi-Tenancy 连接起来,所有这些都很好地结合在一起。但
使用 python 和 pygame 编码和创建游戏的新手。游戏类似于《Flappy Bird》,但在太空中,管道是 meteor 。 正在努力在 Sprite 碰撞时创建一个事件,但 pygame.
我正在通读 this example基于 C++ 的 QT 项目。定义了一个名为 Mouse 的类(在文件 mouse.h 中)继承自 QGraphicsItem,该类有一个声明如下的方法: prot
碰撞检测在我的游戏中有效,但我似乎找不到任何方法来增加每次子弹碰撞时移除的分数计数器。 [相关代码] [类项目符号] def collide(self, spriteGroup): retur
我目前在 Android 的 2D 游戏中工作。我的场景中有一个玩家,如果用户倾斜他的设备,玩家对象就会在地面上移动。但他只是从左侧和右侧移出屏幕。我试图做一堵“墙”,但没有成功。在我的玩家游戏对象处
关闭。这个问题需要details or clarity .它目前不接受答案。 想改进这个问题吗? 通过 editing this post 添加细节并澄清问题. 关闭 7 年前。 Improve t
我想在我的车轮上添加一个车轮碰撞器,但它带有 90 度旋转。 这是图片: 如何将对撞机调整到车轮? 最佳答案 为了进一步引用,我将我的评论写下来作为答案。 我能想到的最简单的解决方案是;添加一个空的
我正在努力使用 P5.play 引擎将我的决赛的所有组件组合在一起,虽然我在设置迷你游戏的各个方面取得了一些进展,但我在碰撞方面遇到了困难。这应该很容易,但无论出于何种原因,当我设置两个对象(鱼和垃圾
if (colliderBox.isTouching (col) && col.CompareTag("barrier")) { score++; this.GetCo
if (colliderBox.isTouching (col) && col.CompareTag("barrier")) { score++; this.GetCo
我正在制作一个非常简单的游戏,小鸟(玩家)必须躲避岩石,如果它被岩石击中,你就输了。我正在尝试使用 pygame.sprite.collide_rect() 来判断它们是否接触过,但我似乎无法弄清楚如
我是一名优秀的程序员,十分优秀!