随机运动pygame

2023-12-02

我正在尝试制作一个简单的生活模拟器,我需要“细胞”在屏幕上几乎随机移动(有一些规则)。但问题是,一段时间后,它们往往会聚集在屏幕的左上角。我尝试改变很多事情,比如完全跳过规则并让它们完全随机移动,但它们仍然聚集在一起。我的代码中是否存在一些明显的问题?或者我应该以完全不同的方式做这个动作?

删除无关部分的代码:

import sys, random, pygame
from pygame.locals import *
pygame.init()

WIDTH = 640 #game window width
HEIGHT = 480 #game window height
FPS = 60 #game's speeds
Pixsize = 2
screen = pygame.display.set_mode((WIDTH, HEIGHT)) #set the game window


class cell:
    def __init__(self):
        self.x = random.randrange(10, WIDTH-10) #x position
        self.y = random.randrange(10, HEIGHT-10) #y position
        self.speed = random.randrange(2,5) #cell speed
        self.move = [None, None] #realtive x and y coordinates to move to
        self.direction = None #movement direction

    def draw(self):
        pygame.draw.rect(screen, (255,255,255), (self.x,self.y,Pixsize,Pixsize),0) #draw the cell


    def wander(self):
        directions = {"S":((-1,2),(1,self.speed)),"SW":((-self.speed,-1),(1,self.speed)),"W":((-self.speed,-1),(-1,2)),"NW":((-self.speed,-1),(-self.speed,-1)),"N":((-1,2),(-self.speed,-1)),"NE":((1,self.speed),(-self.speed,-1)),"E":((1,self.speed),(-1,2)),"SE":((1,self.speed),(1,self.speed))} #((min x, max x)(min y, max y))
        directionsName = ("S","SW","W","NW","N","NE","E","SE") #possible directions
        if random.randrange(0,5) == 2: #move about once every 5 frames
            if self.direction == None: #if no direction is set, set a random one
                self.direction = random.choice(directionsName)
            else:
                a = directionsName.index(self.direction) #get the index of direction in directions list
                b = random.randrange(a-1,a+2) #set the direction to be the same, or one next to the current direction
                if b > len(directionsName)-1: #if direction index is outside the list, move back to the start
                    b = 0
                self.direction = directionsName[b]
            self.move[0] = random.randrange(directions[self.direction][0][0],directions[self.direction][0][1]) #change relative x to a random number between min x and max x
            self.move[1] = random.randrange(directions[self.direction][1][0],directions[self.direction][1][1]) #change relative y to a random number between min y and max y
        if self.x < 5 or self.x > WIDTH - 5 or self.y < 5 or self.y > HEIGHT - 5: #if cell is near the border of the screen, change direction
            if self.x < 5:
                self.direction = "E"
            elif self.x > WIDTH - 5:
                self.direction = "W"
            elif self.y < 5:
                self.direction = "S"
            elif self.y > HEIGHT - 5:
                self.direction = "N"
            self.move[0] = random.randrange(directions[self.direction][0][0],directions[self.direction][0][1]) #change relative x to a random number between min x and max x
            self.move[1] = random.randrange(directions[self.direction][1][0],directions[self.direction][1][1]) #change relative x to a random number between min x and max x
        if self.move[0] != None: #add the relative coordinates to the cells coordinates
            self.x += self.move[0]
            self.y += self.move[1]


cells = []
for i in range(200): #generate n cells
    Cell = cell()
    cells.append(Cell)


def mainloop():
    while True:
        for event in pygame.event.get():
            if event.type== QUIT: #if pressing the X, quit the progra
                pygame.quit() #stop pygame
                sys.exit() #stop the program
        screen.fill((0,0,0)) #clear the screen;
        for i in cells: #update all cells
            i.wander()
            i.draw()
        pygame.display.update() #update display
        pygame.time.Clock().tick(FPS) #limit FPS

mainloop()

你的细胞聚集到左上角的原因是random.randrange().

The randrange()部分处理范围,根据蟒蛇 range()功能。看着range()功能,range( A, B )返回一个列表A -> B-1:

>>> for i in range( 1,10 ): print( i, end = ", " )
... 
1, 2, 3, 4, 5, 6, 7, 8, 9,

所以当你的代码执行时random.randrange(directions[self.direction][0][0],directions[self.direction][0][1]),它排除了范围中的最后一项,它看起来是“SE”。因此,它们更有可能朝其他方向前进,经过数千次迭代后,它们会移动到左上角。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

随机运动pygame 的相关文章

