专栏首页一去紫台连朔漠python3实现2048游戏
原创

python3实现2048游戏

# -*- coding: utf-8 -*- # url: https://www.shiyanlou.com/courses/368/learning/ import curses from random import randrange, choice # generate and place new tile from collections import defaultdict letter_codes = [ord(ch) for ch in 'WASDRQwasdrq'] # print(letter_codes) actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit'] actions_dict = dict(zip(letter_codes, actions * 2)) # print(actions_dict) def get_user_action(keyboard): char = 'N' while char not in actions_dict: # 返回按下键的 ascii 码值 char = keyboard.getch() return actions_dict[char] def transpose(field): return [list(row) for row in zip(*field)] def invert(field): return [row[::-1] for row in field] class GameField(object): def __init__(self, height=4, width=4, win=2048): self.height = height self.width = width self.win_value = win self.score = 0 self.highscore = 0 self.reset() def reset(self): if self.score > self.highscore: self.highscore = self.score self.score = 0 self.field = [[0 for i in range(self.width)] for j in range(self.height)] self.spawn() self.spawn() def move(self, direction): def move_row_left(row): def tighten(row): # squeese non-zero elements together new_row = [i for i in row if i != 0] new_row += [0 for i in range(len(row) - len(new_row))] return new_row def merge(row): pair = False new_row = [] for i in range(len(row)): if pair: new_row.append(2 * row[i]) self.score += 2 * row[i] pair = False else: if i + 1 < len(row) and row[i] == row[i + 1]: pair = True new_row.append(0) else: new_row.append(row[i]) assert len(new_row) == len(row) return new_row return tighten(merge(tighten(row))) moves = {} moves['Left'] = lambda field: [move_row_left(row) for row in field] moves['Right'] = lambda field: invert(moves['Left'](invert(field))) moves['Up'] = lambda field: transpose(moves['Left'](transpose(field))) moves['Down'] = lambda field: transpose(moves['Right'](transpose(field))) if direction in moves: if self.move_is_possible(direction): self.field = moves[direction](self.field) self.spawn() return True else: return False def is_win(self): return any(any(i >= self.win_value for i in row) for row in self.field) def is_gameover(self): return not any(self.move_is_possible(move) for move in actions) def draw(self, screen): help_string1 = '(W)Up (S)Down (A)Left (D)Right' help_string2 = ' (R)Restart (Q)Exit' gameover_string = ' GAME OVER' win_string = ' YOU WIN!' def cast(string): screen.addstr(string + '\n') def draw_hor_separator(): line = '+' + ('+------' * self.width + '+')[1:] separator = defaultdict(lambda: line) if not hasattr(draw_hor_separator, "counter"): draw_hor_separator.counter = 0 cast(separator[draw_hor_separator.counter]) draw_hor_separator.counter += 1 def draw_row(row): cast(''.join('|{: ^5} '.format(num) if num > 0 else '| ' for num in row) + '|') screen.clear() cast('SCORE: ' + str(self.score)) if 0 != self.highscore: cast('HIGHSCORE: ' + str(self.highscore)) for row in self.field: draw_hor_separator() draw_row(row) draw_hor_separator() if self.is_win(): cast(win_string) else: if self.is_gameover(): cast(gameover_string) else: cast(help_string1) cast(help_string2) def spawn(self): new_element = 4 if randrange(100) > 89 else 2 (i, j) = choice([(i, j) for i in range(self.width) for j in range(self.height) if self.field[i][j] == 0]) self.field[i][j] = new_element def move_is_possible(self, direction): def row_is_left_movable(row): def change(i): # true if there'll be change in i-th tile if row[i] == 0 and row[i + 1] != 0: # Move return True if row[i] != 0 and row[i + 1] == row[i]: # Merge return True return False return any(change(i) for i in range(len(row) - 1)) check = {} check['Left'] = lambda field: \ any(row_is_left_movable(row) for row in field)

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • centos磁盘空间满的问题处理.

    qdjx
  • Centos7.5 安装Cmake 3.6.2

    yum install -y gcc gcc-c++ make automake openssl-devel

    qdjx
  • 解决github下载慢的问题

    4.克隆gitee项目(git clone https://gitee.com/do_1977107948/games)

    qdjx
  • 古老的机械钟表蕴含着神秘的数学原理

    时间是一个比较抽象的概念,是物质运动、变化的持续性、顺序性的表现。正因为人们需要研究物质的运动,就必须通过一个中介者来认识和度量时间,这个中介者就是计时器,从古...

    不可言诉的深渊
  • 基于vagrant+VirtualBox快速搭建虚拟机

    咻一咻
  • python爬虫——爬取古诗名句

    py3study
  • [数据结构与算法] 链表的其他类型

    单链表是最简单的链表,单链表的一种变形就是循环单链表,其中最后一个结点的next域不用None,而是指向表的第一个结点,这样就形成了一种循环结构,所以叫循环单链...

    用户1622570
  • 腾讯高级副总裁郭凯天做客北大讲堂,谈腾讯与“互联网+”

    9月26日,腾讯高级副总裁郭凯天做客北大讲堂,围绕“互联网+”与腾讯发展战略进行了主题演讲。郭凯天表示,互联网正逐渐成为社会的基础设施,如水和电一样,融入各...

    腾讯研究院
  • Python | Python 新手不可错过的 Python 知识合集

    来源:https://segmentfault.com/a/1190000018737045

    咸鱼学Python
  • unittest测试驱动之执行测试(三)

    在unittest的模块中,提供了TestRunner类来进行运行测试用例,在实际的应用中,经常使用的是TextTestRunner类,执行后,会已文字...

    无涯WuYa

扫码关注云+社区

领取腾讯云代金券