资源简介
python实现的2048游戏,初学者可以下载看看。
代码片段和文件信息
#-*-coding:utf-8-*-
#-*-coding:utf-8-*-
import curses
from random import randrange choice
from collections import defaultdict
import argparse
import curses
from random import randrange choice # generate and place new tile
from collections import defaultdict
letter_codes = [ord(ch) for ch in ‘WASDRQwasdrq‘]
actions = [‘Up‘ ‘Left‘ ‘Down‘ ‘Right‘ ‘Restart‘ ‘Exit‘]
actions_dict = dict(zip(letter_codes actions * 2))
def get_user_action(keyboard):
char = “N“
while char not in actions_dict:
char = keyboard.getch()
return actions_dict[char]
#以左上角和右下角为轴,旋转180°,叫做矩阵转置
#[[135][246]]转换后[[12][34][56]]
‘‘‘
135 => 127
246 => 348
789 => 569
‘‘‘
def transpose(field):
return [list(row) for row in zip(*field)]
#中轴旋转180°,叫做矩阵逆置
#[[135][246]]转换后[[531][642]]
‘‘‘
135 => 531
246 => 642
789 => 987
‘‘‘
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):
#实现某一行的左移
#把某一行所有非0元素统一压缩的左边
#[20208]=>[22800]
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
#实现相邻元素的合并
#[22800]=>[04800]
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
‘‘‘
[04800]=>[48000]
‘‘‘
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
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 8522 2017-05-26 11:15 2048游戏\2048.py
文件 27671 2016-05-05 10:34 2048游戏\我的公众号,谢谢关注.jpg
目录 0 2017-05-26 11:29 2048游戏
----------- --------- ---------- ----- ----
36193 3
- 上一篇:xgboost安装包
- 下一篇:Python.CLF
评论
共有 条评论