#-*- coding: utf-8 -*-

import curses
from random import randrange, choice
from collections import defaultdict #Defines valid inputs to not allow for input errors
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
lettercodes = [ord(ch) for ch in 'WASDRQwasdrq']
actions_dict = dict(zip(lettercodes, actions * 2)) # Character not in dictonary so it adds it to the dictionary to make it recongized
def get_user_action(keyboard):
char = 'N'
while char not in actions_dict:
char = keyboard.getch()
return actions_dict[char] # Transpose of matrix to determine tile moveability
def transpose(field):
return [list(row) for row in zip(*field)] # Inversion of matrix to determine tile moveability
def invert(field):
return [row[::-1] for row in field] #Defines game terms: 4x4 matrix, if you get 2048 you win anf
class GameField(object):
def __init__(self, height=4, width=4, win=2048):
self.height = height
self.width = width
self.win_value = 2048
self.score = 0
self.highscore = 0
self.reset()
# Randomly inputs a either 2 or 4 into the board after a move has been made
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
# resets score but if a highscore it updates highscore first
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()
#Defines all the movements in the the game
def move(self, direction):
def move_row_left(row):
#Collapses one row once 2 tiles are merged
def tighten(row):
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
#merges 2 tiles if they are equal and multiplies the value by itself of the new tile. Them upates the score accordingly
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 same value will append the 2 tiles
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)))
#Shows valid moves for each direction
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 move is valid it will spawn a new random tile (2 or 4)
if direction in moves:
if self.move_is_possible(direction):
self.field = moves[direction](self.field)
self.spawn()
return True
else:
return False
# win if 2048 is reached
def is_win(self):
return any(any(i >= self.win_value for i in row) for row in self.field)
#game is over if no possible moves on field
def is_gameover(self):
return not any(self.move_is_possible(move) for move in actions)
# Draws to screen depending on action
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')
#seperator for horizontal tile sqaures
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
#draws rows to create table to play game
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('HGHSCORE: ' + str(self.highscore))
for row in self.field:
draw_hor_separator()
draw_row(row)
draw_hor_separator()
if self.is_win(): # if you win print you win string
cast(win_string)
else:
if self.is_gameover(): # if you lose print game over string
cast(gameover_string)
else:
cast(help_string1)
cast(help_string2)
# checks if valid move is possible for tile
def move_is_possible(self, direction):
def row_is_left_movable(row):
def change(i):
if row[i] == 0 and row[i + 1] != 0:
return True
if row[i] != 0 and row[i + 1] == row[i]:
return True
return False
return any(change(i) for i in range(len(row) - 1))
# checks the directions in which a tile can move
check = {}
check['Left'] = lambda field:\
any(row_is_left_movable(row) for row in field)
check['Right'] = lambda field:\
check['Left'](invert(field))
check['Up'] = lambda field:\
check['Left'](transpose(field))
check['Down'] = lambda field:\
check['Right'](transpose(field)) if direction in check:
return check[direction](self.field)
else:
return False
# main class to run game
def main(stdscr):
# initalize game
def init():
#重置游戏棋盘
game_field.reset()
return 'Game'
#gives options if game is open but not in play
def not_game(state):
#画出 GameOver 的画面
#读取用户输入判断是Restart还是Exit
game_field.draw(stdscr)
action = get_user_action(stdscr)
responses = defaultdict(lambda: state)
responses['Restart'], responses['Exit'] = 'Init', 'Exit'
return responses[action] def game():
# based on response will act appropriately (user says restart it will restart)
game_field.draw(stdscr)
action = get_user_action(stdscr)
if action == 'Restart':
return 'Init'
if action == 'Exit':
return 'Exit'
if game_field.move(action):
if game_field.is_win():
return 'Win'
if game_field.is_gameover():
return 'Gameover'
return 'Game'
# defines the 4 possible actions that the user can be in
state_actions = {
'Init' : init,
'Win' : lambda: not_game('Win'),
'Gameover': lambda: not_game('Gameover'),
'Game': game
}
#As long as user doesnt exit keep game going
curses.use_default_colors()
game_field = GameField(win = 32)
state = 'Init'
while state != 'Exit':
state = state_actions[state]() curses.wrapper(main)

  

  普通版:
# -*- coding: utf-8 -*-

