728x90
import os
import keyboard
import random
import threading
from time import sleep
#맵크기
filed_size=11
#시작위치
start_position = int(filed_size/2)
#시작위치변수
snake_y=start_position
snake_x=start_position
snake_position=[[snake_y,snake_x],[snake_y,snake_x],[snake_y,snake_x]]
#스레드 키 입력 변수
key=None
game_speed = 0.1
star_count = 0
game_speed = float(input("1~3 중 속도 입력 ")) * 0.1
#별 생성 주기
star_gen_cycle=5
star_list=[]
def printMap(field):
for i in field:
for j in i:
print(j, end=" ")
print()
# print("별 위치 : {0}".format(star_list))
# print("뱀 위치 : {0},{1}".format(snake_y,snake_x))
# print(star_count)
# print("현재 키: {0}".format(key))
global snake_position
global tail_y
global tail_x
tail_y=snake_position[len(snake_position) -1][0]
tail_x=snake_position[len(snake_position) -1][1]
print("꼬리 Y:{0} ".format(tail_y))
print("꼬리 X:{0} ".format(tail_x))
print(snake_position)
print("q나 r 누를 시 초기화")
#초기화
def initGame():
global field
global snake_x
global snake_y
global star_count
global snake_position
global star_list
if len(snake_position)>=3:
del snake_position
if len(star_list)>=1:
del star_list
snake_position=[[start_position,start_position],[start_position,start_position],[start_position,start_position]]
star_list=[]
field = [["□" for col in range(filed_size)] for row in range(filed_size)]
os.system('cls')
printMap(field)
star_count=0
os.system('cls')
for i in snake_position:
field[i[0]][i[1]] = "■"
printMap(field)
print("========PushAnyArrow========")
def moveUp():
os.system('cls')
cnt = len(snake_position) -1
field[snake_position[cnt][0]][snake_position[cnt][1]] = "□"
while cnt>=1:
snake_position[cnt] = snake_position[cnt-1]
cnt-=1
snake_position[0] = [snake_position[0][0]-1,snake_position[0][1]]
for i in snake_position:
field[i[0]][i[1]] = "■"
printMap(field)
def moveDown():
os.system('cls')
cnt = len(snake_position) -1
field[snake_position[cnt][0]][snake_position[cnt][1]] = "□"
while cnt>=1:
snake_position[cnt] = snake_position[cnt-1]
cnt-=1
snake_position[0] = [snake_position[0][0]+1,snake_position[0][1]]
for i in snake_position:
field[i[0]][i[1]] = "■"
printMap(field)
def moveLeft():
os.system('cls')
cnt = len(snake_position) -1
field[snake_position[cnt][0]][snake_position[cnt][1]] = "□"
while cnt>=1:
snake_position[cnt] = snake_position[cnt-1]
cnt-=1
snake_position[0] = [snake_position[0][0],snake_position[0][1]-1]
for i in snake_position:
field[i[0]][i[1]] = "■"
printMap(field)
def moveRight():
os.system('cls')
cnt = len(snake_position) -1
field[snake_position[cnt][0]][snake_position[cnt][1]] = "□"
while cnt>=1:
snake_position[cnt] = snake_position[cnt-1]
cnt-=1
snake_position[0] = [snake_position[0][0],snake_position[0][1]+1]
for i in snake_position:
field[i[0]][i[1]] = "■"
printMap(field)
#별 생성함수
def generateStar():
star_x = random.randrange(0,filed_size)
star_y = random.randrange(0,filed_size)
global star_list
#별 생성 위치에 오브젝트 존재할 시 다른 곳으로 출력
if(field[star_y][star_x] in ["■", "★"]):
while field[star_y][star_x] in ["■", "★"]:
star_x = random.randrange(0,filed_size)
star_y = random.randrange(0,filed_size)
field[star_y][star_x] = "★"
printMap(field)
star_list.append([star_y,star_x])
else:
field[star_y][star_x] = "★"
printMap(field)
star_list.append([star_y,star_x])
def getStar():
if snake_position[0] in star_list:
grow()
star_list.remove(snake_position[0])
def controll():
while True:
global star_count
if key=='up':
while (key=='up'):
star_count+=1
moveUp()
getStar()
collision()
sleep(game_speed)
if star_count>=star_gen_cycle:
generateStar()
star_count=0
elif key=='down':
while (key=='down'):
star_count+=1
moveDown()
getStar()
collision()
sleep(game_speed)
if star_count>=star_gen_cycle:
generateStar()
star_count=0
elif key=='left':
while (key=='left'):
star_count+=1
moveLeft()
getStar()
collision()
sleep(game_speed)
if star_count>=star_gen_cycle:
generateStar()
star_count=0
elif key=='right':
while (key=='right'):
star_count+=1
moveRight()
getStar()
collision()
sleep(game_speed)
if star_count>=star_gen_cycle:
generateStar()
star_count=0
#게임초기화
elif key=='q' or key=='r':
break
game()
def readKey():
global key
key=keyboard.read_key()
sleep(0.1)
threading.Thread(target=readKey,daemon=True).start()
def grow():
global tail_y
global tail_x
if(key=='up'):
tail_y=snake_y+1
snake_position.append([tail_y,tail_x])
if(key=='down'):
tail_y=snake_y-1
snake_position.append([tail_y,tail_x])
if(key=='left'):
tail_x=snake_x+1
snake_position.append([tail_y,tail_x])
if(key=='right'):
tail_x=snake_x-1
snake_position.append([tail_y,tail_x])
def gameover():
os.system('cls')
printMap(field)
print("***********GAMEOVER***************")
a = input("다시 하려면 q나 r 입력, 다른 거 입력하면 종료")
if a in ('q','r'):
game()
def collision():
if snake_position[0] in snake_position[1:]:
gameover()
def game():
try:
initGame()
readKey()
controll()
except IndexError as e:
gameover()
game()
만들어 놓고 버그픽스하기 귀찮아서 미루다가 완성이 오래걸렸다.
버그의 문제는 꼬리의 좌표값을 잘못 지정해주어서..
snake_position[0][0] = tail_y
snake_position[0][x] = tail_x
해당 코드를
snake_position[len(snake_position) -1 ][0] = tail_y
snake_position[len(snake_position) -1 ][1] = tail_x
로 수정하니 잘 되더라
인터넷에 올라온 코드와 비교하면 길지만 완성은 했다.
배포파일
'Python' 카테고리의 다른 글
[파이썬 토이프로젝트] wordcloud와 konlpy를 이용한 카카오톡 채팅내역 시각화 (0) | 2022.03.16 |
---|---|
[Python] 스네이크 게임3 (0) | 2021.09.12 |
[Python] 스네이크 게임 2 (0) | 2021.09.10 |
[Python] 스네이크 게임 1 (0) | 2021.09.08 |