python实现一个简单的2048游戏
2018-07-20 来源:open-open
[Python]代码
# -*- coding: utf8 -*- import random data = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] _MAX_X = 4 _MAX_Y = 4 _RECT_SIZE = _MAX_X * _MAX_Y class GameOverException(Exception): pass def zero_list(size): return [0] * size def initialize(): for index in range(_MAX_Y): data[index] = zero_list(_MAX_X) new_pos() def is_empty(x, y): try: return data[y][x] == 0 except IndexError as e: return False def to_xy(no): return no % _MAX_Y, no // _MAX_X def get_random_pos(): no = random.randint(0, _RECT_SIZE - 1) for index in range(no, _RECT_SIZE): x, y = to_xy(index) if is_empty(x, y): return x, y raise GameOverException def print_map(): for row in data: print(row) def get_by_xy(x, y): return data[y][x] def get_row(index): return data[index] def get_col(index): return [row[index] for row in data] def replace_col(index, col): assert type(col) == list assert len(col) == _MAX_Y for y in range(_MAX_Y): data[y][index] = col[y] def replace_row(index, row): assert type(row) == list assert len(row) == _MAX_X for x in range(_MAX_X): data[index][x] = row[x] def merge_data(src, *, reverse=False): pre_len = len(src) source = [item for item in src if item != 0] if reverse: source.reverse() for start in range(1, len(source) // 2 + 1): for index in range(start, len(source) - start + 1): moon = source[index - 1] star = source[index] if moon == star: moon += star star = 0 elif moon == 0: moon = star star = 0 source[index - 1] = moon source[index] = star source.extend(zero_list(pre_len - len(source))) if reverse: source.reverse() return source def new_pos(): x, y = get_random_pos() data[y][x] = 2 def show(): print_map() def vertical(*, reverse=False): changed = False for index in range(_MAX_X): source = get_col(index) summary = merge_data(source, reverse=reverse) changed |= (summary != source) replace_col(index, summary) return changed def horizontal(*, reverse=False): changed = False for index in range(_MAX_Y): source = get_row(index) summary = merge_data(source, reverse=reverse) changed |= (summary != source) replace_row(index, summary) return changed def up(): if vertical(): new_pos() def down(): if vertical(reverse=True): new_pos() def left(): if horizontal(): new_pos() def right(): if horizontal(reverse=True): new_pos() if __name__ == '__main__': pass
标签: 代码
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