Pygame:细胞物理学

2024-05-07

我正在制作一个简化版本agar.io http://agar.io.

目前,单元格被放置在网格背景上,就像游戏中一样。细胞吃食物,但只有圆圈内较小的正方形部分实际上吃食物(在我的程序中),当你足够大时,这一点是显而易见的。此外,当您按空格键时,它会将单元格分成 2 个较小的部分,几秒钟后它们会合并回来。这需要一个KEY_UP and K_SPACE事件,但我不确定如何实施。另外,一旦你的质量达到 34 左右,你可以按 w 射击你自己的一小部分,即质量约为 14 的较小细胞。

当细胞达到一定质量时,我尝试使用一堆 if 语句来减慢细胞速度。在游戏中,速度自然减慢。Here http://www.reddit.com/r/Agario/comments/3ae9vs/math_to_eat_or_not_to_eat/ and Here http://www.reddit.com/r/Agario/comments/34x2fa/game_mechanics_explained_in_depth_numbers_and/是描述游戏中使用的数学的来源。

这是我的代码:

import pygame, sys, random
from pygame.locals import *

# set up pygame
pygame.init()
mainClock = pygame.time.Clock()

# set up the window
width = 800
height = 600
thesurface = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('')

bg = pygame.image.load("bg.png")
basicFont = pygame.font.SysFont('calibri', 36)

# set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
size = 10
playercolor = BLUE
# set up the player and food data structure
foodCounter = 0
NEWFOOD = 35
FOODSIZE = 10
player = pygame.draw.circle(thesurface, playercolor, (60, 250), 40)
foods = []
for i in range(20):
    foods.append(pygame.Rect(random.randint(0, width - FOODSIZE), random.randint(0, height - FOODSIZE), FOODSIZE, FOODSIZE))

# set up movement variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False

MOVESPEED = 10

score = 0
# run the game loop
while True:
    # check for events
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            # change the keyboard variables
            if event.key == K_LEFT or event.key == ord('a'):
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT or event.key == ord('d'):
                moveLeft = False
                moveRight = True
            if event.key == K_UP or event.key == ord('w'):
                moveDown = False
                moveUp = True
            if event.key == K_DOWN or event.key == ord('s'):
                moveUp = False
                moveDown = True
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_LEFT or event.key == ord('a'):
                moveLeft = False
            if event.key == K_RIGHT or event.key == ord('d'):
                moveRight = False
            if event.key == K_UP or event.key == ord('w'):
                moveUp = False
            if event.key == K_DOWN or event.key == ord('s'):
                moveDown = False
            if event.key == ord('x'):
                player.top = random.randint(0, height - player.height)
                player.left = random.randint(0, width - player.width)

        if event.type == MOUSEBUTTONUP:
            foods.append(pygame.Rect(event.pos[0], event.pos[1], FOODSIZE, FOODSIZE))

    foodCounter += 1
    if foodCounter >= NEWFOOD:
        # add new food
        foodCounter = 0
        foods.append(pygame.Rect(random.randint(0, width - FOODSIZE), random.randint(0, height - FOODSIZE), FOODSIZE, FOODSIZE))
    if 100>score>50:
        MOVESPEED = 9
    elif 150>score>100:
        MOVESPEED = 8
    elif 250>score>150:
        MOVESPEED = 6
    elif 400>score>250:
        MOVESPEED = 5
    elif 600>score>400:
        MOVESPEED = 3
    elif 800>score>600:
        MOVESPEED = 2
    elif score>800:
        MOVESPEED = 1
    # move the player
    if moveDown and player.bottom < height:
        player.top += MOVESPEED
    if moveUp and player.top > 0:
        player.top -= MOVESPEED
    if moveLeft and player.left > 0:
        player.left -= MOVESPEED
    if moveRight and player.right < width:
        player.right += MOVESPEED
    thesurface.blit(bg, (0, 0))

    # draw the player onto the surface
    pygame.draw.circle(thesurface, playercolor, player.center, size)

    # check if the player has intersected with any food squares.
    for food in foods[:]:
        if player.colliderect(food):
            foods.remove(food)
            size+=1
            score+=1

    # draw the food
    for i in range(len(foods)):
        pygame.draw.rect(thesurface, GREEN, foods[i])

    printscore = basicFont.render("Score: %d" % score, True, (0,0,0))
    thesurface.blit(printscore, (495, 10))

    pygame.display.update()
    # draw the window onto the thesurface
    pygame.display.update()
    mainClock.tick(80)

再次,这是我想要解决的问题。

  • 我希望按下空格键时单元格分成两部分。仅当单元格大小超过 30 时才会发生这种情况。
  • 我希望当你按 W 时,细胞能够吐出自身的一小部分。吐出的部分将是设定的 15 质量。原来的单元格会小 15。多次点击W会吐出多个小球,直到原来的细胞质量达到20,此时就无法再吐出。

编辑:我尝试过做分裂的事情:

if event.key == K_SPACE:
    pygame.draw.circle(thesurface, playercolor,(player.centerx,player.centery),int(size/2))
    pygame.draw.circle(thesurface, playercolor,(player.centerx+size,player.centery+size),int(size/2))

