python 50行写个贪吃蛇

50行python写个贪吃蛇

别问我为什么这么无聊,我只是想告诉一个小朋友。。。贪吃蛇真的不需要用150行来写

上图

效果图

嗯,代码

import random
import msvcrt # 读取键盘要用
import os; os.system("chcp 65001 & cls") # 设定控制台编码为UTF8
w, h  = 30, 15 # 沙盘大小设定

directions = {72:[0,-1],77:[1,0],80:[0,1],75:[-1,0]} # 四个方向,用方向键低位编号表示
headpos = [random.randint(0, w-1), random.randint(0, h-1)] # 头部位置
headdpos = directions[random.choice([72,77,80,75])] # 头部位置的变化,相当于头部方向
snake = [headpos] #蛇身,其实就是一堆坐标
foods = [] #食物
def posChar(pos): #决定某个坐标显示的东西
    return ((pos in snake and "*") or 
            (pos in foods and "%") or " " )

def printSnake():
    outputs = []
    outputs.append("欢迎来到雪星实验室 - 贪吃蛇 ================================")
    for y in range(h):
        outputs.append("|" + " ".join([ posChar([x, y]) for x in range(w)] ) + " |")
    outputs.append("欢迎来到雪星实验室 - 贪吃蛇 ================================")

    os.system("cls")
    print("\n".join(outputs))

def go():
    global headdpos
    global headpos
    if random.random() < 0.1 or foods.__len__() == 0:
        foods.append([random.randint(0, w-1), random.randint(0, h-1)])
    printSnake() #先打印当前地图
    userkey = msvcrt.getch() == b'\xe0' and msvcrt.getch() or " " # 等待用户按键
    headdpos = directions.get(ord(userkey), headdpos) # 根据按键设定方向
    headpos = [x+y for x, y in zip(headpos, headdpos)] # 坐标相加
    snake.insert(0, headpos) # 向头部前进一个位置
    if headpos in foods: # 如果吃到了食物
        foods.remove(headpos) # 就移除这个食物
    else: #如果没东西吃
        snake.pop() # 那蛇尾就没掉了

def liveQ():
    return  ((headpos[0] in range(w) and headpos[1] in range(h)) # 没撞墙
             and (not headpos in snake[2:]  ) ) # 也没撞自己

while(liveQ()):
    go()

print("大侠请重新来过 ..................")
input()

评论