【问题标题】:I am trying to create a list that "updates" the position of a value on a button input我正在尝试创建一个“更新”按钮输入值位置的列表
【发布时间】:2022-12-15 12:34:09
【问题描述】:

基本上我只是尝试使用终端创建一个蛇游戏,不是因为它特别有趣,高效(我知道有很多更好的方法来做到这一点)而是习惯使用和理解 python 因为我只是一个初学者.

import keyboard

dirx = 1
diry = 0

x = 0
y = 0


a = ['-', '-', '-', '-', '-']

def getkey():
    global x
    keyboard.wait('d')
    x +=1

while True:
    # creates a constantly updating list, which will function as part of the game board
    a[x] = 0
    a[not x] = '-'
    print('\r', a, end='')
    getkey()

    if x > 4:
        x = 0

这是我到达的地方,我遇到了一些障碍,我可以让 0 继续前进,但让其余位置更新回“-”要困难得多,不是x 有点工作,但它在超过 0 后停止,我认为它不考虑更新的值,但我不确定。这可能是一个非常简单的解决方案,但我只是在学习,我无法弄清楚

【问题讨论】:

    标签: python


    【解决方案1】:

    不幸的是,“not x”不是选择除 x 之外的所有列表元素的正确方法。 not x 只是评估 x 是否为 True (>0) 然后否定这个结果。

    因此,not x 的唯一结果是 True 或 False,然后在索引期间将其转换为 0(第一个元素)或 1(第二个元素)。

    为避免这种情况,您有两种选择。 “蛮力”方式是在每个循环中完全重建列表:

    import keyboard
    
    x = 0
    
    def getkey():
        global x
        keyboard.wait('d')
        x += 1
    
    while True:
        a = ['-', '-', '-', '-', '-']
        a[x] = 0
        print('
    ', a, end='')
        getkey()
    
        if x > 4:
            x = 0
    

    对于“高级索引”,我会考虑查看numpy 数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 2016-02-20
      • 2020-05-29
      • 2021-10-14
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 2019-05-06
      相关资源
      最近更新 更多