#Importing libraries to be used
import wx
import os
import random
import copy # creating the user interface frame that the user will interact with and perform actions that will have an appropriate response
class Frame(wx.Frame):
def __init__(self,title):
#created a default toolbar of application with a resizeable option and minimize box
super(Frame,self).__init__(None,-1,title,
style=wx.DEFAULT_FRAME_STYLE^wx.MAXIMIZE_BOX^wx.RESIZE_BORDER)
#Setting different colours for each tile in the game
self.colors = {0:(204,192,179),2:(238, 228, 218),4:(237, 224, 200),
8:(242, 177, 121),16:(245, 149, 99),32:(246, 124, 95),
64:(246, 94, 59),128:(237, 207, 114),256:(237, 207, 114),
512:(237, 207, 114),1024:(237, 207, 114),2048:(237, 207, 114),
4096:(237, 207, 114),8192:(237, 207, 114),16384:(237, 207, 114),
32768:(237, 207, 114),65536:(237, 207, 114),131072:(237, 207, 114),
262144:(237, 207, 114),524288:(237, 207, 114),1048576:(237, 207, 114),
2097152:(237, 207, 114),4194304:(237, 207, 114),
8388608:(237, 207, 114),16777216:(237, 207, 114),
33554432:(237, 207, 114),67108864:(237, 207, 114),
134217728:(237, 207, 114),268435456:(237, 207, 114),
536870912:(237, 207, 114),1073741824:(237, 207, 114),
2147483648:(237, 207, 114),4294967296:(237, 207, 114),
8589934592:(237, 207, 114),17179869184:(237, 207, 114),
34359738368:(237, 207, 114),68719476736:(237, 207, 114),
137438953472:(237, 207, 114),274877906944:(237, 207, 114),
549755813888:(237, 207, 114),1099511627776:(237, 207, 114),
2199023255552:(237, 207, 114),4398046511104:(237, 207, 114),
8796093022208:(237, 207, 114),17592186044416:(237, 207, 114),
35184372088832:(237, 207, 114),70368744177664:(237, 207, 114),
140737488355328:(237, 207, 114),281474976710656:(237, 207, 114),
562949953421312:(237, 207, 114),1125899906842624:(237, 207, 114),
2251799813685248:(237, 207, 114),4503599627370496:(237, 207, 114),
9007199254740992:(237, 207, 114),18014398509481984:(237, 207, 114),
36028797018963968:(237, 207, 114),72057594037927936:(237, 207, 114)}
#Initalize game
self.setIcon()
self.initGame()
#Displays game and provides settings to move the tiles
panel = wx.Panel(self)
panel.Bind(wx.EVT_KEY_DOWN,self.onKeyDown)
panel.SetFocus()
self.initBuffer()
self.Bind(wx.EVT_SIZE,self.onSize)
self.Bind(wx.EVT_PAINT, self.onPaint)
self.Bind(wx.EVT_CLOSE,self.onClose)
self.SetClientSize((505,720))
self.Center()
self.Show()
#Puts on board so user can see
def onPaint(self,event):
dc = wx.BufferedPaintDC(self,self.buffer)
# Saves score and terminates when closed
def onClose(self,event):
self.saveScore()
self.Destroy()
# putting icon on toolbar
def setIcon(self):
icon = wx.Icon("icon.ico",wx.BITMAP_TYPE_ICO)
self.SetIcon(icon)
#Opens previous game and loads and updates score
def loadScore(self):
if os.path.exists("bestscore.ini"):
ff = open("bestscore.ini")
self.bstScore = ff.read()
ff.close()
#Saves score and writes to file so it may be opened later
def saveScore(self):
ff = open("bestscore.ini","w")
ff.write(str(self.bstScore))
ff.close()
#Initalize game so when it opens it displays text, score and all data needed for the game
def initGame(self):
self.bgFont = wx.Font(50,wx.SWISS,wx.NORMAL,wx.BOLD,face=u"Roboto")
self.scFont = wx.Font(36,wx.SWISS,wx.NORMAL,wx.BOLD,face=u"Roboto")
self.smFont = wx.Font(12,wx.SWISS,wx.NORMAL,wx.NORMAL,face=u"Roboto")
self.curScore = 0
self.bstScore = 0
self.loadScore()
# 4 rows and 4 coloums for tiles ( using arrays because it easily represents system used )
self.data = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
count = 0
# First 2 tile inialized if 1 tile it must be 2 but if 2 tiles connected then its 4
while count<2:
row = random.randint(0,len(self.data)-1)
col = random.randint(0,len(self.data[0])-1)
if self.data[row][col]!=0: continue
self.data[row][col] = 2 if random.randint(0,1) else 4
count += 1
# empty bitmap to put pixels in for game
def initBuffer(self):
w,h = self.GetClientSize()
self.buffer = wx.EmptyBitmap(w,h)
#Displays all drawings to the screen
def onSize(self,event):
self.initBuffer()
self.drawAll()
#Placing tiles on screen and multiplying by 2 if 2 tiles interact with one another(game logic)
def putTile(self):
available = []
for row in range(len(self.data)):
for col in range(len(self.data[0])):
if self.data[row][col]==0: available.append((row,col)) # add tile if empty square
if available:
row,col = available[random.randint(0,len(available)-1)]
self.data[row][col] = 2 if random.randint(0,1) else 4
return True
return False
def update(self,vlist,direct): # updates score and game tiles
score = 0
if direct: #up or left
i = 1
while i<len(vlist):
# if 2 tiles of equal value mesh upward it multiples the values and deletes the ith number (2 squares = 1 square)
if vlist[i-1]==vlist[i]:
del vlist[i]
vlist[i-1] *= 2
score += vlist[i-1] # Adds multiplied value to score
i += 1
i += 1
else:
#direction moved downward same thing as above but different direction
i = len(vlist)-1
while i>0:
if vlist[i-1]==vlist[i]:
del vlist[i]
vlist[i-1] *= 2
score += vlist[i-1]
i -= 1
i -= 1
return score
# The calucation and keeping logs of data for score (upward and downward movements)
def slideUpDown(self,up):
score = 0
numCols = len(self.data[0])
numRows = len(self.data)
oldData = copy.deepcopy(self.data) for col in range(numCols):
cvl = [self.data[row][col] for row in range(numRows) if self.data[row][col]!=0]
if len(cvl)>=2:
score += self.update(cvl,up)
for i in range(numRows-len(cvl)):
if up: cvl.append(0)
else: cvl.insert(0,0)
for row in range(numRows): self.data[row][col] = cvl[row]
return oldData!=self.data,score # The calucation and keeping logs of data for score (right and left movements)
def slideLeftRight(self,left):
score = 0
numRows = len(self.data)
numCols = len(self.data[0])
oldData = copy.deepcopy(self.data) for row in range(numRows):
rvl = [self.data[row][col] for col in range(numCols) if self.data[row][col]!=0]
if len(rvl)>=2:
score += self.update(rvl,left)
for i in range(numCols-len(rvl)):
if left: rvl.append(0)
else: rvl.insert(0,0)
for col in range(numCols): self.data[row][col] = rvl[col]
return oldData!=self.data,score
def isGameOver(self):
copyData = copy.deepcopy(self.data) flag = False # Tile is not moveable or you have lost if all tiles cant move any pieces up,down, left or right
if not self.slideUpDown(True)[0] and not self.slideUpDown(False)[0] and \
not self.slideLeftRight(True)[0] and not self.slideLeftRight(False)[0]:
flag = True #continue playing and copydata
if not flag: self.data = copyData
return flag
# Game logic to see if you can make a move or end the game
def doMove(self,move,score):
# if you can move put a tile and update change
if move:
self.putTile()
self.drawChange(score)
# if game is over put a message box and update best score if its the new best score
if self.isGameOver():
if wx.MessageBox(u"游戏结束,是否重新开始?",u"哈哈",
wx.YES_NO|wx.ICON_INFORMATION)==wx.YES:
bstScore = self.bstScore
self.initGame()
self.bstScore = bstScore
self.drawAll() # when you click a directon for the tile to move, it moves in the appropriate direction
def onKeyDown(self,event):
keyCode = event.GetKeyCode() if keyCode==wx.WXK_UP:
self.doMove(*self.slideUpDown(True))
elif keyCode==wx.WXK_DOWN:
self.doMove(*self.slideUpDown(False))
elif keyCode==wx.WXK_LEFT:
self.doMove(*self.slideLeftRight(True))
elif keyCode==wx.WXK_RIGHT:
self.doMove(*self.slideLeftRight(False)) # Creates background for the game board
def drawBg(self,dc):
dc.SetBackground(wx.Brush((250,248,239)))
dc.Clear()
dc.SetBrush(wx.Brush((187,173,160)))
dc.SetPen(wx.Pen((187,173,160)))
dc.DrawRoundedRectangle(15,150,475,475,5)
#Creates a 2048 logo
def drawLogo(self,dc):
dc.SetFont(self.bgFont)
dc.SetTextForeground((119,110,101))
dc.DrawText(u"2048",15,26)
# provides text to screen (Chinese text)
def drawLabel(self,dc):
dc.SetFont(self.smFont)
dc.SetTextForeground((119,110,101))
dc.DrawText(u"合并相同数字,得到2048吧!",15,114)
dc.DrawText(u"怎么玩: \n用-> <- 上下左右箭头按键来移动方块. \
\n当两个相同数字的方块碰到一起时,会合成一个!",15,639)
# Displays score to screen
def drawScore(self,dc):
dc.SetFont(self.smFont)
scoreLabelSize = dc.GetTextExtent(u"SCORE")
bestLabelSize = dc.GetTextExtent(u"BEST")
curScoreBoardMinW = 15*2+scoreLabelSize[0]
bstScoreBoardMinW = 15*2+bestLabelSize[0]
curScoreSize = dc.GetTextExtent(str(self.curScore))
bstScoreSize = dc.GetTextExtent(str(self.bstScore))
curScoreBoardNedW = 10+curScoreSize[0]
bstScoreBoardNedW = 10+bstScoreSize[0]
curScoreBoardW = max(curScoreBoardMinW,curScoreBoardNedW)
bstScoreBoardW = max(bstScoreBoardMinW,bstScoreBoardNedW)
dc.SetBrush(wx.Brush((187,173,160)))
dc.SetPen(wx.Pen((187,173,160)))
dc.DrawRoundedRectangle(505-15-bstScoreBoardW,40,bstScoreBoardW,50,3)
dc.DrawRoundedRectangle(505-15-bstScoreBoardW-5-curScoreBoardW,40,curScoreBoardW,50,3)
dc.SetTextForeground((238,228,218))
dc.DrawText(u"BEST",505-15-bstScoreBoardW+(bstScoreBoardW-bestLabelSize[0])/2,48)
dc.DrawText(u"SCORE",505-15-bstScoreBoardW-5-curScoreBoardW+(curScoreBoardW-scoreLabelSize[0])/2,48)
dc.SetTextForeground((255,255,255))
dc.DrawText(str(self.bstScore),505-15-bstScoreBoardW+(bstScoreBoardW-bstScoreSize[0])/2,68)
dc.DrawText(str(self.curScore),505-15-bstScoreBoardW-5-curScoreBoardW+(curScoreBoardW-curScoreSize[0])/2,68)
# Put rounded rectangular tiles on screen
def drawTiles(self,dc):
dc.SetFont(self.scFont)
for row in range(4):
for col in range(4):
value = self.data[row][col]
color = self.colors[value]
if value==2 or value==4:
dc.SetTextForeground((119,110,101))
else:
dc.SetTextForeground((255,255,255))
dc.SetBrush(wx.Brush(color))
dc.SetPen(wx.Pen(color))
dc.DrawRoundedRectangle(30+col*115,165+row*115,100,100,2)
size = dc.GetTextExtent(str(value))
while size[0]>100-15*2: # changes font size based on number within tile
self.scFont = wx.Font(self.scFont.GetPointSize()*4/5,wx.SWISS,wx.NORMAL,wx.BOLD,face=u"Roboto")
dc.SetFont(self.scFont)
size = dc.GetTextExtent(str(value))
if value!=0: dc.DrawText(str(value),30+col*115+(100-size[0])/2,165+row*115+(100-size[1])/2)
# Draws everything to the screen
def drawAll(self):
dc = wx.BufferedDC(wx.ClientDC(self),self.buffer)
self.drawBg(dc)
self.drawLogo(dc)
self.drawLabel(dc)
self.drawScore(dc)
self.drawTiles(dc)
# Calculates current score and checks if it is the best score and if so updates
def drawChange(self,score):
dc = wx.BufferedDC(wx.ClientDC(self),self.buffer)
if score:
self.curScore += score
if self.curScore > self.bstScore:
self.bstScore = self.curScore
self.drawScore(dc)
self.drawTiles(dc)
# Shows creator info
if __name__ == "__main__":
app = wx.App()
Frame(u"2048 v1.0.1 by Guolz")
app.MainLoop()

  