输入上面的代码后,运行程序并按空格键,没有任何反应。该程序的表现就像我从未按下它一样。


您将需要移动.draw调用后调用 blit 你的背景,否则它会覆盖你的玩家的圆圈。我在这里使用了一个布尔标志,然后您可以将其与计时器一起使用,以便在您想要关闭分割时进行切换:

import pygame, sys, random
from pygame.locals import *

# set up pygame
pygame.init()
mainClock = pygame.time.Clock()

# set up the window
width = 800
height = 600
thesurface = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('')

bg = pygame.image.load("bg.png")
basicFont = pygame.font.SysFont('calibri', 36)

# set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
size = 10
playercolor = BLUE
# set up the player and food data structure
foodCounter = 0
NEWFOOD = 35
FOODSIZE = 10
splitting = False
player = pygame.draw.circle(thesurface, playercolor, (60, 250), 40)
foods = []
for i in range(20):
    foods.append(pygame.Rect(random.randint(0, width - FOODSIZE), random.randint(0, height - FOODSIZE), FOODSIZE, FOODSIZE))

# set up movement variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False

MOVESPEED = 10

score = 0
# run the game loop
while True:
    # check for events
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            # change the keyboard variables
            if event.key == K_LEFT or event.key == ord('a'):
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT or event.key == ord('d'):
                moveLeft = False
                moveRight = True
            if event.key == K_UP or event.key == ord('w'):
                moveDown = False
                moveUp = True
            if event.key == K_DOWN or event.key == ord('s'):
                moveUp = False
                moveDown = True
            if event.key == K_SPACE and size >= 30: # XXX if size and space set splitting to true
                splitting = True
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_LEFT or event.key == ord('a'):
                moveLeft = False
            if event.key == K_RIGHT or event.key == ord('d'):
                moveRight = False
            if event.key == K_UP or event.key == ord('w'):
                moveUp = False
            if event.key == K_DOWN or event.key == ord('s'):
                moveDown = False
            if event.key == ord('x'):
                player.top = random.randint(0, height - player.height)
                player.left = random.randint(0, width - player.width)

        if event.type == MOUSEBUTTONUP:
            foods.append(pygame.Rect(event.pos[0], event.pos[1], FOODSIZE, FOODSIZE))

    foodCounter += 1
    if foodCounter >= NEWFOOD:
        # add new food
        foodCounter = 0
        foods.append(pygame.Rect(random.randint(0, width - FOODSIZE), random.randint(0, height - FOODSIZE), FOODSIZE, FOODSIZE))
    if 100>score>50:
        MOVESPEED = 9
    elif 150>score>100:
        MOVESPEED = 8
    elif 250>score>150:
        MOVESPEED = 6
    elif 400>score>250:
        MOVESPEED = 5
    elif 600>score>400:
        MOVESPEED = 3
    elif 800>score>600:
        MOVESPEED = 2
    elif score>800:
        MOVESPEED = 1
    # move the player
    if moveDown and player.bottom < height:
        player.top += MOVESPEED
    if moveUp and player.top > 0:
        player.top -= MOVESPEED
    if moveLeft and player.left > 0:
        player.left -= MOVESPEED
    if moveRight and player.right < width:
        player.right += MOVESPEED
    thesurface.blit(bg, (0, 0))

    # draw the player onto the surface
    if not splitting: # XXX check the split flag and draw accordingly...
        pygame.draw.circle(thesurface, playercolor, player.center, size)
    else:
        pygame.draw.circle(thesurface, playercolor,(player.centerx,player.centery),int(size/2))
        pygame.draw.circle(thesurface, playercolor,(player.centerx+size,player.centery+size),int(size/2))
    # check if the player has intersected with any food squares.
    for food in foods[:]:
        if player.colliderect(food):
            foods.remove(food)
            size+=1
            score+=1

    # draw the food
    for i in range(len(foods)):
        pygame.draw.rect(thesurface, GREEN, foods[i])

    printscore = basicFont.render("Score: %d" % score, True, (0,0,0))
    thesurface.blit(printscore, (495, 10))

    pygame.display.update()
    # draw the window onto the thesurface
    pygame.display.update()
    mainClock.tick(80)

您肯定也想将其放入一些函数和/或类中。

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

