我应该如何随下一个箭头随机翻转箭头?

时间:2019-03-30 18:05:17

标签: python pygame

我正在通过pygame创建简单的游戏。在代码中,每个pygame的箭头随机翻转。绘制,但我希望它翻转(在游戏中的下一个箭头时随机。

这是不完整的代码

import pygame
import random
import sys
pygame.init()
h=600
w=800
arrow_pos=[w/2,0]
base_size=[w/2,50]
base_pos=[w/4,h-50]
screen=pygame.display.set_mode((w,h))
bg_color=(0,0,0)
base_color=(255,0,0)
arrow_color=(0,150,255)
clock=pygame.time.Clock()
game_over=False
def updating_arrow(arrow_pos):
    if arrow_pos[1]>=0 and arrow_pos[1]<h:
        arrow_pos[1]+=10
    else:
        arrow_pos[1]-=h
    return arrow_pos[1]    
def draw_arrow(screen,arrow_color,arrow_pos,arrow_size):
        pygame.draw.polygon(screen, arrow_color, ((arrow_pos[0], 
        arrow_pos[1]+10), (arrow_pos[0], arrow_pos[1]+20), 
        (arrow_pos[0]+arrow_size, arrow_pos[1]+20), 
        (arrow_pos[0]+arrow_size, 
        arrow_pos[1]+30), (arrow_pos[0]+(arrow_size)*1.5, 
        arrow_pos[1]+15), 
        (arrow_pos[0]+arrow_size, arrow_pos[1]), 
        (arrow_pos[0]+arrow_size, 
        arrow_pos[1]+10)),0)
while not game_over:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()
    screen.fill(bg_color)
    arrow_pos[1]=updating_arrow(arrow_pos)

    arrow_size=random.choice([50,-50])
    draw_arrow(screen,arrow_color,arrow_pos,arrow_size)
    pygame.draw.rect(screen,base_color, 
    (base_pos[0],base_pos[1],base_size[0],base_size[1]))
    pygame.display.update()
    clock.tick(30)

1 个答案:

答案 0 :(得分:0)

在主循环之前随机初始化arrow_size

arrow_size = random.choice([50,-50])
while not game_over:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()  

当新的箭头出现在窗口顶部时,仅更改箭头的大小。您必须使用global statement来更改函数arrow_size中的全局变量updating_arrow的值:

def updating_arrow(arrow_pos):
    global arrow_size
    if arrow_pos[1] >= 0 and arrow_pos[1] < h:
        arrow_pos[1] += 10
    else:
        arrow_pos[1] -= h
        arrow_size = random.choice([50,-50])
    return arrow_pos[1]  

或通过参数将arrow_size传递给函数并返回更改的内容,就像使用arrow_pos一样:

def updating_arrow(arrow_pos, arrow_size):
    if arrow_pos[1]>=0 and arrow_pos[1]<h:
        arrow_pos[1]+=10
    else:
        arrow_pos[1]-=h
        arrow_size = random.choice([50,-50])
    return arrow_pos, arrow_size  
arrow_pos, arrow_size = updating_arrow(arrow_pos, arrow_size) 
# arrow_pos[1]=updating_arrow(arrow_pos) <---- delete
# arrow_size=random.choice([50,-50])     <---- delete