请选择 进入手机版 | 继续访问电脑版
设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: manhong2112

新人報到

[复制链接]

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

发表于 2016-3-8 23:06:12 |显示全部楼层
有空寫代碼了, 而且在官網找到了3.5版的pygame, 所以把Pygame版的2048做出來了
  1. import random
  2. from copy import deepcopy as copy

  3. import pygame


  4. def calc_color(i):
  5.     return 255 - (i ** 2 % 255)


  6. class Game(object):
  7.     vector = {pygame.K_w: (0, 1),
  8.               pygame.K_s: (0, -1),
  9.               pygame.K_a: (1, 0),
  10.               pygame.K_d: (-1, 0)}

  11.     def __init__(self):
  12.         self.block = ([0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0])
  13.         self.recently_block = copy(self.block)
  14.         self.block[random.randint(0, 3)][random.randint(0, 3)] = random.choice((2, 2, 4))
  15.         pass

  16.     def next(self):
  17.         loc_list = []
  18.         for x in range(4):
  19.             for y in range(4):
  20.                 if not self.block[x][y]:
  21.                     loc_list.append((x, y))

  22.         if loc_list:
  23.             if self.recently_block == self.block:
  24.                 return True
  25.         else:
  26.             return self.movable()

  27.         loc = random.choice(loc_list)
  28.         self.block[loc[0]][loc[1]] = random.choice((2, 2, 4))
  29.         return True
  30.         pass

  31.     def end(self):
  32.         self.print()
  33.         print("# END #")
  34.         print("# Your Score is: {0} #".format(self.score()))
  35.         input("Enter to continue...")
  36.         exit()
  37.         pass

  38.     def move(self, direction, is_check=False):
  39.         cache = copy(self.block)
  40.         dx, dy = self.vector[direction]
  41.         i = ()
  42.         while i != cache:
  43.             i = copy(cache)
  44.             for x in range(3, -1, -1):
  45.                 for y in range(3, -1, -1):
  46.                     _x, _y = x - dx, y - dy
  47.                     if not (0 <= _x < 4 and 0 <= _y < 4):
  48.                         continue
  49.                     if cache[y][x] and (not cache[_y][_x] or cache[y][x] == cache[_y][_x]):
  50.                         cache[_y][_x] += cache[y][x]
  51.                         cache[y][x] = 0
  52.         if is_check:
  53.             return cache != self.block

  54.         self.recently_block = copy(self.block)
  55.         self.block = cache
  56.         pass

  57.     def movable(self):
  58.         for i in (pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d):
  59.             if self.move(i, True):
  60.                 return True
  61.         return False
  62.         pass

  63.     def print(self, display=None, _font=None):
  64.         if display is None or _font is None:
  65.             for x in range(4):
  66.                 for y in range(4):
  67.                     print(self.block[x][y], end=' ')
  68.                 print()
  69.         else:
  70.             for x in range(4):
  71.                 for y in range(4):
  72.                     v = self.block[x][y]
  73.                     pygame.draw.rect(
  74.                             display,
  75.                             (calc_color(v ** 2), calc_color(v ** 3), calc_color(v ** 5)),  # color
  76.                             (120 * y, 120 * x, 120, 120))  # x, y ,width, height
  77.                     display.blit(
  78.                             _font.render(
  79.                                     str(v) if v != 0 else "",
  80.                                     1,
  81.                                     (30, 30, 30)
  82.                             ),
  83.                             (120 * y + 54, 120 * x + 54))
  84.         pass

  85.     def score(self):
  86.         def _f(val, score=0):
  87.             for i in val:
  88.                 score += _f(i) if type(i) == list else i
  89.             return score

  90.         return _f(self.block)


  91. pygame.init()
  92. screen = pygame.display.set_mode((480, 480), 0, 32)
  93. pygame.display.set_caption("2048")

  94. font = pygame.font.SysFont("arial", 20)

  95. game = Game()
  96. game.print(screen, font)

  97. k = ""
  98. finish = False

  99. while True:
  100.     for event in pygame.event.get():
  101.         if event.type == pygame.QUIT:
  102.             pygame.quit()
  103.             exit()
  104.         if event.type == pygame.KEYDOWN:
  105.             if event.key == pygame.K_ESCAPE:
  106.                 pygame.quit()
  107.                 exit()

  108.             if event.key == pygame.K_r:
  109.                 game.print(screen, font)
  110.                 game = Game()
  111.                 finish = False

  112.             if finish:
  113.                 game.print(screen, font)
  114.                 screen.blit(font.render(
  115.                                 "You lose, total score is {}".format(game.score()),
  116.                                 1,
  117.                                 (30, 30, 30)
  118.                             ), (120, 240))
  119.                 screen.blit(font.render(
  120.                                 "press ESC to leave",
  121.                                 1,
  122.                                 (30, 30, 30)
  123.                             ), (128, 260))
  124.                 screen.blit(font.render(
  125.                                 "press R to restart",
  126.                                 1,
  127.                                 (30, 30, 30)
  128.                             ), (128, 280))

  129.                 pygame.display.update()
  130.                 continue

  131.             k = event.key
  132.             try:
  133.                 game.move(k)
  134.                 finish = not game.next()
  135.             except KeyError:
  136.                 continue
  137.             finally:
  138.                 game.print(screen, font)
  139.                 k = ""

  140.     pygame.display.update()
