簡體   English   中英

如何在 Pygame 中創建自動化 object

[英]How to create an automated object in Pygame

我想創建一個自動 object 移動到屏幕上的隨機位置。 圖像正在顯示,但它沒有移動到任何位置。

導入 pygame 后,設置顯示並加載所需的圖像,我定義了以下參數:

object_start_x = 200
object_start_y = -600
object_width = 60
object_height = 160
object_speed = 1

在主游戲循環中,使用我之前定義的 object() game_loop ,我將隨機整數作為 x 和 y 坐標:

gameExit = False

while not gameExit:
    object(object_start_x, object_start_y, object_width, object_height)
    object_start_y += object_speed
        if object_start_y >= 50:
            object_start_y = 50
            random_locationx = random.randint(50, display_width - object_width)
            random_locationy = random.randint(50, display_height - object_height)

然后,我嘗試更改對象的 position 直到它與生成的隨機 integer 相同。

            if random_locationx < object_start_x:
                object_start_x - object_speed
                if object_start_x == random_locationx:
                    object_start_x == random_locationx
            elif random_locationx > object_start_x:
                object_start_x + object_speed
                if object_start_x == random_locationx:
                    object_start_x == random_locationx
            elif random_locationx == object_start_x:
                object_start_x == random_locationx

我對 y 坐標的object_start_yrandom_locationy重復了相同的操作。 雖然圖像確實出現了,但 object 沒有移動。 關於我能做些什么來解決這個問題的任何想法?

編輯:針對@Sal 的評論, Pygame 移動 object並不能解決我的問題,因為我想隨機自動化 object,不能自己移動它。

這里沒有太多代碼,但有一些問題,所以我將記錄這些:

僅當 object 在y中通過 50 個像素時,才會生成隨機位置。 也許這是設計使然?

if object_start_y >= 50:
   object_start_y = 50
   random_locationx = random.randint(50, display_width - object_width)
   random_locationy = random.randint(50, display_height - object_height)

我不清楚這個代碼部分的目的是什么,但看起來比較運算符==正在使用,而賦值運算符=的目的是。

if random_locationx < object_start_x:
    object_start_x - object_speed
    if object_start_x == random_locationx:
        object_start_x == random_locationx    # <-- HERE

此外,即使這是一個作業,它也相當於if my_fruit == 'apple', then my_fruit = 'apple' 它沒有實現改變。

我會將“對象”數據打包成一個結構。 python Rect object 是最好的,因為它已經支持 x、y、寬度、高度,並帶有一組很棒的實用功能(用於碰撞等)

object_start_x = 200
object_start_y = -600
object_width   = 60
object_height  = 160

my_object_rect  = pygame.Rect( object_start_x, object_start_y, object_width, object_height )
my_object_speed = 1   # in Y

...

while not gameExit:

    # Move the object
    my_object_rect.y += my_object_speed
    if ( my_object_rect.y > 50 ):
        rand_x = random.randint(50, display_width - object_width)
        rand_y = random.randint(50, display_height - object_height)
        my_object_rect.topleft = ( rand_x, rand_y )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM