- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我关注这个tutorial我已将 class Opponent()
添加到 class Platform()
,如图 here 。接下来我一直在尝试将groupcollide_and_loop_for添加到完整的代码中,以便对手被子弹击中时被移除。我一直在看这个question关于在 class Opponent()
本身中使用 groupcollide。我尝试了几种方法在 while not done
中的 def main
中调用 groupcollide
但我没有得到任何结果或任何错误,它只是没有不起作用。
groupcollide_and_loop_for:
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))
import pygame
# Global constants
bulletpicture = pygame.image.load("bullet.png")
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
class Player(pygame.sprite.Sprite):
"""
This class represents the bar at the bottom that the player controls.
"""
# -- Methods
def __init__(self):
""" Constructor function """
# Call the parent's constructor
super().__init__()
# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
width = 40
height = 60
self.image = pygame.Surface([width, height])
self.image.fill(RED)
# Set a referance to the image rect.
self.rect = self.image.get_rect()
# Set speed vector of player
self.change_x = 0
self.change_y = 0
# List of sprites we can bump against
self.level = None
def update(self):
""" Move the player. """
# Gravity
self.calc_grav()
# Move left/right
self.rect.x += self.change_x
# See if we hit anything
block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
for block in block_hit_list:
# If we are moving right,
# set our right side to the left side of the item we hit
if self.change_x > 0:
self.rect.right = block.rect.left
elif self.change_x < 0:
# Otherwise if we are moving left, do the opposite.
self.rect.left = block.rect.right
# Move up/down
self.rect.y += self.change_y
# Check and see if we hit anything
block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
for block in block_hit_list:
# Reset our position based on the top/bottom of the object.
if self.change_y > 0:
self.rect.bottom = block.rect.top
elif self.change_y < 0:
self.rect.top = block.rect.bottom
# Stop our vertical movement
self.change_y = 0
def calc_grav(self):
""" Calculate effect of gravity. """
if self.change_y == 0:
self.change_y = 1
else:
self.change_y += .35
# See if we are on the ground.
if self.rect.y >= SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:
self.change_y = 0
self.rect.y = SCREEN_HEIGHT - self.rect.height
def jump(self):
""" Called when user hits 'jump' button. """
# move down a bit and see if there is a platform below us.
# Move down 2 pixels because it doesn't work well if we only move down 1
# when working with a platform moving down.
self.rect.y += 2
platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
self.rect.y -= 2
# If it is ok to jump, set our speed upwards
if len(platform_hit_list) > 0 or self.rect.bottom >= SCREEN_HEIGHT:
self.change_y = -10
# Player-controlled movement:
def go_left(self):
""" Called when the user hits the left arrow. """
self.change_x = -6
def go_right(self):
""" Called when the user hits the right arrow. """
self.change_x = 6
def stop(self):
""" Called when the user lets off the keyboard. """
self.change_x = 0
class Platform(pygame.sprite.Sprite):
""" Platform the user can jump on """
def __init__(self, width, height):
""" Platform constructor. Assumes constructed with user passing in
an array of 5 numbers like what's defined at the top of this code.
"""
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(GREEN)
self.rect = self.image.get_rect()
class Level():
""" This is a generic super-class used to define a level.
Create a child class for each level with level-specific
info. """
def __init__(self, player):
""" Constructor. Pass in a handle to player. Needed for when moving
platforms collide with the player. """
self.platform_list = pygame.sprite.Group()
self.enemy_list = pygame.sprite.Group()
self.player = player
# How far this world has been scrolled left/right
self.world_shift = 0
# Update everythign on this level
def update(self):
""" Update everything in this level."""
self.platform_list.update()
self.enemy_list.update()
def draw(self, screen):
""" Draw everything on this level. """
# Draw the background
screen.fill(BLUE)
# Draw all the sprite lists that we have
self.platform_list.draw(screen)
self.enemy_list.draw(screen)
def shift_world(self, shift_x):
""" When the user moves left/right and we need to scroll
everything: """
# Keep track of the shift amount
self.world_shift += shift_x
# Go through all the sprite lists and shift
for platform in self.platform_list:
platform.rect.x += shift_x
for enemy in self.enemy_list:
enemy.rect.x += shift_x
class Bullet(pygame.sprite.Sprite):
"""This class represents the bullet."""
def __init__(self,x,y):
super().__init__()
self.image = bulletpicture
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def update(self):
"""Move the bullet."""
self.rect.y -= 5
# Remove the bullet if it flies up off the screen
if self.rect.y < -12:
self.kill() # Remove the sprite from all sprite groups.
class Opponent(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("cowboy.png") #.convert()
self.rect = self.image.get_rect()
self.lives = 1
self.rect.x = 50
self.rect.y = 280
self.change_x = 1
self.change_y = 0
# List of sprites we can bump against
self.level = None
pass
def update(self):
if self.lives <= 0:
self.kill() # Remove the sprite from all sprite groups.
self.rect.x += self.change_x
if self.rect.x > 280:
self.change_x *= -1
self.rect.x += self.change_x
if self.rect.x < 0:
self.change_x *= -1
self.rect.x += self.change_x
pass
# Create platforms for the level
class Level_01(Level):
""" Definition for level 1. """
def __init__(self, player):
""" Create level 1. """
# Call the parent constructor
Level.__init__(self, player)
self.level_limit = -1000
# Array with width, height, x, and y of platform
level = [[210, 70, 500, 500],
[210, 70, 800, 400],
[210, 70, 1000, 500],
[210, 70, 1120, 280],
]
# Go through the array above and add platforms
for platform in level:
block = Platform(platform[0], platform[1])
block.rect.x = platform[2]
block.rect.y = platform[3]
block.player = self.player
self.platform_list.add(block)
for enemy in level:
opponent = Opponent()
opponent.rect.x = 150
opponent.rect.y = 280
opponent.player = self.player
self.enemy_list.add(opponent)
# Create platforms for the level
class Level_02(Level):
""" Definition for level 2. """
def __init__(self, player):
""" Create level 1. """
# Call the parent constructor
Level.__init__(self, player)
self.level_limit = -1000
# Array with type of platform, and x, y location of the platform.
level = [[210, 30, 450, 570],
[210, 30, 850, 420],
[210, 30, 1000, 520],
[210, 30, 1120, 280],
]
# Go through the array above and add platforms
for platform in level:
block = Platform(platform[0], platform[1])
block.rect.x = platform[2]
block.rect.y = platform[3]
block.player = self.player
self.platform_list.add(block)
def main():
""" Main Program """
pygame.init()
# Set the height and width of the screen
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Side-scrolling Platformer")
# Create the player
player = Player()
# Create all the levels
level_list = []
level_list.append(Level_01(player))
level_list.append(Level_02(player))
# Set the current level
current_level_no = 0
current_level = level_list[current_level_no]
active_sprite_list = pygame.sprite.Group()
player.level = current_level
player.rect.x = 340
player.rect.y = SCREEN_HEIGHT - player.rect.height
active_sprite_list.add(player)
# --- NEW
bullet_list = pygame.sprite.Group()
player_list = pygame.sprite.Group()
player_list.add(player)
opponent = Opponent()
opponents = pygame.sprite.Group()
opponents.add(opponent)
score = 0
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
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(player.rect.x,player.rect.y)
bullet_list.add(bullet)
active_sprite_list.add(bullet)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.jump()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and player.change_x < 0:
player.stop()
if event.key == pygame.K_RIGHT and player.change_x > 0:
player.stop()
# Update the player.
active_sprite_list.update()
# ----- The code commented below is what I tried in many ways
#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))
# Update items in the level
current_level.update()
# If the player gets near the right side, shift the world left (-x)
if player.rect.right >= 500:
diff = player.rect.right - 500
player.rect.right = 500
current_level.shift_world(-diff)
# If the player gets near the left side, shift the world right (+x)
if player.rect.left <= 120:
diff = 120 - player.rect.left
player.rect.left = 120
current_level.shift_world(diff)
# If the player gets to the end of the level, go to the next level
current_position = player.rect.x + current_level.world_shift
if current_position < current_level.level_limit:
player.rect.x = 120
if current_level_no < len(level_list)-1:
current_level_no += 1
current_level = level_list[current_level_no]
player.level = current_level
# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
current_level.draw(screen)
active_sprite_list.draw(screen)
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
# Limit to 60 frames per second
clock.tick(60)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()
if __name__ == "__main__":
main()
最佳答案
我使用print()
来查看对手
和子弹
的位置。我发现对手
永远不会改变位置。
深入研究代码后,我发现您创建了两个对手。
main()
中,您创建了opponent
,它没有添加到active_sprite_list
中,因此它不会移动,也不会显示,但你用它来检查碰撞Level_01()
中,您创建对手
,并将其添加到active_sprite_list
中,以便它移动并显示在屏幕上,但您不这样做用它来检查碰撞。因为您检查与永远不会移动的对手
的碰撞,因此它永远不会与子弹碰撞。
在main()
中你必须删除
opponent = Opponent()
opponents = pygame.sprite.Group()
opponents.add(opponent)
并使用
#opponents = level_list[current_level_no].enemy_list
opponents = current_level.enemy_list
当你改变级别时也可以使用它
current_level_no += 1
current_level = level_list[current_level_no]
#opponents = level_list[current_level_no].enemy_list
opponents = current_level.enemy_list
关于python - 群体碰撞在 Pygame 的平台滚动条上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60310351/
我在 cordova@7.1.0、cordova-ios@4.5.2 下运行。安装平台:ios 4.5.2。 我运行 npm install、bower install,然后运行 cordova
我正在使用 VSTS 构建 IOS,运行命令后出现以下错误:cordova build ios 平台“android”似乎不是有效的 cordova 平台。它缺少 API.js。不支持安卓。 Cord
您使用什么软件/Wiki 来编写和分享有关开发人员、测试人员和管理人员的规范? 你使用维基系统,如果是,你使用什么维基软件? 或者您是否使用 Sharepoint 来管理和版本规范?将 SharePo
这是一家销售完整软件套件/平台的公司的示例 www.ql2.com/technology/platform.php 我想知道这样的套件/平台是如何开发的?你必须使用J2EE吗? 我更感兴趣的是这家公司
这个问题不太可能对任何 future 的访客有帮助;它只与一个较小的地理区域、一个特定的时间点或一个非常狭窄的情况相关,通常不适用于全世界的互联网受众。如需帮助使此问题更广泛适用,visit the
我有一个连接到套接字连接的应用程序,并且该连接向我发送了很多信息..可以说每秒 300 个订单(也许更多)..我有一个类(它就像一个监听器,对某个事件(并且该事件具有顺序)接收该顺序。创建一个对象,然
我即将开始一个 Netbeans 平台的项目。有没有人推荐他们用过并觉得有用的书籍或教程? 编辑: 这是一个已经开发好的swing应用。 最佳答案 除了 NetBeans 网站上的教程外,我还喜欢这本
有没有什么好的方法可以以非特定语言的方式定义接口(interface)/类层次结构,然后以特定语言生成相应的源代码?特别是,我需要同时针对 Java 和 C# 来创建一个相当全面的 API。我记得有一
关闭。这个问题是opinion-based .它目前不接受答案。 想要改进这个问题? 更新问题,以便 editing this post 可以用事实和引用来回答它. 关闭 8 年前。 Improve
大家晚上好我使用 API 平台,我想在创建实体时自动将所有者添加到我的实体中。我创建了一个事件来覆盖 API 平台,它获取当前用户并添加它。但是我的事件永远不会发生,但它确实存在于 debug:eve
这是一个有点奇怪的元编程问题,但我意识到我的新项目不需要完整的 MVC 框架,作为一个 Rails 人,我不确定现在该使用什么。 为您提供必要功能的要点;该网站将显示静态页面,但用户将能够登录并“编辑
这两天我的信息有点过载。 我打算建立自己的网站,允许本地企业列出他们的打折商品,然后用户可以进来搜索“Abercrombie T 恤”,然后就会列出出售它们的商店。 这是一个非常棒的小项目,我真的很兴
我的任务是为产品的下一代版本评估“企业”平台。我们目前正在考虑两种“类型”的平台——RAD(工作流引擎、集成 UI、工作流“技术插件”的小核心、状态的自动持久化……),例如 SalesForce.co
我需要一个不依赖于特定语言或构建系统的依赖管理器。我研究了几个优秀的工具(Gradle、Bazel、Hunter、Biicode、Conan 等),但没有一个能满足我的要求(见下文)。我还使用了 Gi
我在 Symfony 4 Flex 应用程序中使用 API Platform v2.2.5,该应用程序由一个功能 API 和 JWT Authentication 组成。 ,一些资源默认Open AP
虽然隐私法通常不属于我们开发人员的管辖范围,但我确实认为这是一个重要的话题,因为我们开发人员应该有责任警告我们的雇主,如果他们想要的东西会违反一些法律......在这种情况下,隐私法......通常情
我已经下载了 VisualVM 源代码,并尝试使用 Netbeans 7.01 编译 Glassfish 插件。这样做会导致以下错误: C:\source\visualvm\trunk\plugins
尝试 gradle 同步后...失败并在消息对话框中显示 Missing Android platform(s) detected: 'android-26' Install missing plat
大家好!我最近开始使用 Cordova,当我运行 Cordova platform add android 时,出现以下错误。我已经成功放置了 Java 和 Android SDK 的环境变量。但 n
已关闭。这个问题是 off-topic 。目前不接受答案。 想要改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。 已关闭10 年前。 Improve th
我是一名优秀的程序员,十分优秀!