复制代码
回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

发表于 2016-3-9 14:55:53 |显示全部楼层
manhong2112 发表于 2016-3-8 23:06
有空寫代碼了, 而且在官網找到了3.5版的pygame, 所以把Pygame版的2048做出來了

这个不错
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

发表于 2016-4-5 21:04:23 |显示全部楼层
本帖最后由 manhong2112 于 2016-4-5 22:59 编辑

Y算子 + 部分邱奇碼, 弄出來後只感覺lambda真強大...
  1. Y = (lambda F: ((lambda u: u(u))(lambda f: F(lambda v: f(f)(v)))))
  2. Y(lambda f: (lambda x: 1 if x <= 2 else f(x - 1) + f(x - 2)))(5)
  3. Y(lambda f: (lambda x: 1 if x == 0 else x * f(x - 1)))(5)

  4. TRUE = lambda t,f: t
  5. FALSE = lambda t,f: f
  6. IF = lambda b,t,f: b(t,f)
  7. AND = lambda b1, b2: IF(b1, b2, FALSE)
  8. OR = lambda b1, b2: IF(b1, TRUE, b2)
  9. NOT = lambda b: IF(b, FALSE, TRUE)
复制代码
回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

发表于 2016-4-6 10:40:46 |显示全部楼层
manhong2112 发表于 2016-4-5 21:04
Y算子 + 部分邱奇碼, 弄出來後只感覺lambda真強大...

#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

发表于 2016-4-7 19:01:49 |显示全部楼层
本帖最后由 manhong2112 于 2016-12-17 23:38 编辑

