在课堂上使用碰撞列表

2023-12-24

我创建了一个类来创建矩形并将它们放入列表中。我不想让它们碰撞,所以我使用 collidelist 但它不起作用。矩形仍在碰撞。

我还希望矩形在击中特定点时向下移动并更改 x 位置,

我可以做到这一点,但我不确定它是否会阻止碰撞列表工作

请查看下面的代码以获取更多说明。

import pygame
import random
from pygame.locals import *
import time 
pygame.init()
a = 255,255,255
b = 0,0,0
c = 80,255,0
d = 0,125,125
r1 = (b,c,d)
r = random.choice(r1)
p_x = 500
p_y = 1399
width = 500
height = 1890

display = pygame.display.set_mode((width,height))
title = pygame.display.set_caption("Game")
clock = pygame.time.Clock()

run = False
exit_game = False

x = random.randrange(10,900)
y = random.randrange(10,900)

sy = 10
w = random.randrange(40,90)
h = random.randrange(40,90)

rectangles =[]

class Rectangle:
    def __init__(self ,color ,x,y,w,h):
        self.c = color
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.rect =pygame.Rect(self.x ,self.y ,self.w ,self.h)
        
    def draw(self):
        pygame.draw.rect(display , self.c ,(self.x ,self.y ,self.w,self.h))
        
        self.y += sy
        if self.y > height:
                self.y = -25
                self.x = random.randint(10,900)
                return self.rect
        return self.rect
                
        
    
                
            
            


for count in range(5):
    r_c = random.randint(0,255) , random.randint(0,255) , random.randint(0,255) 
    
    r_x = random.randint(10,900)
    r_y = random.randint(10,79)
    r_w = random.randint(60,100) 
    r_h = random.randint(40,80) 
    
    
    rectangle = Rectangle(r_c ,r_x,r_y,r_w,r_h)
    rectangles.append(rectangle)

    
    
    
    

while not run:
    display.fill(a)
    p =pygame.draw.rect(display,c,(p_x ,p_y ,56,56))
    
    

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit_game = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                p_x -= 60
            if event.key == pygame.K_p:
                p_x += 60
                
    for rectangle in rectangles:
        if rectangle.rect.collidelist(rectangles) > -1:     
            rectangle.draw()

        

    
    pygame.display.update()
    clock.tick(60)
    

pygame.quit()
quit()
    

collidelist() https://www.pygame.org/docs/ref/rect.html#pygame.Rect.collidelist评估单个之间的碰撞pygame.Rect https://www.pygame.org/docs/ref/rect.html#pygame.Rect对象和列表pygame.Rect对象。 删除属性.x, .y, .w and .h从类中添加一个新方法更新:

class Rectangle:
    def __init__(self, color, x, y, w, h):
        self.c = color
        self.rect = pygame.Rect(x, y, w, h)
    def update(self):
        self.rect.y += sy
        if self.rect.y > height:
            self.rect.y = -25
            self.rect.x = random.randint(10,900)
    def draw(self):
        pygame.draw.rect(display, self.c, self.rect)

在碰撞测试之前,您必须生成一个列表pygame.Rect对象。由于每个矩形都在列表中,因此碰撞测试将始终至少找到一个矩形(本身)。使用collidelistall() https://www.pygame.org/docs/ref/rect.html#pygame.Rect.collidelistall并测试碰撞矩形的数量是否小于 2:

while not run:
    # [...]

    for rectangle in rectangles:
        rectangle.update()
        rectlist = [r.rect for r in rectangles]
        if len(rectangle.rect.collidelistall(rectlist)) < 2:     
            rectangle.draw()

无论如何,我建议创建不相交的矩形。初始化时:

rectangles = []        
rectlist = []           
for count in range(5):
    r_c = random.randint(0,255) , random.randint(0,255) , random.randint(0,255) 
    
    create_new = True
    while create_new:
        r_x = random.randint(10,900)
        r_y = random.randint(10,79)
        r_w = random.randint(60,100) 
        r_h = random.randint(40,80) 
        rectangle = Rectangle(r_c, r_x,r_y,r_w,r_h)
        create_new = rectangle.rect.collidelist(rectlist) > -1
    
    rectangles.append(rectangle)
    rectlist.append(rectangle.rect)

