一、源码
import curses
from itertools import chain
from random import choice
class GameField(object):
# 初始化信息
def __init__(self, width=4, height=4, win_value=2048):
self.width = width
self.height = height
self.win_value = win_value
self.score = 0 # 当前得分
self.highscore = 0 # 最高分
self.moves = {}
self.moves['Left'] = self.is_move_left
self.moves['Right'] = self.is_move_right
self.moves['Down'] = self.is_move_down
self.moves['Up'] = self.is_move_up
self.movesDict = {}
self.movesDict['Left'] = self.move_left
self.movesDict['Right'] = self.move_right
self.movesDict['Down'] = self.move_down
self.movesDict['Up'] = self.move_up
def reset(self): # 重置棋盘
if self.score > self.highscore:
self.highscore = self.score # 更新最高分
self.score = 0
# 需求1: 生成4*4的棋盘, 其中数据结构选择列表嵌套列表;
self.field = [[0 for j in range(self.width)]
for i in range(self.height)]
# 在棋盘的一个随机位置插入一个数字2或者4
self.random_create()
self.random_create()
def random_create(self):
# 在棋盘的一个随机位置插入一个数字2或者4
# field[0][3] = 2
while True:
i, j = choice(range(self.height)), choice(range(self.width))
if self.field[i][j] == 0:
self.field[i][j] = choice([2, 2, 2, 4])
break
def draw(self, stdscr):
def draw_sep():
stdscr.addstr('+' + "-----+"