随机推荐

  • 声明 Javascript 函数后可以更改它吗?

    假设我有var a function return 1 是否可以改变a以便a 回报2 也许通过编辑a对象 因为每个函数都是一个对象 Update 哇 谢谢所有的回复 但是 恐怕我并不是想简单地重新分配变量 而是实际编辑现有函数 我正在思考如
  • 如何通过 React Router 传递状态?

    这是给我带来麻烦的文件 var Routers React createClass getInitialState function return userName relatives userLoggedIn function userN
  • 从 char 数组的元素中减去 'a' 是什么意思

    是什么意思a s1 i a and int a 26 0 我不确定 但它是为了将数组的每个元素初始化为 0 值 int main char s1 10010 s2 10010 cin gt gt s1 gt gt s2 int a 26 0
  • Paypal SetExpressCheckout 肥皂

    当我尝试 setExpressCheckout 时 我得到 ack success 但没有令牌返回 paypal api的版本是87 0 这里是 wsdl 链接 https www sandbox paypal com wsdl PayPa
  • Xpath 发生错误

    我想存储此网页的评论部分 http timesofindia indiatimes com india Officer who tracked major scams back in Enforcement Directorate arti
  • 数字后跟单词的正则表达式

    在 JavaScript 中 数字后跟单词的正则表达式是什么 我需要捕获数字和单词 并在计算后替换它们 以下是示例形式的条件 123 dollars gt Catch the 123 and the dollars foo bar 0 2
  • 在 3D 动画中保持相机前面可见球体的数量恒定

    我创建了一个 3D 光流动画 其中相机向球体移动 如图所示here 我想在相机前面保留相同数量的可见球体 这样 当相机向它们移动时 当一个球体位于相机后面时 另一个球体就会绘制在相机前面 为此 生成每个球体的初始坐标 x y z near
  • 每个请求都快速更改会话

    我有一个登录功能 app post doLogin function req res db users findOne username req body username function err user if err console
  • Vue - 将一个元素的宽度设置为等于另一个元素的宽度

    我正在尝试使用 Vue 动态地将最里面元素的宽度设置为等于最外面元素的宽度 div class row div class col xs 12 div class card mb 2 div class banner banner tag
  • 名称 [jdbc/mydb] 未在此上下文中绑定

    我发现这个问题已经被提出过好几次了 我也经历了所有这些问题 但我仍然无法解决我的问题 谁能帮我查明我做错了什么 当我尝试访问database jsp时收到以下错误消息 HTTP Status 500 An exception occurre
  • 用C#模拟批处理文件

    我有一个运行四个命令的批处理文件 vsinstr coverage hello exe vsperfcmd start coverage output run coverage hello vsperfcmd shutdown 如何使用 C
  • cblas_dgemv 出现意外结果

    我有一个关于 cblas dgemv 的问题 我正在尝试了解它是如何工作的 以及我可能做错了什么 我有一个数组矩阵 然后尝试读取该矩阵 RowMajor 和 ColumnMajor 我在 RowMajor 案例中得到了预期的结果 6 2 4
  • Itertools.chain.from_iterable

    谁能向我解释一下 这段代码片段到底在做什么 chained country list set itertools chain from iterable country and countrycodes set all countries
  • 处理/删除 UTF-8 从右到左覆盖字符的最佳方法是什么?

    有一个 utf 8 字符 十六进制字节 E2 80 AE 当由启用 utf 8 的系统正确处理时 在向用户显示时将显示严格反转的字符 蛇通常用来隐藏或弄乱文件扩展名 以下是此类文件名字符串的示例 an EXE called EvilFile
  • 当我尝试在 pyqt5 中运行语音识别时,程序崩溃了

    当我尝试在 pyqt5 中运行语音识别时 程序崩溃了 Sr的代码位于另一个脚本文件中 我将其导入到 pyqt5 脚本中 我用 sr 功能连接了按钮 当我按下按钮时 sr 可以工作 但两者都会崩溃 PyQt5代码 import sys fro
  • Firebird 2.1 - 简单选择

    我想合并一些数据 但一个简单的选择示例不起作用 选择现有的表工作正常 SELECT 1 as foo 信息 can t format message 13 896 message file C xxxx firebird msg not f
  • 实体核心动态 LINQ LIKE 函数未找到[关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 目前不接受答案 我正在尝试使用 ZZZ 动态 LINQ 库在我的 net core 项目中使用他们网站上的示例 但我遇到了问题 使用他们自己的 JS 小提琴也会发生
  • 获取实时 Log4J 消息

    如何获取 log4j 在监控应用程序中所有 log4j 日志的中央类中正在写入的内容 Thanks 编辑 我希望我不必从日志文件中读取它 因为它会使用更多资源 您可以自己实现Appender并使用正常配置复制其上的所有日志 log4j ro
  • 使用 iconv 进行简单的 UTF8->UTF16 字符串转换

    我想编写一个函数将 UTF8 字符串转换为 UTF16 小端 问题是 iconv函数似乎没有让您提前知道需要多少字节来存储输出字符串 我的解决方案是从分配开始2 strlen utf8 然后运行iconv在循环中 增加该缓冲区的大小real
  • 随机运动pygame

    我正在尝试制作一个简单的生活模拟器 我需要 细胞 在屏幕上几乎随机移动 有一些规则 但问题是 一段时间后 它们往往会聚集在屏幕的左上角 我尝试改变很多事情 比如完全跳过规则并让它们完全随机移动 但它们仍然聚集在一起 我的代码中是否存在一些明