并且在方法中update班级的Rectangle:

class Rectangle:
    # [...]

    def update(self, rectangles):
        self.rect.y += sy
        if self.rect.y > height:
            rectlist = [r.rect for r in rectangles if r != self]
            self.rect.y = -25
            self.rect.x = random.randint(10,900)
            while self.rect.collidelist(rectlist) > -1:
                self.rect.x = random.randint(10,900)

完整示例:

import pygame
import random
from pygame.locals import *
import time 
pygame.init()
a = 255,255,255
b = 0,0,0
c = 80,255,0
d = 0,125,125
r1 = (b,c,d)
r = random.choice(r1)
p_x = 500
p_y = 1399
width = 500
height = 1890

display = pygame.display.set_mode((width,height))
title = pygame.display.set_caption("Game")
clock = pygame.time.Clock()

run = False
exit_game = False

sy = 10

class Rectangle:
    def __init__(self, color, x, y, w, h):
        self.c = color
        self.rect = pygame.Rect(x, y, w, h)

    def update(self, rectangles):
        self.rect.y += sy
        if self.rect.y > height:
            rectlist = [r.rect for r in rectangles if r != self]
            self.rect.y = -25
            self.rect.x = random.randint(10,900)
            while self.rect.collidelist(rectlist) > -1:
                self.rect.x = random.randint(10,900)
    
    def draw(self):
        pygame.draw.rect(display, self.c, self.rect)

rectangles = []        
rectlist = []           
for count in range(5):
    r_c = random.randint(0,255) , random.randint(0,255) , random.randint(0,255) 
    
    create_new = True
    while create_new:
        r_x = random.randint(10,900)
        r_y = random.randint(10,79)
        r_w = random.randint(60,100) 
        r_h = random.randint(40,80) 
        rectangle = Rectangle(r_c, r_x,r_y,r_w,r_h)
        create_new = rectangle.rect.collidelist(rectlist) > -1
    
    rectangles.append(rectangle)
    rectlist.append(rectangle.rect)

while not run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit_game = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                p_x -= 60
            if event.key == pygame.K_p:
                p_x += 60
                
    for rectangle in rectangles[:]:
        rectangle.update(rectangles)
    
    display.fill(a)
    p = pygame.draw.rect(display,c,(p_x ,p_y ,56,56))
    for rectangle in rectangles:
        rectangle.draw()
    pygame.display.update()
    clock.tick(60)
    