簡單的lisp解釋器...

  1. from copy import copy

  2. def pick(k, e):
  3.     try:
  4.         return e[k]
  5.     except Exception:
  6.         return k

  7. def put(k, v, e):
  8.     e[k] = v
  9.     return e

  10. def put_rec(pair, e):
  11.     for k, v in pair:
  12.         e[k] = interp(v, e)
  13.     return e


  14. class Closure:
  15.     def __str__(self):
  16.         return "<Closure exp({}), env({})>".format(self.exp, self.env)
  17.         pass

  18.     def __init__(self, exp, env):
  19.         self.exp = exp
  20.         self.env = env


  21. class quote:
  22.     def __str__(self):
  23.         return "<quote %s>".format(self.lst)

  24.     def __init__(self, lst):
  25.         self.lst = lst
  26.         pass

  27.     def cons(x, _quote):
  28.         l = copy(_quote.lst[::-1])
  29.         l.append(str(x))
  30.         return quote(l[::-1])

  31.     def car(_quote):
  32.         return _quote.lst[0]

  33.     def cdr(_quote):
  34.         return quote(_quote.lst[1:])

  35.     def pick(i, _quote):
  36.         return _quote.lst[i + 1]

  37.     def put(i, v, _quote):
  38.         l = copy(_quote.lst[:])
  39.         l[i] = v
  40.         return quote(l)


  41. def interp(scheme, env={}):
  42.     if isinstance(scheme, str):
  43.         if (scheme[0] == "-" and scheme[1:].isdigit()) or scheme.isdigit():
  44.             return eval(scheme)
  45.         if scheme == "True" or scheme == "False":
  46.             return eval(scheme)
  47.         return pick(scheme, env)

  48.     if isinstance(scheme, list):
  49.         v0 = interp(scheme[0], env)
  50.         if isinstance(v0, Closure):
  51.             return interp(v0.exp[2], put(v0.exp[1][0], interp(scheme[1], env), v0.env))

  52.         if v0 in ("if", "lambda", "let"):
  53.             return {
  54.                 "if": lambda: interp(scheme[2 if interp(scheme[1], env) else 3], env),
  55.                 "lambda": lambda: Closure(scheme, copy(env)),
  56.                 "let": lambda: interp(scheme[2], put_rec(scheme[1], env))
  57.             }[v0]()

  58.         v1 = interp(scheme[1], env)
  59.         if v0 in ("car", "cdr"):
  60.             return {
  61.                 "car": lambda: quote.car(v1),
  62.                 "cdr": lambda: quote.cdr(v1)
  63.             }[v0]()

  64.         v2 = interp(scheme[2], env)
  65.         if v0 in ("pick", "cons", "+", "-", "*", "/", "^", "=", ">", "<", "<=", ">="):
  66.             return {
  67.                 "pick": lambda: quote.pick(v1, v2),
  68.                 "cons": lambda: quote.cons(v1, v2),
  69.                 "+": lambda: v1 + v2,
  70.                 "-": lambda: v1 - v2,
  71.                 "*": lambda: v1 * v2,
  72.                 "/": lambda: v1 / v2,
  73.                 "^": lambda: v1 ** v2,
  74.                 "=": lambda: v1 == v2,
  75.                 ">": lambda: v1 > v2,
  76.                 "<": lambda: v1 < v2,
  77.                 "<=": lambda: v1 <= v2,
  78.                 ">=": lambda: v1 >= v2
  79.             }[v0]()


  80. # (lambda arg exp) => Closure((lambda arg exp) env)
  81. # (Closure(lambda env) arg)
  82. # (quote (lst))
  83. # (if b t f)
  84. # (op e1 e2)
  85. # (let ((k1 exp1) .. (kn expn)) exp)

  86. # parser str to list
  87. def parser(s):
  88.     def _f(index):
  89.         result = []
  90.         t = ""
  91.         while True:
  92.             if s[index] == "(":
  93.                 x, index = _f(index + 1)
  94.                 result.append(x)
  95.             c = s[index]
  96.             if c == ")":
  97.                 if t != "":
  98.                     result.append(t)
  99.                 return result, index + 1
  100.             elif c == " ":
  101.                 if t != "":
  102.                     result.append(t)
  103.                     t = ""
  104.             else:
  105.                 t += c
  106.             index += 1
  107.     return _f(1)[0]


  108. print(interp(parser("(let ((abs (lambda (n) (if (< n 0) (- 0 n) n)))) (abs -5))")))
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

发表于 2016-4-8 17:35:53 |显示全部楼层
本帖最后由 manhong2112 于 2016-8-14 16:14 编辑

infix 轉成 postfix
  1. priority = {
  2.     "+": 0,
  3.     "-": 0,
  4.     "*": 1,
  5.     "/": 1
  6. }


  7. def to_postfix(expr, start=0):
  8.     stack = []
  9.     result = []
  10.     buffer = ""
  11.     i = start
  12.     while i < len(expr):
  13.         if expr[i].isalpha() or expr[i].isdigit():
  14.             if expr[i].isdigit():
  15.                 buffer += expr[i]
  16.             else:
  17.                 result.append(expr[i])
  18.             i += 1
  19.             continue
  20.         if buffer != "":
  21.             result.append(buffer)
  22.             buffer = ""
  23.         if(expr[i] == "("):
  24.             x = to_postfix(expr, i + 1)
  25.             result += x[0]
  26.             i = x[1]
  27.         elif(expr[i] == ")"):
  28.             result += "".join(stack[::-1])
  29.             return result, i
  30.         else:
  31.             if len(stack) != 0 and priority[expr[i]] < priority[stack[-1]]:
  32.                 result += stack.pop()
  33.             stack.append(expr[i])
  34.         i += 1
  35.     result.extend(stack[::-1])
  36.     return result, i
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

发表于 2016-4-9 13:11:40 |显示全部楼层
本帖最后由 manhong2112 于 2016-12-8 21:44 编辑