小游戏:200行python代码手写2048的更多相关文章

  1. 200行Python代码实现2048

    200行Python代码实现2048 一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiyanlou 2. 环境介绍 本实验环境采用带桌面的Ubuntu Linux环境,实验中会用到桌面 ...

  2. 200行PYTHON代码实现贪吃蛇

    200行Python代码实现贪吃蛇 话不多说,最后会给出全部的代码,也可以从这里Fork,正文开始: 目前实现的功能列表: 贪吃蛇的控制,通过上下左右方向键: 触碰到边缘.墙壁.自身则游戏结束: 接触 ...

  3. 用200行Python代码“换脸”

    介绍 本文将介绍如何编写一个只有200行的Python脚本,为两张肖像照上人物的“换脸”. 这个过程可分为四步: 检测面部标记. 旋转.缩放和转换第二张图像,使之与第一张图像相适应. 调整第二张图像的 ...

  4. python 之路,200行Python代码写了个打飞机游戏!

    早就知道pygame模块,就是没怎么深入研究过,恰逢这周未没约到妹子,只能自己在家玩自己啦,一时兴起,花了几个小时写了个打飞机程序. 很有意思,跟大家分享下. 先看一下项目结构 "" ...

  5. (转)python 之路,200行Python代码写了个打飞机游戏!

    原文:https://www.cnblogs.com/alex3714/p/7966656.html

  6. 【Xamarin挖墙脚系列:代码手写UI,xib和StoryBoard间的博弈,以及Interface Builder的一些小技巧(转)】

    正愁如何选择构建项目中的视图呢,现在官方推荐画板 Storybord...但是好像 xib貌似更胜一筹.以前的老棒子总喜欢装吊,用代码写....用代码堆一个HTML页面不知道你们尝试过没有.等页面做出 ...

  7. 只用200行Go代码写一个自己的区块链!

    Coral Health · 大约23小时之前 · 220 次点击 · 预计阅读时间 7 分钟 · 不到1分钟之前 开始浏览 区块链是目前最热门的话题,广大读者都听说过比特币,或许还有智能合约,相信大 ...

  8. 代码手写UI,xib和StoryBoard间的博弈,以及Interface Builder的一些小技巧

    近期接触了几个刚入门的iOS学习者,他们之中存在一个普遍和困惑和疑问.就是应该怎样制作UI界面.iOS应用是非常重视用户体验的,能够说绝大多数的应用成功与否与交互设计以及UI是否美丽易用有着非常大的关 ...

  9. 只用200行Go代码写一个自己的区块链!(转)

    区块链是目前最热门的话题,广大读者都听说过比特币,或许还有智能合约,相信大家都非常想了解这一切是如何工作的.这篇文章就是帮助你使用 Go 语言来实现一个简单的区块链,用不到 200 行代码来揭示区块链 ...