Pygame:细胞物理学 的相关文章

  • 在 numpy 数组中查找满足条件的大量连续值

    我在 numpy 数组中加载了一些音频数据 我希望通过查找静音部分 即一段时间内音频幅度低于特定阈值的部分 来对数据进行分段 一个非常简单的方法是这样的 values join 1 if abs x lt SILENCE THRESHOLD
  • QSortFilterProxyModel + QAbstractItemModel modelIndex.internalPointer() 导致崩溃

    我在 PyQt 4 8 Python 2 7 中实现了自己的 QAbstractItemModel class FriendListModel QtCore QAbstractItemModel def init self groups c
  • 使用 Marshmallow 中的数据更新行 (SQLAlchemy)

    我正在使用 Flask Flask SQLAlchemy Flask Marshmallow marshmallow sqlalchemy 尝试实现 REST api PUT 方法 我还没有找到任何使用 SQLA 和 Marshmallow
  • 按 ListProperty (NDB) 对查询进行排序

    如何按 ListProperty 对查询进行排序 该模型 class Chapter ndb Model title ndb StringProperty required True version ndb IntegerProperty
  • 用于打印 C/C++ 文件的所有函数定义的 Python 脚本

    我想要一个 python 脚本来打印 C C 文件中定义的所有函数的列表 e g abc c定义两个函数为 void func1 int func2 int i printf d i return 1 我只想搜索文件 abc c 并打印其中
  • 在 C# 中实例化 python 类

    我已经用 python 编写了一个类 我想通过 IronPython 将其包装到 net 程序集中 并在 C 应用程序中实例化 我已将该类迁移到 IronPython 创建了一个库程序集并引用了它 现在 我如何真正获得该类的实例 该类看起来
  • 打印一个 Jupyter 单元中定义的所有变量

    有没有一种更简单的方法来以漂亮的方式显示单个单元格中定义的所有变量的名称和值 我现在做的方式是这样的 但是当有30个或更多变量时我浪费了很多时间 您可以使用whos http ipython readthedocs io en stable
  • Docker:通过 Gunicorn 运行 Flask 应用程序 - Worker 超时?表现不佳?

    我正在尝试创建一个用Python Flask编写的新应用程序 由gunicorn运行 然后进行dockerized 我遇到的问题是 docker 容器内的性能非常差 不一致 我最终得到了响应 但我不明白为什么性能会下降 有时我会在日志中看到
  • 检查对象数组中的多个属性匹配

    我有一个对象数组 它们都是相同的对象类型 并且它们有多个属性 有没有办法返回一个较小的对象数组 其中所有属性都与测试用例 字符串匹配 无论该属性类型是什么 使用列表理解all http docs python org 3 library f
  • keras 预测内存交换无限期增加

    我使用keras实现了一个分类程序 我有一大组图像 我想使用 for 循环来预测每个图像 然而 每次计算新图像时 交换内存都会增加 我尝试删除预测函数内部的所有变量 并且我确信该函数内部存在问题 但内存仍然增加 for img in ima
  • 从文档字符串生成 sphinx 文档不起作用

    我有一个具有以下结构的项目 我想保留 my project build here is where sphinx should dump into requirements txt make bat Makefile more config
  • 如何在 Numpy 中实现垃圾收集

    我有一个名为main py 它引用另一个文件Optimisers py它仅具有功能并用于for循环进入main py 这些函数都有不同的优化功能 This Optimisers py然后引用另外两个类似的文件 其中也只有函数 它们位于whi
  • 将 ASCII 字符转换为“”unicode 表示法的脚本

    我正在对 Linux 区域设置文件进行一些更改 usr share i18n locales like pt BR 并且需要格式化字符串 例如 d m Y H M 必须以 Unicode 指定 其中每个 在本例中为 ASCII 字符表示为
  • 如何在 Tkinter 的 Button 小部件中创建多个标签?

    我想知道如何在 Tkinter 中创建具有多个标签的按钮小部件 如下图所示 带有子标签的按钮 https i stack imgur com jOZRw jpg正如您所看到的 在某些按钮中有一个子标签 例如按钮 X 有另一个小标签 A 我试
  • Scrapy - 不会爬行

    我正在尝试运行递归爬行 由于我编写的爬行不能正常工作 因此我从网络上提取了一个示例并进行了尝试 我真的不知道问题出在哪里 但是爬行没有显示任何错误 谁能帮我这个 另外 是否有任何逐步调试工具可以帮助理解蜘蛛的爬行流程 非常感谢任何与此相关的
  • pandas apply:函数名是否带引号的区别

    简单数据框定义示例 df pd DataFrame A 2 4 1 B 8 4 1 C 6 2 7 df A B C 0 2 8 6 1 4 4 2 2 1 1 7 尝试理解以下块中函数参数调用的差异 df apply sum df app
  • if/else 在 while 循环内正确缩进[关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 我开始学习 Python 编程大约几周了 我遇到了一些麻烦 下面的代码是一个小程序 用于检查列表中是否有偶数 如果找到第一个偶数
  • 如何在包更新之间保留数据文件?

    我正在使用data files的论证setuptools setup 将配置文件安装到 etc和用户主目录 但是更新包pip install
  • 在 Gensim 中通过 ID 检索文档的字符串版本

    我正在使用 Gensim 进行一些主题建模 并且已经达到使用 LSI 和 tf idf 模型进行相似性查询的程度 我取回 ID 集和相似点 例如 299501 0 64505910873413086 如何获取与 ID 在本例中为 29950
  • 将笔记本生成的 HTML 片段转换为 LaTeX 和 PDF

    在我的笔记本里有时会有 from IPython display import display HTML display HTML h3 The s is important h3 question of the day 但当我后来将笔记本

随机推荐