前提・実現したいこと
ライフゲームをPythonで作りたいです。
youtubeのゲヱム道場さんの動画を参考にしています。
以下のエラーの原因がわかりません。
発生している問題・エラーメッセージ
例外が発生しました: TypeError
'int' object is not subscriptable
File "C:\Users\python\game_of_life2.py", line 52, in getAdjacentLivesCount
count += get_key(CELL_TYPE, cells[current][y2][x2][0])
File "C:\Users\python\game_of_life2.py", line 95, in <module>
n = getAdjacentLivesCount(x, y)
該当のソースコード
python
1#! python3 2# game_of_life.py - Game of life 3 4import os, sys, random, time 5from msvcrt import getch 6 7FIELD_WIDTH = FIELD_HEIGHT = 20 8 9cursorX = cursorY = 0 10 11 12cells = [] 13cells2 = [] 14 15current = 0 16 17CELL_TYPE = { 18 0 : "・", 19 1 : "■" 20} 21 22for y in range(FIELD_HEIGHT): 23 cells2.append([]) 24 for x in range(FIELD_WIDTH): 25 cells2[y].append([]) 26 27for y in range(FIELD_HEIGHT): 28 for x in range(FIELD_WIDTH): 29 cells2[y][x].append(CELL_TYPE[0]) 30 31cells.append(cells2) 32cells.append(cells2) 33 34 35 36 37def get_key(d, val): 38 keys = [k for k, v in d.items() if v == val] 39 if keys: 40 return int(keys[0]) 41 return None 42 43def getAdjacentLivesCount(_x, _y): 44 count = 0 45 46 for y in range(-1, 2): 47 for x in range(-1, 2): 48 if (x is 0) and (y is 0): 49 continue 50 x2 = (FIELD_WIDTH + _x + x) % FIELD_WIDTH 51 y2 = (FIELD_HEIGHT + _y + y) % FIELD_HEIGHT 52 count += get_key(CELL_TYPE, cells[current][y2][x2][0]) 53 54 return count 55 56while True: 57 os.system('cls') 58 for y in range(FIELD_HEIGHT): 59 for x in range(FIELD_WIDTH): 60 if (x is cursorX) and (y is cursorY): 61 print('◎', end='') 62 else: 63 print(cells[current][y][x][0], end='') 64 """if (x is cursorX) and (y is cursorY): 65 print("@", end='') 66 else: 67 print(getAdjacentLivesCount(x, y), end='')""" 68 print("\n") 69 70 while True: 71 ans = chr(ord(getch())) 72 if ans == 'w': 73 cursorY = cursorY-1 74 break 75 elif ans == 's': 76 cursorY = cursorY+1 77 break 78 elif ans == 'a': 79 cursorX = cursorX-1 80 break 81 elif ans == 'd': 82 cursorX = cursorX+1 83 break 84 elif ans == 'q': 85 sys.exit() 86 elif ans == ' ': 87 if cells[current][cursorY][cursorX][0] is CELL_TYPE[0]: 88 cells[current][cursorY][cursorX] = CELL_TYPE[1] 89 else: 90 cells[current][cursorY][cursorX] = CELL_TYPE[0] 91 break 92 elif ans == '\r': 93 for y in range(FIELD_HEIGHT): 94 for x in range(FIELD_WIDTH): 95 n = getAdjacentLivesCount(x, y) 96 next = cells[current][y][x] 97 if(cells[current][y][x]): 98 if(n <= 1) or (n >= 4): 99 next = 0 100 else: 101 if(n == 3): 102 next = 1 103 cells[current^1][y][x] = next 104 current = current^1 105 break 106 107
補足情報(FW/ツールのバージョンなど)
Visual Code
Anaconda Prompt のインタプリタ?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/01/28 14:31
2019/01/29 12:10
2019/01/29 14:11