PyGame蠕虫 - 与坏苹果的线程

时间:2012-07-09 11:46:04

标签: python multithreading pygame

我正在使用PyGame开发一个小蠕虫程序。我吃了一只虫子,每次吃苹果就会长大。当它遇到它自己的尾巴或窗户bordure时,它就会超过'。 我想随意添加带有毒药的坏苹果。这些苹果出现在屏幕上的任何地方,某些地方还没有苹果占用。相反,好的苹果一次出现一个。当虫子吃一个苹果时,它会长出一个,另一个苹果出现在屏幕上。所以,我想我应该在分离的线程中生产坏苹果。但是,我希望能够访问主线程中的坏苹果等位置,以便在遇到一个坏苹果时虫子死亡。

你知道如何写这个吗?

我想在main()

中有这个
# Start bad apples thread
threading.Thread(target=badApples).start()

这样main()最终看起来像这样:

def runGame():
# Set a random start point.
startx = random.randint(5, CELLWIDTH-5)
starty = random.randint(5, CELLHEIGHT-5)
wormCoords = [{'x': startx,     'y': starty},
              {'x': startx - 1, 'y': starty},
              {'x': startx - 2, 'y': starty}]
direction = RIGHT

# Start the apple in a random place.
apple = getRandomLocation()

# Start bad apples thread
threading.Thread(target=badApples).start()

while True: # main game loop
    for event in pygame.event.get(): # event handling loop
        if event.type == QUIT:
            terminate()
        elif event.type == KEYDOWN:
            if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:
                direction = LEFT
            elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:
                direction = RIGHT
            elif (event.key == K_UP or event.key == K_w) and direction != DOWN:
                direction = UP
            elif (event.key == K_DOWN or event.key == K_s) and direction != UP:
                direction = DOWN
            elif event.key == K_ESCAPE:
                terminate()

    # check if the worm has hit itself or the edge
    if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == CELLWIDTH or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == CELLHEIGHT:
        return # game over
    for wormBody in wormCoords[1:]:
        if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
            return # game over

    # etc... 

(主要来自http://inventwithpython.com/的代码)

以及以

开头的目标方法badApples
def badApples():
    time.sleep(random.randint(200,500))
    badApple = getRandomLocation()

但是如何在主线程中恢复坏苹果的位置,以便删除蠕虫?

感谢和问候

1 个答案:

答案 0 :(得分:4)

你绝对不必为此使用线程。当您控制游戏循环时,您可以安排创建一个坏苹果(使用某种倒计时)。

创建一个变量,该变量将存储一个值,指示新的坏苹果何时出现,以及已创建的坏苹果列表。

def get_bad_apple_time():
    # create a bad apple every 5 to 15 seconds
    # assuming your FPS is 60 
    return random.randrange(5, 16) * 60 

#  all bad apple coordinates go here
bad_apples = []  

# timeout until the next bad apple shows up
next_bad_apple = get_bad_apple_time()

在主循环中,减小next_bad_apple的值。如果它达到0,则创建一个坏苹果并重新开始。

while True:
    ...
    next_bad_apple -= 1
    if not next_bad_apple:
        pos = getRandomLocation()

        # if there's already a bad apple on this position
        # create a new position
        while pos in bad_apples:
            pos = getRandomLocation()

        bad_apples.append(pos)
        next_bad_apple = get_bad_apple_time()