티스토리 뷰
프로그램을 클래스로 분해해서 만들어보자.
*snake.py *food.py *scoreboard.py
[main.py]
from turtle import Screen, Turtle
from snake import Snake
import time
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.tracer(0)
screen.title("kio's snake game - ver.20220223(e first one)")
snake = Snake()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.2)
snake.move()
screen.exitonclick()
[snake.py]
from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
COLOR = ["red", "orange", "yellow", "green", "blue", "navy", "purple"]
MOVING_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.turtles = []
self.create_snake()
self.head = self.turtles[0]
def create_snake(self):
color_index = 0
for pos in STARTING_POSITIONS:
new_turtle = Turtle(shape="square")
new_turtle.color(COLOR[color_index])
new_turtle.pu()
new_turtle.setpos(pos)
color_index += 1
self.turtles.append(new_turtle)
def move(self):
for tut_num in range(len(self.turtles)-1, 0, -1): #(start=2, stop=0, step=-1)
new_x = self.turtles[tut_num - 1].xcor()
new_y = self.turtles[tut_num - 1].ycor()
self.turtles[tut_num].goto(new_x,new_y)
self.head.fd(MOVING_DISTANCE)
def up(self):
if self.head.heading() != DOWN:
self.head.setheading(UP)
def down(self):
if self.head.heading() != UP:
self.head.setheading(DOWN)
def left(self):
if self.head.heading() != RIGHT:
self.head.setheading(LEFT)
def right(self):
if self.head.heading() != LEFT:
self.head.setheading(RIGHT)
'Test > Python(20220101~)' 카테고리의 다른 글
Days21. 뱀게임4 - scoreboard 추가 (0) | 2022.03.02 |
---|---|
Days21. 클래스 상속(Class Inheritance), 뱀게임3-먹이 랜덤출력 (0) | 2022.03.01 |
Days20. 뱀게임1 (0) | 2022.02.24 |
Days19. Turtle race (0) | 2022.02.21 |
Days19. Make an Etch-a-Sketch (0) | 2022.02.21 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 차집합
- 3par
- LIST
- oracle
- 읽어오기
- Join
- virt-sysprep
- 스토리지
- exadata
- sysprep
- 대소문자
- dp-1
- cloud-init
- artandculture
- vmware.powercli
- set()
- insert
- 배열
- dezoomify
- EXA
- 부동없이
- powershell
- dp-2
- vmware
- 정렬
- fromkeys
- 변수화
- powercli
- storage
- 중복제거
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
글 보관함