之前寫的一堆排序算法...
  1. import random
  2. import timeit


  3. def printf(string, *obj):
  4.     return print(string.format(*obj))


  5. def bubble_sort(arr):
  6.     arr = arr[:]
  7.     for i in range(len(arr) - 1, 0, -1):
  8.         for j in range(i):
  9.             if arr[j] > arr[j + 1]:
  10.                 arr[j], arr[j + 1] = arr[j + 1], arr[j]
  11.     return arr


  12. def quick_sort(arr):
  13.     if len(arr) <= 1:
  14.         return arr
  15.     a = arr[0]
  16.     b = []
  17.     c = []
  18.     for i in arr[1:]:
  19.         (b if i < a else c).append(i)
  20.     return quick_sort(b) + [a] + quick_sort(c)


  21. def swap(arr, x, y):
  22.     arr[x], arr[y] = arr[y], arr[x]

  23. def quicksort_inplace_iter(arr):
  24.     stack = [(0, len(arr))]
  25.     while stack:
  26.         s, e = stack.pop()
  27.         s1, e1 = s, e
  28.         if s >= e:
  29.             continue
  30.         i = s
  31.         x = arr[e-1]
  32.         while s+1 < e1:
  33.             if arr[s] > x:
  34.                 swap(arr, s, e1 - 1)
  35.                 e1 -= 1
  36.             else:
  37.                 swap(arr, s, s1)
  38.                 s1 += 1
  39.             s += 1
  40.         stack.append((i, s))
  41.         stack.append((s+1, e))

  42. def random_arr(length):
  43.     arr = []
  44.     for i in range(length):
  45.         arr.append(random.randint(0, length ** 2))
  46.     return arr


  47. def merge_sort(arr):
  48.     def merge(arr1, arr2):
  49.         result = []
  50.         i = 0
  51.         j = 0
  52.         while True:
  53.             if i == len(arr1):
  54.                 result.extend(arr2[j:])
  55.                 break
  56.             if j == len(arr2):
  57.                 result.extend(arr1[i:])
  58.                 break
  59.             if arr1[i] < arr2[j]:
  60.                 result.append(arr1[i])
  61.                 i += 1
  62.             else:
  63.                 result.append(arr2[j])
  64.                 j += 1
  65.         return result

  66.     length = len(arr)
  67.     if length <= 1:
  68.         return arr
  69.     return arr if length <= 1 else merge(
  70.         merge_sort(arr[:int(length / 2)]),
  71.         merge_sort(arr[int(length / 2):]))


  72. def select_sort(arr):
  73.     for i in range(len(arr)):
  74.         for j in range(i, len(arr)):
  75.             if arr[j] < arr[i]:
  76.                 arr[i], arr[j] = arr[j], arr[i]
  77.     return arr


  78. def time(fun, *arr):
  79.     s = timeit.default_timer()
  80.     fun(*arr)
  81.     e = timeit.default_timer()
  82.     return((e - s) * 1000)
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