随机推荐

  1. 更改mac电脑图片默认存储位置

    1.创建存储位置screenshot 2.打开terminal 3.defaults write com.apple.screencapture location ~/Desktop/screensh ...

  2. 对android中ActionBar中setDisplayHomeAsUpEnabled和setHomeButtonEnabled和setDisplayShowHomeEnabled方法的理解

    转自: http://blog.csdn.net/lovexieyuan520/article/details/9974929 http://blog.csdn.net/cyp331203/artic ...

  3. android 和 webService交互

    webService 很久不用了,第一次使用还是13年, 早已忘记怎么搞了.今天看了篇博文,写了个demo .记录下吧! 首先要下载skoap2  .... xxx.jar  ,我用的是最新的3.6. ...

  4. AtomicInteger 一个提供原子操作的Integer类

    转自:http://www.blogjava.net/freeman1984/archive/2011/10/17/361402.html AtomicInteger,一个提供原子操作的Integer ...

  5. HBase读延迟的12种优化套

    任何系统都会有各种各样的问题,有些是系统本身设计问题,有些却是使用姿势问题.HBase也一样,在真实生产线上大家或多或少都会遇到很多问题,有些是HBase还需要完善的,有些是我们确实对它了解太少. 总 ...

  6. CoDeSys

    CoDeSys是全球最著名的PLC内核软件研发厂家德国的3S(SMART,SOFTWARE,SOLUTIONS)公司出的一款与制造商无关的IEC 61131-1编程软件.CoDeSys 支持完整版本的 ...

  7. ansible-playbook流程控制-loops循环使用

    1. ansible-playbook流程控制-loops循环使用    有时你想要多次重复任务.在计算机编程中,这称为循环.common ansible循环包括使用文件模块更改多个文件和/或目录的所 ...

  8. mybatis源码专题(2)--------一起来看下使用mybatis框架的insert语句的源码执行流程吧

    本文是作者原创,版权归作者所有.若要转载,请注明出处.本文以简单的insert语句为例 1.mybatis的底层是jdbc操作,我们先来回顾一下insert语句的执行流程,如下 执行完后,我们看下数据 ...

  9. charles SSL代理设置

    本文参考:charles SSL代理设置 charles SSL代理设置 SSL Proxying Srtting 这里最常用的设置就是第一个ssl proxying,这里记录了需要捕获哪些ssl的信 ...

  10. 第一次接触WebSocket遇到的坑以及感受

    要求用.net写一个服务,然后通过webscoket实现客户端与服务端之间的通信. 第一次知道.net还可以用来写服务,然后问题来了,服务是什么- -..下面图里的就是服务,可以停止暂停和启动. 我要 ...