相信2048这个游戏对大家来说一定不陌生,下面这篇文章就主要给大家介绍了怎么用python实现2048小游戏,文中通过注释与示例代码介绍的很详细,相信对大家的理解和学习具有一定的参考借鉴价值,有需要的朋友们一起来看看吧。
前言
2048游戏规则:简单的移动方向键让数字叠加,并且获得这些数字每次叠加后的得分,当出现2048这个数字时游戏胜利。同时每次移动方向键时,都会在这个4*4的方格矩阵的空白区域随机产生一个数字2或者4,如果方格被数字填满了,那么就gameover了。
主逻辑图
def main(stdscr):
def init():
#重置游戏棋盘
game_field.reset()
return ‘game’
def not_game(state):
#画出 gameover 或者 win 的界面
game_field.draw(stdscr)
#读取用户输入得到action,判断是重启游戏还是结束游戏
action = get_user_action(stdscr)
responses = defaultdict(lambda: state) #默认是当前状态,没有行为就会一直在当前界面循环
responses[‘restart’], responses[‘exit’] = ‘init’, ‘exit’ #对应不同的行为转换到不同的状态
return responses[action]
def game():
#画出当前棋盘状态
game_field.draw(stdscr)
#读取用户输入得到action
action = get_user_action(stdscr)
if action == ‘restart’:
return ‘init’
if action == ‘exit’:
return ‘exit’
if game_field.move(action): # move successful
if game_field.is_win():
return ‘win’
if game_field.is_gameover():
return ‘gameover’
return ‘game’
state_actions = {
‘init’: init,
‘win’: lambda: not_game(‘win’),
‘gameover’: lambda: not_game(‘gameover’),
‘game’: game
}
curses.use_default_colors()
game_field = gamefield(win=32)
state = ‘init’
#状态机开始循环
while state != ‘exit’:
state = state_actions[state]()
逐条解读(代码框内会标注是来自外部,无标注则是来自内部):定义主函数
def main(stdscr):
def init():
#重置游戏棋盘
game_field.reset()
reset出自外部定义的类,game_field=gamefield的一个方法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()
#其中highscore为程序初始化过程中定义的一个变量。记录你win游戏的最高分数记录。
return ‘game’
返回一个游戏进行中的状态。game_field=gamefield状态在后面有定义:
主函数底部定义:
state_actions = {
‘init’: init,
‘win’: lambda: not_game(‘win’),
‘gameover’: lambda: not_game(‘gameover’),
‘game’: game
}
def not_game(state):
#画出 gameover 或者 win 的界面
game_field.draw(stdscr)
draw是导入的类game_field=gamefield中的方法:
#来自外部类
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(‘hghscore: ‘ + 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)
#这里面的draw方法的字函数我就不做多的解释了,很简单的一些概念。
#但是又运用到了很优秀的精简代码。
#有的地方建议去查一下python的一些高级概念,我就不做多的介绍了。
这里面的draw方法的字函数我就不做多的解释了,很简单的一些概念。
但是又运用到了很优秀的精简代码。
有的地方建议去查一下python的一些高级概念,我就不做多的介绍了。
#读取用户输入得到action,判断是重启游戏还是结束游戏
action = get_user_action(stdscr)
读取用户行为,函数来自于代码初始的定义
#来自外部定义的函数
def get_user_action(keyboard):
char = “n”
while char not in actions_dict:
char = keyboard.getch()
return actions_dict[char]
在结尾处,也即是主函数执行的第三步,定义了state = state_actions[state]()这一实例:
#主函数底部:
state = ‘init’
#状态机开始循环
while state != ‘exit’:
state = state_actions[state]()
responses = defaultdict(lambda: state) #默认是当前状态,没有行为就会一直在当前界面循环
responses[‘restart’], responses[‘exit’] = ‘init’, ‘exit’ #对应不同的行为转换到不同的状态
return responses[action]
def game():
#画出当前棋盘状态
game_field.draw(stdscr)
#读取用户输入得到action
action = get_user_action(stdscr)
if action == ‘restart’:
return ‘init’
if action == ‘exit’:
return ‘exit’
if game_field.move(action): # move successful
if game_field.is_win():
return ‘win’
if game_field.is_gameover():
return ‘gameover’
return ‘game’
#game()函数的定义类似于上面已经讲过的not_game(),只是game()有了内部循环
#即如果不是restart/exit或者对move之后的状态进行判断,如果不是结束游戏,就一直在game()内部循环。
game()函数的定义类似于上面已经讲过的not_game() ,只是game()有了内部循环,即如果不是restart/exit或者对move之后的状态进行判断,如果不是结束游戏,就一直在game()内部循环。
state_actions = {
‘init’: init,
‘win’: lambda: not_game(‘win’),
‘gameover’: lambda: not_game(‘gameover’),
‘game’: game
}
curses.use_default_colors()
game_field = gamefield(win=32)
state = ‘init’
#状态机开始循环
while state != ‘exit’:
state = state_actions[state]()
#此处的意思是:state=state_actions[state] 可以看做是:
#state=init()或者state=not_game(‘win’)或者是另外的not_game(‘gameover’)/game()
此处的意思是:state=state_actions[state] 可以看做是:state=init()或者state=not_game(‘win’)或者是另外的not_game(‘gameover’)/game()
废话不多说,上一个我的成功的图,另外,可以通过设置最后几行中的win=32来决定你最终获胜的条件!
完整代码
#-*- coding:utf-8 -*-
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 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(‘hghscore: ‘ + 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)
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
def main(stdscr):
def init():
#重置游戏棋盘
game_field.reset()
return ‘game’
def not_game(state):
#画出 gameover 或者 win 的界面
game_field.draw(stdscr)
#读取用户输入得到action,判断是重启游戏还是结束游戏
action = get_user_action(stdscr)
responses = defaultdict(lambda: state) #默认是当前状态,没有行为就会一直在当前界面循环
responses[‘restart’], responses[‘exit’] = ‘init’, ‘exit’ #对应不同的行为转换到不同的状态
return responses[action]
def game():
#画出当前棋盘状态
game_field.draw(stdscr)
#读取用户输入得到action
action = get_user_action(stdscr)
if action == ‘restart’:
return ‘init’
if action == ‘exit’:
return ‘exit’
if game_field.move(action): # move successful
if game_field.is_win():
return ‘win’
if game_field.is_gameover():
return ‘gameover’
return ‘game’
state_actions = {
‘init’: init,
‘win’: lambda: not_game(‘win’),
‘gameover’: lambda: not_game(‘gameover’),
‘game’: game
}
curses.use_default_colors()
game_field = gamefield(win=32)
state = ‘init’
#状态机开始循环
while state != ‘exit’:
state = state_actions[state]()
curses.wrapper(main)
更多x一步步教你用python实现2048小游戏相关文章请关注php中文网!