发表于 2016-6-26 19:38:46 |显示全部楼层
筆記本
  1. import os
  2. import math
  3. import pickle
  4. sum = lambda x: 0 if len(x) == 0 else x[0] + sum(x[1:])


  5. class Reader(object):

  6.     def __init__(self, path=None):
  7.         self.Note = NoteManager.get_note(path)
  8.         self.Note.load()
  9.         pass

  10.     def read(self):
  11.         return self.Note.Context

  12.     def write(self, context):
  13.         self.Note.Context = context
  14.         pass

  15.     def write_line(self, context):
  16.         self.Note.Context += context
  17.         self.Note.Context += "\n"
  18.         pass

  19.     def append(self, context):
  20.         self.Note.Context += context
  21.         pass

  22.     def save(self):
  23.         with open(self.Note.nPath, "wb+") as f:
  24.             pickle.dump((self.Note.Context, self.Note.Type), f)


  25. class Note(object):
  26.     storageLoc = "./note"

  27.     def __init__(self, path, name, file_type="Text"):
  28.         assert type(name) is str
  29.         assert type(path) is str
  30.         assert type(file_type) is str
  31.         self.Name = name
  32.         self.Type = file_type
  33.         self.id = path
  34.         self.nPath = os.path.join(self.storageLoc, path)
  35.         self.Context = ""

  36.     def load(self):
  37.         os.makedirs(os.path.dirname(self.nPath), exist_ok=True)
  38.         if not os.path.isfile(self.nPath):
  39.             with open(self.nPath, "wb+") as f:
  40.                 pickle.dump(("", self.Type), f)
  41.         with open(self.nPath, "rb+") as f:
  42.             self.Context, self.Type = pickle.load(f)


  43. class NoteManager(object):
  44.     note_pool_loc = "./NoteList.db"
  45.     __note_pool = {}

  46.     @staticmethod
  47.     def get_note(path):
  48.         pool, name = NoteManager.parse_path(path)
  49.         return pool[name]["Note"]
  50.         pass

  51.     @staticmethod
  52.     def new_note(path, name, file_type="Text"):
  53.         n = Note(path, name, file_type)
  54.         NoteManager.add_note(path, n)
  55.         pass

  56.     @staticmethod
  57.     def filter(dir, f):
  58.         assert type(dir) is str
  59.         result = []
  60.         pool, name = NoteManager.parse_path(dir)
  61.         for i in pool:
  62.             if i[-1] == "/":
  63.                 result.extend(NoteManager.filter(dir + i, f))
  64.             elif (pool[i]["Tag"] & f) == f:
  65.                 result.append(dir + i)
  66.         return sorted(result)
  67.         pass

  68.     @staticmethod
  69.     def save():
  70.         tmp = {}

  71.         def _f(path, pool):
  72.             for p in pool:
  73.                 if p[-1] == "/":
  74.                     _f(path + p, pool[p])
  75.                 else:
  76.                     x = pool[p]
  77.                     tmp[p] = {"Tag": x["Tag"], "Name": x["Note"].Name}
  78.         _f("", NoteManager.__note_pool)
  79.         with open(NoteManager.note_pool_loc, "wb+") as f:
  80.             pickle.dump(tmp, f)
  81.         pass

  82.     @staticmethod
  83.     def add_note(path, note):
  84.         pool, name = NoteManager.parse_path(path)
  85.         pool[name] = {"Tag": 0, "Note": note}
  86.         pass

  87.     @staticmethod
  88.     def del_note(path):
  89.         os.remove(os.path.join(Note.storageLoc, path))
  90.         pool, name = NoteManager.parse_path(path)
  91.         pool.remove(name)
  92.         pass

  93.     @staticmethod
  94.     def add_tag(path, *tag):
  95.         pool, name = NoteManager.parse_path(path)
  96.         t = sum(tag)
  97.         if (pool[name]["Tag"] & t) != t:
  98.             pool[name]["Tag"] += t

  99.     @staticmethod
  100.     def del_tag(path, *tag):
  101.         pool, name = NoteManager.parse_path(path)
  102.         t = sum(tag)
  103.         if (pool[name]["Tag"] & t) == t:
  104.             pool[name]["Tag"] -= t

  105.     @staticmethod
  106.     def get_tag(path):
  107.         pool, name = NoteManager.parse_path(path)
  108.         t = pool[name]["Tag"]
  109.         tag = set({})
  110.         while t != 0:
  111.             x = int(math.log(t, 2))
  112.             t -= x
  113.             tag.add(TagManager.tag(x))
  114.             pass
  115.         return tag

  116.     @staticmethod
  117.     def parse_path(path):
  118.         x = path.split("/")
  119.         pool = NoteManager.__note_pool
  120.         for i in x[:-1]:
  121.             if i + "/" not in pool:
  122.                 pool[i + "/"] = {}
  123.             pool = pool[i + "/"]
  124.         return pool, x[-1]

  125.     if not os.path.isfile(note_pool_loc):
  126.         with open(note_pool_loc, "wb+") as f:
  127.             pickle.dump(__note_pool, f)
  128.     else:
  129.         with open(os.path.join(note_pool_loc), "rb+") as f:
  130.             tmp = pickle.load(f)
  131.         for i in tmp:
  132.             x = i.split("/")
  133.             pool = __note_pool
  134.             for i in x[:-1]:
  135.                 if i + "/" not in pool:
  136.                     pool[i + "/"] = {}
  137.                 pool = pool[i + "/"]
  138.             name = x[-1]
  139.             pool[name] = {"Tag": tmp[i]["Tag"],
  140.                           "Note": Note(i, tmp[i]["Name"])}


  141. class TagManager(object):
  142.     tag_pool_loc = "TagList.db"
  143.     __tag_pool = []

  144.     @staticmethod
  145.     def mk_filter(*tag):
  146.         return sum(tag)

  147.     @staticmethod
  148.     def new_tag(tag_name):
  149.         if tag_name not in TagManager.__tag_pool:
  150.             TagManager.__tag_pool.append(tag_name)
  151.         pass

  152.     @staticmethod
  153.     def tag(x):
  154.         if type(x) is str:
  155.             return 2**TagManager.__tag_pool.index(x)
  156.         elif type(x) is int:
  157.             return TagManager.__tag_pool[math.log(x, 2)]

  158.     @staticmethod
  159.     def save():
  160.         with open(os.path.join(TagManager.tag_pool_loc), "wb+") as f:
  161.             pickle.dump(TagManager.__tag_pool, f)
  162.         pass

  163.     if os.path.isfile(tag_pool_loc):
  164.         with open(os.path.join(tag_pool_loc), "rb+") as f:
  165.             __tag_pool = pickle.load(f)
  166.     else:
  167.         with open(os.path.join(tag_pool_loc), "wb+") as f:
  168.             pickle.dump(__tag_pool, f)

