- 帖子
- 52
- 精华
- 0
- 积分
- 207
- 阅读权限
- 30
- 注册时间
- 2016-1-15
- 最后登录
- 2016-12-17
|
本帖最后由 manhong2112 于 2016-1-20 21:08 编辑
2048 bj4- import random
- from copy import deepcopy as copy
- def print2048(block):
- for i in range(len(block)):
- print(str(block[i]).replace(", ", "]["))
- def get(block, x, y):
- a = copy(block)
- return a[y][x]
- def set(block, x, y, value):
- a = copy(block)
- a[y][x] = value
- return a
- def add(block, x, y, value):
- a = copy(block)
- a[y][x] += value
- return a
- def up(block):
- a = copy(block)
- for i in range(0, 4):
- for x in range(0, 4)[::-1]:
- for y in range(0, 3):
- if get(a, x, y + 1) == get(a, x, y) or get(a, x, y) == 0:
- a = add(a, x, y, get(a, x, y + 1))
- a = set(a, x, y + 1, 0)
- return a
- def down(block):
- a = copy(block)
- for i in range(0, 4):
- for x in range(0, 4):
- for y in range(1, 4):
- if get(a, x, y - 1) == get(a, x, y) or get(a, x, y) == 0:
- a = add(a, x, y, get(a, x, y - 1))
- a = set(a, x, y - 1, 0)
- return a
- def left(block):
- a = copy(block)
- for i in range(0, 4):
- for x in range(0, 3):
- for y in range(0, 4)[::-1]:
- if get(a, x + 1, y) == get(a, x, y) or get(a, x, y) == 0:
- a = add(a, x, y, get(a, x + 1, y))
- a = set(a, x + 1, y, 0)
- return a
- def right(block):
- a = copy(block)
- for i in range(0, 4):
- for x in range(1, 4):
- for y in range(0, 4):
- if get(a, x - 1, y) == get(a, x, y) or get(a, x, y) == 0:
- a = add(a, x, y, get(a, x - 1, y))
- a = set(a, x - 1, y, 0)
- return a
- def reset():
- a = ([0, 0, 0, 0],
- [0, 0, 0, 0],
- [0, 0, 0, 0],
- [0, 0, 0, 0])
- return set(a, random.randrange(0,4), random.randrange(0,4), random.choice([2, 4]))
- def add_number(block):
- a = copy(block)
- b = []
- for i in range(0, 4):
- for j in range(0, 4):
- if get(a, i, j) == 0:
- b.append((i, j))
- if (not b) and right(a) == left(a) == up(a) == down(a):
- print2048(a)
- print("You lose")
- exit()
- if (not b) or right(a) == left(a) == up(a) == down(a):
- return a
- c = random.choice(b)
- return set(block, c[0], c[1], random.choice([2, 4]))
- f = {"w": up,
- "a": left,
- "s": down,
- "d": right}
- block2048 = reset()
- while 1:
- block2048 = add_number(block2048)
- print2048(block2048)
- while 1:
- try:
- block2048 = f[input("Choose Direction (w a s d) > ")](block2048)
- except KeyError:
- print("E> Value Error")
- continue
- break
复制代码 |
|