pygame.quit()
quit()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在课堂上使用碰撞列表 的相关文章

  • 分配列表的多个值

    我很想知道是否有一种 Pythonic 方式将列表中的值分配给元素 为了更清楚 我要求这样的事情 myList 3 5 7 2 a b c d something myList So that a 3 b 5 c 7 d 2 我正在寻找比手
  • 如何使用我自己的自定义表单覆盖 django-rest-auth 中的表单?

    我正在使用 django rest auth 并尝试通过覆盖表单的方法之一来修复密码重置视图中的错误 尽管我已经使用不同的 django rest auth 表单成功完成了类似的操作 但我无法让它在这个表单上工作 无论我做什么 都会使用旧的
  • 在 Jupyter Notebook 中设置环境变量的不同方法

    在某些情况下 我在 Windows 10 计算机上使用 Jupyter 笔记本 我想通过设置环境变量 GOOGLE APPLICATION CREDENTIALS 来向 GCP 进行身份验证 我想知道 这两种设置环境变量的方式有什么区别 当
  • 绝对导入不起作用,但相对导入起作用

    这是我的应用程序结构 foodo setup py foodo init py foodo py models py foodo foodo foodo py从导入类models py module from foodo models im
  • Django 查询:“datetime + delta”作为表达式

    好吧 我的问题如下 假设我有下一个模型 这是一个简单的情况 class Period models Model name CharField field specs here start date DateTimeField field s
  • 如何使用 python、openCV 计算图像中的行数

    我想数纸张 所以我正在考虑使用线条检测 我尝试过一些方法 例如Canny HoughLines and FLD 但我只得到处理过的照片 我不知道如何计算 有一些小线段就是我们想要的线 我用过len lines or len contours
  • 在 PhotoImage 下调整图像大小

    我需要调整图像大小 但我想避免使用 PIL 因为我无法使其在 OS X 下工作 不要问我为什么 无论如何 因为我对 gif pgm ppm 感到满意 所以 PhotoImage 类对我来说没问题 photoImg PhotoImage fi
  • 如何调试 numpy 掩码

    这个问题与this one https stackoverflow com q 73672739 11004423 我有一个正在尝试矢量化的函数 这是原来的函数 def aspect good angle float planet1 goo
  • 如何在 numpy 数组中查找并保存重复的行?

    我有一个数组 例如 Array 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 1 1 1 2 2 2 我想要输出以下内容的东西 Repeated 1 1 1 2 2 2 保留重复行的数量也可以 例如 Repeated 1 1
  • 将多索引转换为行式多维 NumPy 数组。

    假设我有一个类似于以下示例的 MultiIndex DataFrame多索引文档 http pandas pydata org pandas docs stable advanced html gt gt gt df 0 1 2 3 fir
  • 从字典中绘制直方图

    我创建了一个dictionary计算 a 中出现的次数list每个键的内容 我现在想绘制其内容的直方图 这是我想要绘制的字典的内容 1 27 34 1 3 72 4 62 5 33 6 36 7 20 8 12 9 9 10 6 11 5
  • Django Web 应用程序中的 SMTP 问题

    我被要求向使用 Django Python 框架实现的现有程序添加一个功能 此功能将允许用户单击一个按钮 该按钮将显示一个小对话框 表单以输入值 我确实编写了一些代码 显示电子邮件已发送的消息 但实际上 它没有发送 My code from
  • 一个类似 dict 的 Python 类

    我想编写一个自定义类 其行为类似于dict 所以 我继承自dict 不过 我的问题是 我是否需要创建一个私有的dict我的成员 init 方法 我不明白这个有什么意义 因为我已经有了dict如果我只是继承自的行为dict 谁能指出为什么大多
  • 在 pygame 中,我如何创建一个数据结构来跟踪调整大小事件和对象的坐标?

    我希望在调整屏幕大小后使鼠标事件与对象保持同步 有人告诉我需要创建一个数据结构来跟踪 调整事件大小 新坐标以匹配调整大小 如何使用简单的代数方程来完成此操作并将其集成到调整大小事件中以进行准确更新 反过来做 创建一个虚拟游戏地图 在绘制场景
  • 如何让 Streamlit 每 5 秒重新加载一次?

    我必须每 5 秒重新加载 Streamlit 图表 以便在 XLSX 报告中可视化新数据 如何实现这一目标 import streamlit as st import pandas as pd import os mainDir os pa
  • 我可以在 if 语句中使用“as”机制吗

    是否可以使用as in if类似的声明with我们使用的 例如 with open tmp foo r as ofile do something with ofile 这是我的代码 def my list rtrn lst True if
  • 异步异常处理程序:在事件循环线程停止之前不会被调用

    我正在我的异步事件循环上设置异常处理程序 但是 在事件循环线程停止之前 它似乎不会被调用 例如 考虑以下代码 def exception handler loop context print Exception handler called
  • 如何使用logging.conf文件使用RotatingFileHandler将所有内容记录到文件中?

    我正在尝试使用RotatingHandler用于 Python 中的日志记录目的 我将备份文件保留为 500 个 这意味着我猜它将创建最多 500 个文件 并且我设置的大小是 2000 字节 不确定建议的大小限制是多少 如果我运行下面的代码
  • 如何在supervisord中设置组?

    因此 我正在设置 Supervisord 并尝试控制多个进程 并且一切正常 现在我想设置一个组 以便我可以启动 停止不同的进程集 而不是全部或全无 这是我的配置文件的片段 group tapjoy programs tapjoy game1
  • 如何在 Qt 中以编程方式制作一条水平线

    我想弄清楚如何在 Qt 中制作一条水平线 这很容易在设计器中创建 但我想以编程方式创建一个 我已经做了一些谷歌搜索并查看了 ui 文件中的 xml 但无法弄清楚任何内容 ui 文件中的 xml 如下所示

随机推荐