@KiringD

При добавлении элемента в список остальные элементы меняются вместе с ним?

Пытаюсь создать банальную змейку, в одном из мест я решил использовать список, но по какой то причине каждый раз когда я добавляю новый элемент, весь список заменяется этим числом. Я крайне извиняюсь у меня так и не получилось повторить ошибку на небольшом примере, так что привожу весь код. (Добавление в список происходит в функции del_tail() Также прикрепляю скриншот

import msvcrt
import os
import time
import asyncio
import random


a=[
["#","#","#","#","#","#","#","#","#","#"],
["|","."," "," "," "," "," "," "," ","|"],
["|"," "," "," "," "," "," "," "," ","|"],
["|"," "," "," "," "," "," "," "," ","|"],
["|"," "," "," "," "," "," "," "," ","|"],
["|"," "," "," "," "," "," "," "," ","|"],
["|"," "," "," "," "," "," "," "," ","|"],
["|"," "," "," "," "," "," "," "," ","|"],
["|"," "," "," "," "," "," "," "," ","|"],
["#","#","#","#","#","#","#","#","#","#"]]


async def update():
	global score
	global a
	# os.system("cls")
	print("Your score:", score)
	for i in range(len(a)):
		for b in a[i]:
			print(b,end=" ")
		print(" ")


async def check_dir():
	global direct
	if msvcrt.kbhit():
		print(2)
		input_char = msvcrt.getch()
		if ord(input_char) == 115:
			direct = "down"
		elif ord(input_char) == 119:
			direct = "up"
		elif ord(input_char) == 97:
			direct = "left"
		elif ord(input_char) == 100:
			direct = "right"

async def change_apple():
	global a
	global apple
	apple = [random.randint(1, 8),random.randint(1, 8)]
	a[apple[0]][apple[1]]="o"

async def del_tail(current,score):
	global a
	global snake

	snake.append(current)
	print(snake)

	

async def main():
	global direct
	global score
	global a
	global current
	while True:
		
		await asyncio.sleep(0.5)
		await check_dir()
		if direct == "right":
			if a[current[0]][current[1]+1]!="|":

				if a[current[0]][current[1]+1]=="o":
					score+=1
					await change_apple()
				await del_tail(current,score)
				
				a[current[0]][current[1]+1] = "."
				current[1] +=1

			await update()
		elif direct == "left":
			if a[current[0]][current[1]-1]!="|":

				if a[current[0]][current[1]-1]=="o":
					score+=1
					await change_apple()
				await del_tail(current,score)
				

				a[current[0]][current[1]-1] = "."
				current[1] -=1
			await update()
		elif direct == "up":
			if a[current[0]-1][current[1]]!="#":
				
				if a[current[0]-1][current[1]]=="o":
					score+=1
					await change_apple()
				await del_tail(current,score)
				
				a[current[0]-1][current[1]] = "."
				current[0] -=1
			await update()
		elif direct == "down":
			if a[current[0]+1][current[1]]!="#":
				
				if a[current[0]+1][current[1]]=="o":
					score+=1
					await change_apple()
				await del_tail(current,score)
				
				a[current[0]+1][current[1]] = "."
				current[0] +=1
			await update()


if __name__ == "__main__":
	score = 0
	current = [1,1]
	direct = "right"
	snake = list()
	apple = [random.randint(1, 8),random.randint(1, 8)]
	a[apple[0]][apple[1]]="o"
	loop = asyncio.get_event_loop()
	asyncio.ensure_future(main())
	loop.run_forever()


6169a8b61d8ea191037712.png
  • Вопрос задан
  • 58 просмотров
Решения вопроса 1
В snake помещена ссылка на current, поэтому изменение current приводит к изменениям значения в snake.
Исправлением послужит помещение копии current в snake.
>>> current = [1,1]
>>> snake = []
>>> snake.append(current.copy())
>>>
>>> snake
[[1, 1]]
>>> current[1] += 1
>>>
>>> current
[1, 2]
>>> snake
[[1, 1]]
>>>
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы