看了这篇文章后,你也可以写出2048
* 学习编程的路上,会玩的人总是能找到乐趣,今天给大家分享我编写的2048(嘿嘿!)
* 2048是一款特别好玩的游戏,操作十分简单,但想要玩好,也是需要很多时间的。
* 今天给大家分享一下我的思路,教会大家如何用python编写2048。
* 如有bug,恳请指出,13694846652@163.com
* 获取源代码请发送邮件(自己写成就感更高喔!)
* 本人未参考任何他人代码 , 纯靠瞎写(^_^)
游戏的逻辑
1. 游戏开始时,游戏界面有两个数字,2或者4,2出现的概率更高
2. 每次滑动(一次操作),数据先进行处理,再在空白处生成一个数字,
2或者4,2出现的概率更高
3. 数据处理的逻辑
a) 数据沿着滑动方向运动
b) 遇见0便移位,并判断下一位是零,或者与下一位是否相等
c) 遇见相同数字便相加
d) 不满足b,c条件,不移动
4.数据保存
游戏被抽象成为一行四个数据,[0,0,0,0]
使用可变有序的列表储存数据,16个数字就是4组列表
[[0,0,0,0], [0,0,0,0],[0,0,0,0] ,[0,0,0,0]]
下面是程序构思:
程序由三个模块编写
1 | main.py(主函数,包括运行逻辑和菜单打印) |
2 | data_handle.py(游戏运行逻辑,数据转换处理) |
3 | interface.py(接收并打印游戏界面) |
首先,先看看实现的成果
--------------------图形界面代码实现--------------------
主要使用一些简单的字符串拼接,大家也可以使用Tkinter库
def game_interface(a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4):
# 游戏打印界面
l=list((a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4))
a1=" " if not a1 else a1
a2=" " if not a2 else a2
a3=" " if not a3 else a3
a4=" " if not a4 else a4
b1=" " if not b1 else b1
b2=" " if not b2 else b2
b3=" " if not b3 else b3
b4=" " if not b4 else b4
c1=" " if not c1 else c1
c2=" " if not c2 else c2
c3=" " if not c3 else c3
c4=" " if not c4 else c4
d1=" " if not d1 else d1
d2=" " if not d2 else d2
d3=" " if not d3 else d3
d4=" " if not d4 else d4
print("\r+-------+-------+-------+-------+\n",
"\r| | | | |\n",
"\r|%s|%s|%s|%s|\n"%(str(a1).center(7),str(a2).center(7),str(a3).center(7),str(a4).center(7)),
"\r| | | | |\n",
"\r+-------+-------+-------+-------+\n",
"\r| | | | |\n",
"\r|%s|%s|%s|%s|\n"%(str(b1).center(7),str(b2).center(7),str(b3).center(7),str(b4).center(7)),
"\r| | | | |\n",
"\r+-------+-------+-------+-------+\n",
"\r| | | | |\n",
"\r|%s|%s|%s|%s|\n"%(str(c1).center(7),str(c2).center(7),str(c3).center(7),str(c4).center(7)),
"\r| | | | |\n",
"\r+-------+-------+-------+-------+\n",
"\r| | | | |\n",
"\r|%s|%s|%s|%s|\n"%(str(d1).center(7),str(d2).center(7),str(d3).center(7),str(d4).center(7)),
"\r| | | | |\n",
"\r+-------+-------+-------+-------+\n",end="")
for i in l:
s=int(i)
if s >2000:
raise ImportError("恭喜达到2048!!!")
1. 我这里使用四个方向的操作,然后形成一个新的列表
2. 将0删除后,判断相加还是不移动
3. 处理完之后将数据转换回去
---------------------------核心逻辑---------------------------
# 进行数据处理,根据操作进行数据转换
import random as r
import sys
square = (2, 2, 2, 4)
def prime_data():
# 起始布局
data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
pp = r.choice(square)
pp1 = r.choice(square)
location = r.sample([i for i in range(16)], 2)
data[location[0]] = pp
data[location[1]] = pp1
return data
def tran_data(data, n):
# 根据操转换为4个小数据列表
# 操作的反向为底边 zero
small_list = []
# print(data)
if n == 0: # 向上操作
for i in range(4):
zero = [data[i], data[i+4], data[i+8], data[i+12]]
small_list.append(zero)
elif n == 1: # 向右操作
zero = data[0:4][::-1]
one = data[4:8][::-1]
two = data[8:12][::-1]
three = data[12:16][::-1]
small_list = [three, two, one, zero]
elif n == 2: # 向下操作
for i in range(12, 16):
zero = [data[i], data[i-4], data[i-8], data[i-12]]
small_list.append(zero)
elif n == 3: # 向左操作
zero = data[:4]
one = data[4:8]
two = data[8:12]
three = data[12:]
small_list = [three, two, one, zero]
return small_list
def add_number(data, n):
# 数据处理函数
lis = []
small_list = tran_data(data, n)
for p in small_list:
try:
for x in range(4):
p.remove(0)
except ValueError:
pass
while True:
s = len(p)
if s < 4:
p.append(0)
else:
break
if p[0] == p[1]:
if p[2] == p[3]:
p[0] += p[1]
p[1] = p[2]+p[3]
p[2], p[3] = 0, 0
else:
p[0] += p[1]
p[1], p[2], p[3] = p[2], p[3], 0
elif p[2] == p[1]:
p[1] += p[2]
p[2], p[3] = p[3], 0
elif p[2] == p[3]:
p[2] += p[3]
p[3] = 0
lis.append(p)
data = tran_list(lis, n)
return data
def tran_list(small_list, n):
big_list = []
if n == 0:
for x in range(4):
for i in range(4):
big_list.append(small_list[i][x])
elif n == 1:
for i in [3, 2, 1, 0]:
s = small_list[i][::-1]
for x in s:
big_list.append(x)
elif n == 2:
for x in range(4):
for i in [3, 2, 1, 0]:
big_list.append(small_list[i][x])
big_list = big_list[::-1]
elif n == 3:
for i in [3, 2, 1, 0]:
for x in small_list[i]:
big_list.append(x)
return big_list
def judgement(big_list):
# 生成并修改数据
s = []
for i in range(16):
if not big_list[i]:
p = i
s.append(p)
try:
l = r.choice(square)
z = r.choice(s)
except (ValueError, IndexError):
s = input("游戏结束,请按任意键退出")
raise NameError(" 游戏结束!")
big_list[z] = l
return big_list
def data_handle(data):
n = input("W A S D(上下左右)--->")
if len(n) > 1:
n = n[-1]
if n in ("w"):
# 向上划
data = add_number(data, 0)
elif n in ("d"):
# 向右划
data = add_number(data, 1)
elif n in ("s"):
# 向下划
data = add_number(data, 2)
elif n in ("a"):
# 向左划
data = add_number(data, 3)
elif n in "q":
raise OSError
else:
raise StopIteration("请输入正确操作")
data = judgement(data)
return data # 返回数据给游戏界面
def read_data(filename="archive.txt"):
s = []
try:
file = open(filename)
for i in file:
p = i.strip()
pp = int(p)
s.append(pp)
file.close()
except OSError:
print("文件打开失败")
return s
def save_data(data, filename="archive.txt"):
try:
file = open(filename, "w")
for i in data:
file.write(str(i))
file.write("\n")
file.close()
except OSError:
print("文件打开错误")
将核心逻辑串起来,添加保存数据,载入旧游戏的功能
---------------------------主程序---------------------------
''' 此模块是2048主模块
'''
import time
from data_handle import *
from interface import game_interface
def menu():
print("+{}+".format("-"*30))
print("|%s|"%("1.进入游戏".center(25)))
print("|%s|"%("2.载入进度".center(25)))
print("|%s|"%("3.保存游戏".center(25)))
print("|%s|"%("4.退出游戏".center(25)))
print("+{}+".format("-"*30))
def showtime():
#主程序
data=prime_data() #初始数据
while True:
menu()
option=int(input("请输入您要进行的操作:"))
if option == 1:
game_interface(*data)
while True:
try:
data=data_handle(data)
game_interface(*data)
except NameError as e:
print(e)
break
except ImportError as e:
print(e)
time.sleep(10)
break
except OSError:
break
except StopIteration as e:
print(e)
continue
elif option == 2:
# 载入数据
data=read_data(filename="archive.txt")
game_interface(*data)
while True:
try:
data=data_handle(data)
game_interface(*data)
except NameError as e:
print(e)
break
except ImportError as e:
print(e)
time.sleep(10)
break
except OSError:
break
except StopIteration as e:
print(e)
continue
elif option == 3:
# 保存数据
save_data(data,filename="archive.txt")
elif option == 4:
exit()
if __name__ == "__main__":
showtime()
注:游戏虽然简单,但自己操作并写出来,成就感还是很强的,希望大家在python的路上越走越远!!!