如何在Pygame中与List的项目进行交互?

时间:2017-05-26 02:22:25

标签: python list python-3.x random pygame

我开始制作游戏, 我偶然发现了一个小问题

*按“空格键”时,红色方块会在显示屏上随机生成

问题 我怎样才能让红场成为障碍?

我是一个完全忘记的人,我很抱歉问这么简单的问题..:/

守则可能会给你一个想法:

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

"List the Stores the Squares"
red_square_list = []

gameDisplay_width = 800
gameDisplay_height = 600

pygame.init()
gameDisplay = pygame.display.set_mode((gameDisplay_width, gameDisplay_height))
pygame.display.set_caption("Square-it")
clock = pygame.time.Clock()
red_color = pygame.Color("red")

"White Square"
white_x = 400
white_y = 300
white_width = 10
white_height = 10
white_color = pygame.Color("white")
white = pygame.Rect(white_x, white_y, white_width, white_height)

"Red Squares"
def create_red_square(x, y):
    red_width = 10
    red_height = 10
    red = pygame.Rect(x, y, red_width, red_height)
    return red

while True:

    clock.tick(60)
    gameDisplay.fill((0, 20, 5))
    gameDisplay.fill(white_color, white)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           sys.exit()

    for each in red_square_list:
        gameDisplay.fill(red_color, each)

    pygame.display.update()

    '''White Square Movement'''
    keys = pygame.key.get_pressed()
    if keys[K_LEFT]:
        white.left = white.left - 4

    if keys[K_RIGHT]:
        white.right = white.right + 4

    if keys[K_UP]:
        white.top = white.top - 4

    if keys[K_DOWN]:
        white.bottom = white.bottom + 4

    "when Space key Pressed, Spawns red Squares"
    if keys[K_SPACE]:
        x = randint(0, gameDisplay_width)
        y = randint(0, gameDisplay_height)
        red_square_list.append(create_red_square(x, y))

1 个答案:

答案 0 :(得分:1)

使用当前系统,只要按住Space,就会在列表中添加一个红色方块。这意味着按下按钮时每个FRAME都会放置一个正方形。太多了!您要做的是将以下内容添加到事件循环中。这将激活您按下该键的帧,而不是更多。

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_SPACE:
         x = randint(0, gameDisplay_width)
         y = randint(0, gameDisplay_height)
         red_square_list.append(create_red_square(x, y))