如何根据if语句Python更改列表的值

问题描述 投票:-2回答:1

我正在尝试创建一个pygame游戏,其中精灵列表会根据点击次数而变化。

p1 = 1
p2 = 1
if p1 == 1:
  list1_1 = [EXAMPLE]
  list1_2 = [EXAMPLE] 
if p1 == 2:
  list1_1 = [EXAMPLE]
  list1_2 = [EXAMPLE]
if p2 == 1:
  list2_1 = [EXAMPLE]
  list2_2 = [EXAMPLE]
if p2 == 2:
  list2_1 = [EXAMPLE]
  list2_2 = [EXAMPLE]

def button():
  if clicked:
    if action == EXAMPLE:
      p1 = 1
    if action == EXAMPLE:
      p1 = 2 
    if action == EXAMPLE:
      p2 = 1
      game()
    if action == EXAMPLE:
      p2 = 2  
      game()  

def menu():
  button(info) 

def game():
  EXTRA

menu()

所以这是我的游戏的缩短版本,可能是我的主要代码。问题是,当我单击按钮更改值时,它实际上不会更改列表的值; list1_1,list1_2,list2_1和list2_2。

python pygame
1个回答
0
投票

目前,列表值在程序开始运行时初始化,之后不会更改,因此它们不会更改。我想你想运行代码的前14行,只要有一个按钮点击就会更新列表值。有很多方法可以做到这一点,一个想法是将它们全部放在一个方法中,然后在你想要更改它们时调用它来更新全局值。例如,

# initialize the lists globally 
list1_1, list1_2, list1_2_1, list1_2_2 = [[]] * 4

pl = 1
p2 = 1

def do_some_action(p1=1, p2=1):
    if p1 == 1:
        global list1_1 = [EXAMPLE]
        global list1_2 = [EXAMPLE]
    if p1 == 2:
        global list1_1 = [EXAMPLE]
        global list1_2 = [EXAMPLE]
    if p2 == 1:
        global list2_1 = [EXAMPLE]
        global list2_2 = [EXAMPLE]
    if p2 == 2:
        global list2_1 = [EXAMPLE]
        global list2_2 = [EXAMPLE]

do_some_action(p1, p2)

def button():
    if clicked:
        if action == EXAMPLE:
            global p1 = 1
            do_some_action(p1, p2)
        if action == EXAMPLE:
            global p1 = 2
            do_some_action(p1, p2)
        if action == EXAMPLE:
            global p2 = 1
            do_some_action(p1, p2)
            game()
        if action == EXAMPLE:
            global p2 = 2
            do_some_action(p1, p2)
            game()

def menu():
    button(info)

def game():
    EXTRA

menu()
© www.soinside.com 2019 - 2024. All rights reserved.