基于curses的2048游戏
本文主要完成了2048游戏,用curses库对界面的显示,用SQlite数据库保存游戏数据。
1. 引言
在突发奇想中,想到了经常玩的2048游戏,于是便用python实现了简易版的2048游戏,实现了基本的上下左右操作,以及退出,重新开始,继续等选项,并且链接SQlite数据库记录最高分。
2. 系统结构
该程序设计采用有限状态机进行设计。因此实现系统结构介绍分为有限状态机设计介绍和主要逻辑介绍。
2.1.系统总体设计
该程序设计采用开发平台为Visual Studio Code,采用程序语言为Python。所使用的Python模块为curses模块、sqlite3模块、random模块、collections模块。不同的Python模块分别用于实现不同的程序功能
表1 模块-功能对照表
2.2.逻辑实现设计
此次游戏采用了常见的游戏设计模式,有限状态机,2048游戏有,初始状态(Init),游戏状态(Game),退出状态(Exit),胜利状态(Win),失败状态(Gameover),继续状态(Goon),重新开始状态(restart),状态之间的关系如图所示:
设计也分三个模块分别设计,数据库模块,主要逻辑模块,状态模块
数据库模块:采用的是轻量级数据库SQlite,内置于Python3,因为目前只需要记录最高分数,不需要使用Mysql等其他数据库。实现基本的增改查。
主要逻辑模块: 2048游戏最主要逻辑是当按下代表上下左右的键时,能够移动并且数字相同的合并达到目标数字赢下游戏。移动逻辑如图:
图2 移动逻辑
实现原理:创建44二维数组,将每一行中不为0的数按顺序移动至最前方,若相邻数字相同,则至前方数字为0,后方为数字2,再进行将每一行中不为0的数按顺序移动至最前方的操作,完成左移。上移,右移,下移则是将矩阵进行反转以或转置操作。如图所示:
图3 其他方位逻辑
状态模块:实现状态机转换,将WASDQRGwasdqrg用字典对应每个状态,获取用户按下的值返回状态,不同状态对应不同的不同的处理函数,只要状态机不等于EXIT,则无限循环等待用户操作。如图4
图4 状态模块逻辑
3. 代码实现
引入模块
import sqlite3
import curses
from random import randrange, choice # generate and place new tile
from collections import defaultdict
将WASDQRGwasdqrg与状态用字典关联
letter_codes = [ord(ch) for ch in 'WASDRQGwasdrqg']
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit','Goon']
actions_dict = dict(zip(letter_codes, actions * 2))
获得用户按下的按键
def get_user_action(keyboard):
char = 'N'
while char not in actions_dict:
# 返回按下键的 ascii 码值
char = keyboard.getch()
return actions_dict[char]
状态模块:对各个状态实现操作函数,将状态与函数关联
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'], responses['Goon'] = 'Init', 'Exit' , 'Goon' # 对应不同的行为转换到不同的状态
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'
def Goon():
game_field.draw(stdscr)
game_field.Goon()
return 'Game'
state_actions = {
'Init': init,
'Win': lambda: not_game('Win'),
'Gameover': lambda: not_game('Gameover'),
'Game': game,
'Goon': Goon
}
#使用默认颜色
curses.use_default_colors()
# curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
# curses.init_pair(2, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
# curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
# curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK)
# curses.init_pair(5, curses.COLOR_CYAN, curses.COLOR_BLACK)
# curses.init_pair(6, curses.COLOR_BLUE, curses.COLOR_BLACK)
# 设置终结状态最大数值为 32
game_field = GameField(win=16)
state = 'Init'
# 状态机开始循环
while state != 'Exit':
state = state_actions[state]()
game_field.reset()
主要逻辑模块,分为游戏逻辑与绘制界面两部分
其中游戏逻辑部分,实现了上下左右对应的操作,判断游戏胜负,初始化。
def Goon(self):
self.win_value *= 2
def reset(self):
if self.score > self.highscore:
self.highscore = self.score
self.dbase.update(self.highscore)
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 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 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!'
goOn_string = ' Go on(G)'
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) + ' GOAL: ' + str(self.win_value))
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)
cast(goOn_string)
else:
if self.is_gameover():
cast(gameover_string)
else:
cast(help_string1)
cast(help_string2)
数据库模块,完成链接数据库,创建表,插入,更新以及查找功能
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!'
goOn_string = ' Go on(G)'
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) + ' GOAL: ' + str(self.win_value))
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)
cast(goOn_string)
else:
if self.is_gameover():
cast(gameover_string)
else:
cast(help_string1)
cast(help_string2)
4. 实验
初始界面:
胜利:
5. 总结与展望
此次实现这个游戏,让我了解游戏的基本设计模式,有限状态机设计,对于Python的很多函数也有了较好的理解,比如Zip,也对一些知识点更加深入理解,当然这个游戏并不完美,并没有实现颜色显示,以及界面大小调整和输入法切换,较为遗憾,此次并没有有到Pygame模块来实现,是因为curses较简单,日后会用Pygame实现。
6. 参考文献
《Python帮助文档》
《PYTHON 数据库 之 sqlite3》
https://blog.csdn.net/xuzhexing/article/details/90600228
如需完整代码
https://download.csdn.net/download/qq_41030253/12579608
本文地址:https://blog.csdn.net/qq_41030253/article/details/107143400