复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

发表于 2016-8-15 20:25:00 |显示全部楼层
本帖最后由 manhong2112 于 2016-8-25 18:34 编辑

Brainfuck 解釋器(+半個編譯器)

  1. import msvcrt


  2. def interp(expr):
  3.     ptr = 0
  4.     ram = dict()
  5.     loopStack = []
  6.     excapingLoop = 0
  7.     i = 0
  8.     while(i < len(expr)):
  9.         # print(ram, loopStack, excapingLoop)
  10.         x = expr[i]
  11.         if not (ptr in ram) or ram[ptr] > 127 or ram[ptr] < -128:
  12.             ram[ptr] = 0
  13.         if x == "[":
  14.             if excapingLoop > 0:
  15.                 excapingLoop += 1
  16.             elif ram[ptr] != 0:
  17.                 loopStack.append(i)
  18.             else:
  19.                 excapingLoop = 1
  20.         elif x == "]":
  21.             if excapingLoop > 0:
  22.                 excapingLoop -= 1
  23.             elif ram[ptr] != 0:
  24.                 i = loopStack[-1]
  25.             else:
  26.                 loopStack.pop()
  27.         elif excapingLoop > 0:
  28.             pass
  29.         elif x == "+":
  30.             ram[ptr] += 1
  31.         elif x == "-":
  32.             ram[ptr] -= 1
  33.         elif x == ">":
  34.             ptr += 1
  35.         elif x == "<":
  36.             ptr -= 1
  37.         elif x == ".":
  38.             print(chr(ram[ptr]), end="")
  39.             pass
  40.         elif x == ",":
  41.             ram[ptr] = ord(msvcrt.getch())
  42.         i += 1

  43. version = 0x01
  44. header = [0x00, 0x10, 0x26, 0xBF, version, 0x00]
  45. # null, id, id, ver, id, mem_len


  46. class ID():
  47.     START_LOOP = 0
  48.     END_LOOP = 1
  49.     INC = 2
  50.     DEC = 3
  51.     NEXT = 4
  52.     BACK = 5
  53.     GETC = 6
  54.     PUTC = 7

  55.     ADD = 8
  56.     MOVE = 9


  57. def compile(expr):
  58.     result = header.copy()
  59.     state = 0
  60.     tmp = 0
  61.     memloc = 0
  62.     mmemloc = 0
  63.     loopStack = []
  64.     i = 0
  65.     while i <= len(expr):
  66.         # print(ram, loopStack, excapingLoop)
  67.         if memloc > mmemloc:
  68.             mmemloc = memloc
  69.         x = expr[i] if i != len(expr) else 0xFF
  70.         if state == 0:
  71.             if x == "[":
  72.                 loopStack.append(len(result))
  73.                 result.append(ID.START_LOOP)
  74.                 result.append(0)
  75.                 if memloc == 0:
  76.                     memloc = 1
  77.             elif x == "]":
  78.                 a = loopStack.pop()
  79.                 result[a + 1] = len(result) - a - 1
  80.                 result.append(ID.END_LOOP)
  81.                 result.append(len(result) - a + 1)
  82.             elif x == "+":
  83.                 state = ID.ADD
  84.                 tmp += 1
  85.             elif x == "-":
  86.                 state = ID.ADD
  87.                 tmp -= 1
  88.             elif x == ">":
  89.                 state = ID.MOVE
  90.                 tmp += 1
  91.             elif x == "<":
  92.                 state = ID.MOVE
  93.                 tmp -= 1
  94.             elif x == ".":
  95.                 result.append(ID.PUTC)
  96.             elif x == ",":
  97.                 result.append(ID.GETC)
  98.         elif state == ID.ADD:
  99.             if x in "+-":
  100.                 if x == "+":
  101.                     tmp += 1
  102.                 elif x == "-":
  103.                     tmp -= 1
  104.             else:
  105.                 if tmp == 0:
  106.                     pass
  107.                 elif tmp == 1:
  108.                     result.append(ID.INC)
  109.                 elif tmp == -1:
  110.                     result.append(ID.DEC)
  111.                 else:
  112.                     result.append(ID.ADD)
  113.                     result.append(tmp)
  114.                 state = 0
  115.                 i -= 1
  116.                 tmp = 0
  117.         elif state == ID.MOVE:
  118.             if x in "><":
  119.                 if x == ">":
  120.                     tmp += 1
  121.                 elif x == "<":
  122.                     tmp -= 1
  123.             else:
  124.                 if tmp == 0:
  125.                     pass
  126.                 elif tmp == 1:
  127.                     result.append(ID.NEXT)
  128.                     memloc += 1
  129.                 elif tmp == -1:
  130.                     result.append(ID.BACK)
  131.                     memloc -= 1
  132.                 else:
  133.                     result.append(ID.MOVE)
  134.                     result.append(tmp)
  135.                     memloc += tmp
  136.                 i -= 1
  137.                 state = 0
  138.                 tmp = 0
  139.         i += 1
  140.     result[5] = mmemloc
  141.     result.append(0xFF)
  142.     return result


  143. class Env(object):
  144.     def __init__(self, mem_len):
  145.         self.data = [0] * (mem_len + 1)
  146.         self.ptr = 0

  147.     def move(self, val):
  148.         self.ptr += val

  149.     def read(self):
  150.         return self.data[self.ptr]

  151.     def write(self, val):
  152.         self.data[self.ptr] = val if -128 <= val <= 127 else 0


  153. def execute(compiledExpr):
  154.     expr = compiledExpr
  155.     i = len(header)
  156.     env = Env(expr[5])
  157.     while i < len(expr) - 1:
  158.         x = expr[i]
  159.         if x == ID.INC:
  160.             env.write(env.read() + 1)
  161.         elif x == ID.DEC:
  162.             env.write(env.read() - 1)
  163.         elif x == ID.NEXT:
  164.             env.move(1)
  165.         elif x == ID.BACK:
  166.             env.move(-1)
  167.         elif x == ID.PUTC:
  168.             print(chr(env.read()), end="")
  169.         elif x == ID.GETC:
  170.             env.write(ord(msvcrt.getch()))
  171.         else:
  172.             if x == ID.START_LOOP and env.read() == 0:
  173.                 i += expr[i + 1]
  174.             elif x == ID.END_LOOP and env.read() != 0:
  175.                 i -= expr[i + 1]
  176.             elif x == ID.ADD:
  177.                 env.write(env.read() + expr[i + 1])
  178.             elif x == ID.MOVE:
  179.                 env.move(expr[i + 1])
  180.             i += 1
  181.         i += 1

  182. import timeit


  183. def time(fun, *arr):
  184.     s = timeit.default_timer()
  185.     fun(*arr)
  186.     e = timeit.default_timer()
  187.     return((e - s) * 1000)

  188. expr = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
  189. cexpr = compile(expr)

  190. x1, x2 = 0, 0
  191. for i in range(0, 100):
  192.     x1 += time(execute, cexpr)
  193. for i in range(0, 100):
  194.     x2 += time(interp, expr)

  195. print(x1 / 100)
  196. print(x2 / 100)
复制代码
回复

使用道具 举报

0

主题

0

好友

8

积分

新手上路

Rank: 1

发表于 2016-8-15 22:13:38 |显示全部楼层
做的很好,不過請問代碼編輯器是怎麼弄出來。

   
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-3-29 18:39 , Processed in 0.030155 second(s), 20 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部