【问题标题】:Pygame, Python 2.7.3. Repeating obstaclesPygame,Python 2.7.3。重复障碍
【发布时间】:2016-03-27 02:21:03
【问题描述】:

我正在使用 python 2.7.3 使用 Pygame 创建一个简单的游戏,其中一个球必须避免障碍物落向球。但是我不知道如何使障碍物反复掉落,而每个障碍物也随机掉落。这是我的代码:

import pygame
from math import pi
import random

pygame.init()

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE =  (  0,   0, 255)
GREEN = (  0, 255,   0)
RED =   (255,   0,   0)
TAN = (252,231,182)
background = (38,37,37)

size = [400, 400]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Game")

siz = 20
x = 200
xminus = x - 140
xadd = x + 140
y = 350
fallingy = 0
rectx = 0
rectl = 60
rectw = 30
done = False
clock = pygame.time.Clock()

while not done:

    clock.tick(10)

    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            done=True 
    screen.fill(background)
    pressed = pygame.key.get_pressed()
    circle = pygame.draw.circle(screen, BLUE, [x,y],siz)

    if pressed[pygame.K_LEFT]:
        screen.fill(background)
        x = 60
        circle2 = pygame.draw.circle(screen, BLUE,[x,y],siz)

    if pressed[pygame.K_RIGHT]:
        screen.fill(background)
        x = 340
        circle = pygame.draw.circle(screen, BLUE,[x,y],siz)

    if pressed[pygame.K_LEFT] and pressed[pygame.K_RIGHT]:
        screen.fill(background)
        circle = pygame.draw.circle(screen, BLUE,[xminus,y],siz)
        circle = pygame.draw.circle(screen, BLUE,[xadd,y],siz)

    else:
        circle = pygame.draw.circle(screen, BLUE, [x,y],siz)
        x = 200
    """THIS IS THE CODE I WANT TO BE REPEATED RANDOMLY"""   
    def middle1():
        pygame.draw.rect(screen, RED, [rectx, fallingy, 170, rectw])
        pygame.draw.rect(screen, RED, [rectx + 400, fallingy, -170, rectw])
    def lnr():
        pygame.draw.rect(screen, RED, [rectx, fallingy, 20, rectw])
        pygame.draw.rect(screen, RED, [rectx +400, fallingy, -20, rectw])
        pygame.draw.rect(screen, RED, [rectx + 100, fallingy, 200, rectw])
    def l():
        pygame.draw.rect(screen, RED, [rectx, fallingy, 20, rectw])
        pygame.draw.rect(screen, RED, [rectx + 400, fallingy, -300, rectw])
    def r():
        pygame.draw.rect(screen, RED, [rectx + 400, fallingy, -20, rectw])
        pygame.draw.rect(screen, RED, [rectx, fallingy, 300, rectw])
    """THIS IS THE CODE I WANT TO BE REPEATED RANDOMLY"""
    fallingy += 5
    pygame.display.flip()
pygame.quit()

任何帮助将不胜感激。

【问题讨论】:

    标签: python python-2.7 pygame


    【解决方案1】:

    通常,处理每个都需要附加数据的代码位的最佳方法是为其编写一个类。您可以从头开始创建自己的类,但从 pygame.sprite.Sprite 之类的东西继承可能更容易,它已经完成了您想要的大部分工作(并且还可以做更多的事情,比如使用更复杂的图像而不仅仅是实心框)。

    【讨论】:

    • 你能给我看一个如何使用pygame.sprite.Sprite的简单例子吗?感谢您的回复!
    • 我链接到的文档页面有一个使用Sprite 的开源代码this search page 的链接,因此您可以在实际代码中看到它。这些搜索链接是 Pygame 文档的新功能,它们曾经有用户提交的糟糕的示例代码。他们很不错!
    猜你喜欢
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多