python簡單遊戲——貪吃蛇

2020-09-28 16:00:01

在這裡插入圖片描述

from turtle import *
from random import randrange
from time import sleep

### 定義變數
snake = [[0,0],[10,0],[20,0],[30,0],[40,0],[50,0]]
apple_x = randrange(-20,20)*10   
apple_y = randrange(-20,20)*10  
aim_x = 10
aim_y = 0


def squre(x,y,size,color_name):
    up()
    goto(x,y)
    down()
    color(color_name)
    begin_fill()

    forward(size)
    left(90)
    forward(size)
    left(90)
    forward(size)
    left(90)
    forward(size)
    left(90)

    end_fill()

## 控制蛇
def change(x,y):
    global aim_x,aim_y
    aim_x = x;
    aim_y = y;
#判斷撞牆
def inside():
    #判斷是否在畫布裡面
    if -210 <= snake[-1][0]<=200 and -210 <= snake[-1][1]<=200:
        return True
    else:
        return False
#隨機生成蘋果
def gameLoop():
    global apple_x,apple_y,aim_x,aim_y,snake
    snake.append([snake[-1][0]+aim_x,snake[-1][1]+aim_y])
    if not inside():
        sleep(2)
        # snake = [[0,0],[10,0],[20,0],[30,0],[40,0],[50,0]]
        # apple_x = randrange(-20,20)*10   
        # apple_y = randrange(-20,20)*10  
        # aim_x = 10
        # aim_y = 0
        return
    #吃蘋果
    if snake[-1][0] != apple_x or snake[-1][1]!=apple_y:
        snake.pop(0) # 加一個元素  刪除一個元素  蛇就往前執行了
    else:
        apple_x = randrange(-20,20)*10   
        apple_y = randrange(-20,20)*10 

    clear() # 清楚之前畫的痕跡
    squre(apple_x,apple_y,10,'red')    ## x y 位置  圖形大小  顏色
    for n in range(len(snake)):
        squre(snake[n][0],snake[n][1],10,'black')

    ontimer(gameLoop,100) #每100毫秒執行一次
    update()

### 主程式
setup(420,420,0,0)
hideturtle()  ## 隱藏箭頭
tracer(False) ## 不延時
listen() #監聽
onkey(lambda: change(0,10), "w")
onkey(lambda: change(0,-10), "s")
onkey(lambda: change(-10,0), "a")
onkey(lambda: change(10,0), "d")

gameLoop()
done()