1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| import curses from random import randrange, choice from collections import defaultdict
actions = [‘Up’, ’Left’, ’Down’, ’Right’, ’Restart’, ’Exit’]
letter_codes = [ord(ch) for ch in ‘WASDRQwasdrq’]
actions_dict = dict(zip(letter_codes, actions * 2))
def main(stdscr):
def init(): return 'Game'
def not_game(state): responses = defaultdict(lambda: state) responses['Restart'], responses['Exit'] = 'Init', 'Exit'
return responses[action]
def game():
if action == 'Restart': return 'Init' if action == 'Exit': return 'Exit' if Win: return 'Win' if Gameover: return 'Gameover' return 'Game'
state_actions = { 'Init': init, 'Win': lambda: not_game('Win'), 'Gameover': lambda: not_game('Gameover'), 'Game': game }
state = 'Init'
while state != 'Exit': state = state_actions[state]()
def get_user_action(keyboard): char = 'N' while char not in actions_dict: 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 = 2048 self.hightscore = 0 self.reset()
def spawn(self): new_element = 4 if randrange(100) > 89 else 2 (i, j) = chioce([(i, j) for i in range(self, width) for j in range(self, height) self.field[i][j] = new_element
def reset(self):
if self.score > self.highscore:
|