Python 打字小游戏开发,来体验不一样的打字游戏乐趣(第一篇)
Python 打字小游戏开发,来体验不一样的打字游戏乐趣(完结篇)
这里将会讲解一些主要的代码实现部分。
首先在类及函数外面定义全局变量:
FLAG = True # 定义一个信号量,用于判断最前面的小车是否到达终点,游戏结束变为False;
CARFLAG = True # 定义小车真正在窗口上移动时的信号量,当小车在窗口上静止不动时变为False;
ROAD = ‘’ # 赛道(Python,Java,MySql赛道)。
# 游戏窗口类
class GameWindow:
bgcolor = '#68696E' # 画布颜色
root = tk.Tk()
root.title('打字小游戏开发')
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
def __init__(self):
pass
# 窗口页面的大小
def window_page_size(self,windowsize):
rootwidth, rootheight = windowsize
rootposx = int((self.screenwidth - rootwidth) / 2)
rootposy = int((self.screenheight - rootheight) / 2) - 100
self.root.geometry('{}x{}+{}+{}'.format(rootwidth, rootheight, rootposx, rootposy))
time.sleep(0.1)
# 选择赛道
def select_road(self):
def func(event):
global FLAG,CARFLAG,ROAD
FLAG = True
CARFLAG = True
road = event.widget["text"]
print(road)
ROAD = road[:-2]
self.select_road_frame.destroy()
self.window_page_size((1000, 560))
self.create_canvas()
configuration_project(ROAD)
self.recording_time()
self.display_typing_speed()
self.replay_button()
self.return_button()
self.window_page_size((500, 300))
self.select_road_frame = tk.Frame(self.root)
self.select_road_frame.place(x=0, y=0, width=500, height=300)
for road in ['Python赛道','Java赛道','MySql赛道']:
b = tk.Button(self.select_road_frame, text=road,font=('华文行楷', 26),relief=tk.RAISED,cursor='hand2',width=12,height=1)
b.pack(pady=20)
b.bind("" , func)
# 创建一张画布
def create_canvas(self):
self.canvas = tk.Canvas(self.root, width=1000, height=400, bg=self.bgcolor)
self.canvas.place(x=0, y=0)
# 创建一条路——赛道
def create_road(self,roadtype):
# self.road = Road('Java') # 实列化一个路的对象(Java类型的路)
self.road = Road(roadtype) # 实列化一个路的对象(Python类型的路)
self.road_img = tk.PhotoImage(file='./sucai/road.png')
self.c_road = [self.canvas.create_image(i, 200, image=self.road_img, tag=f'c_road{i}') for i in range(500, self.road.road_number * 1000, 1000)]
self.tag_road = [f'c_road{i}' for i in range(500, (self.road.road_number - 2) * 1000, 1000)]
# 创建两棵树
def create_tree(self):
self.tree1 = Tree(posx=160, posy=350,filepath='./sucai/tree1.png',treetag='tree1')
self.tree1.tree_create(self.canvas)
self.tree2 = Tree(posx=230, posy=340,filepath='./sucai/tree2.png', treetag='tree2')
self.tree2.tree_create(self.canvas)
# 创建跑程进度条
def displayprogressbar(self,caroop_list):
maximum = self.road.road_length
self.progressbar_list = []
for i in range(4):
progressbar = ttk.Progressbar(self.canvas, length=200, maximum=maximum)
progressbar.place(x=10, y= 20 if i == 0 else i*40 + 20)
tk.Label(self.canvas,text=caroop_list[i].username,fg='#191970').place(x=215,y=20 if i == 0 else i*40 + 20)
self.progressbar_list.append(progressbar)
# 重新开始按钮
def replay_button(self):
def function():
global FLAG,CARFLAG,end_label_list,dt
FLAG = False
CARFLAG = False
for t in threading.enumerate()[1:]:
stop_thread(t)
self.canvas.destroy()
self.text_frame.destroy()
if end_label_list:
for i in end_label_list: i.destroy()
del dt
FLAG = True
CARFLAG = True
self.create_canvas()
configuration_project(ROAD)
self.recording_time()
self.return_button()
self.replaybutton_img = tk.PhotoImage(file='./sucai/replay.png')
tk.Label(self.root,text='重新开始').place(x=920,y=480)
replaybutton = tk.Button(self.root, image=self.replaybutton_img, command=function)
replaybutton.place(x=910,y=400)
# 返回按钮
def return_button(self):
def function():
global FLAG,CARFLAG,ROAD,end_label_list,dt
FLAG = False
CARFLAG = False
ROAD = ''
for t in threading.enumerate()[2:]:
stop_thread(t)
self.canvas.destroy()
self.text_frame.destroy()
self.cpm_label.destroy()
self.wpm_label.destroy()
if end_label_list:
for i in end_label_list: i.destroy()
del dt
self.select_road()
self.returnbutton_img = tk.PhotoImage(file='./sucai/return.png')
returnbutton = tk.Button(self.root,text='返回',image=self.returnbutton_img,command=function)
returnbutton.place(x=900,y=50)
# 记录游戏时间
def recording_time(self):
time_label = tk.Label(self.canvas, text='时长:00:00:00', font=("华文行楷", 15), background='#DAEFE6')
time_label.place(x=870, y=20)
start_time = datetime.datetime.now()
def run():
global FLAG
if FLAG:
time_label.after(1000, run)
update_time = datetime.datetime.now() - start_time
self.time_ = f'时长:{update_time}'.split('.')[0]
time_label.configure(text=self.time_) # 不显示时长的毫秒值
run()
# 展示文本
def display_text_frame(self):
self.text_frame = tk.Frame(self.root, bg='white')
self.text_frame.place(x=100, y=400, width=800, height=150)
# 显示打字速度
def display_typing_speed(self):
self.cpm_label = tk.Label(self.root,text='cpm:0', font=("微软雅黑", 13),fg='#A52A2A')
self.cpm_label.place(x=8,y=410)
self.wpm_label = tk.Label(self.root, text='wpm:0', font=("微软雅黑", 13),fg='#A52A2A')
self.wpm_label.place(x=8, y=440)
# 播放背景音乐函数
def playmusic(self,):
global FLAG
mixer.init()
mixer.music.load('./sucai/bgmusic.mp3')
mixer.music.play()
while FLAG:
time.sleep(2)
mixer.music.stop()
# 显示窗口
def displaywindow(self):
self.root.resizable(False, False)
self.root.mainloop()
speed = 2.0 初始化小车的移动速度,posx = 70 初始化小车的初始位置,x轴方向,car_move_distance = [] 记录小车以初始化速度speed = 2.0开始移动的路程,这里是在整个代码中等程序运行2.5秒之前统计小车真正在窗口上移动的距离,即在程序启动时的2.5秒运行if CARFLAG: 里面的这段代码。反之,程序启动2.5秒后,将进行else里面,电脑小车的移动速度也将会由下面car_speed_change()方法决定。
当进入else里面时,也就意味着整个程序的小车将会在窗口上静止,将由赛道和树往后移动,形成小车向前移动的视觉效果。
里面的这两段代码:
c.delete(self.cartag)
c.create_image(self.posx, self.posy, image=self.car_img, tag=self.cartag)
是与tag的功能有关,画布delete(‘tag’)就是删除指定的画布上的内容,这样就是先删除,再重新画一个。
# 小车类
class Car:
speed = 2.0 # 初始化小车的移动速度
posx = 70 # 初始化小车的初始位置,x轴方向
car_move_distance = [] # 记录小车,以初始化速度speed = 2.0开始移动的路程
def __init__(self, filepath, posy, cartag, username):
self.filepath = filepath
self.posy = posy
self.cartag = cartag
self.username = username
# 小车移动方法
def car_move(self,c,car_img):
global FLAG
print(self.username,'准备就绪...')
self.car_img = car_img
def run():
if FLAG:
if CARFLAG:
self.posx += self.speed
self.car_move_distance = []
self.car_move_distance.append((self.cartag, self.posx))
c.delete(self.cartag)
c.create_image(self.posx, self.posy, image=self.car_img, tag=self.cartag)
c.delete(self.username)
c.create_text(self.posx, self.posy, text=self.username, font=("Purisa", 13), fill='white',tag=self.username)
else:
c.delete(self.cartag)
c.create_image(self.posx, self.posy, image=self.car_img, tag=self.cartag)
c.delete(self.username)
c.create_text(self.posx, self.posy, text=self.username, font=("Purisa", 13), fill='white',tag=self.username)
c.after(10, run)
else: print(f'{self.username} 小车停止')
run()
# 小车移动速度随时变化
def car_speed_change(self):
global FLAG,player
time.sleep(2.3)
while FLAG:
if player.car.speed < 14: self.speed = random.uniform(player.car.speed - 0.3, player.car.speed + 0.7)
elif 14 < player.car.speed < 18: self.speed = random.uniform(player.car.speed - 0.8, player.car.speed + 0.5)
else: self.speed = random.uniform(19 - 1.1, 19 + 0.3)
time.sleep(1)
小车移动速度随时变化car_speed_change()方法,这里面可以看到有一个while死循环,所以要调用这个方法时需要开启一个子线程来调用该方法。这里面就是使小车每隔1秒后随机在一个范围值里面改变该小车的速度(player.car.speed——由自己的打字速度决定的),实时更新速度(其实在整个流程中只会对电脑的玩家小车更新速度,不然为啥子是随机设置速度喃)。
设置一个游戏名,再用tk.Canvas()画布下的create_image()方法创建小车。
在创建小车时会先创建一个小车对象,所以我在这里的想法就是可以理解为一个玩家就是一个小车。
# 玩家类
class Player:
def __init__(self,username):
self.username = '[玩家]'+username
# 创建小车
def car_create(self,c,carposy_list):
self.car = Car('./sucai/car1.png', carposy_list, 'img1', self.username)
self.car_img = tk.PhotoImage(file=self.car.filepath)
c.create_image(self.car.posx, self.car.posy, image=self.car_img, tag=self.car.cartag)
c.create_text(self.car.posx-30, self.car.posy, text=self.car.username, font=("Purisa", 16), fill='white', tag=self.car.username)
与玩家类同理。
# 电脑类
class Computer:
def __init__(self,username='[电脑]'):
self.username = username
# 创建小车
def car_create(self,c,filepath, posy, cartag, username):
self.car = Car(filepath, posy, cartag, username)
self.car_img = tk.PhotoImage(file=self.car.filepath)
c.create_image(self.car.posx, self.car.posy, image=self.car_img, tag=self.car.cartag)
c.create_text(self.car.posx-30, self.car.posy, text=self.car.username, font=("Purisa", 16), fill='white',tag=self.car.username)
在初始化类时,可以看到带参构造方法里面有个roadtype,这个就是在窗口类中选择赛道(Python,Java,MySql赛道)时得到的赛道类型,然后打开文件读取里面的内容(关键字单词)。将单词的长度处理一下来初始化赛道的数量(就是窗口类中create_road()循环创建赛道图片对象的个数)、及需要跑完赛道的长度。然后就是画起点线、终点线,roadmove()方法里面,self.road_s 判断赛道移动是否大于1000删除掉tag对象,for循环则是赛道的移动。
# 赛道类
class Road:
def __init__(self,roadtype):
self.text = []
with open(f'./sucai/{roadtype}关键字.txt', mode='r', encoding='utf-8') as f:
for line in f:
self.text.append(line.strip().split('\t')[0])
self.road_number = int(len(self.text)*1.2) if ROAD == 'Python' else int(len(self.text)*1.5) # 赛道的数量
self.road_length = (self.road_number - 3) * 1000 # 需要跑完赛道的长度
self.road_s = 0.0
# 起点线
def begin(self,c):
c.create_rectangle(100, 50, 150, 352, fill='#FFF6EE', tag='begin')
c.create_text(135, 200, text='R\ne\na\nd\ny\ni\nn\ng\n \nG\nO', font=("Purisa", 20), fill='black', tag='begin')
# 终点线
def destination(self,c):
self.c_end = c.create_text(self.road_length - 120, 200, text='终\n点', font=("Purisa", 52), fill='white',tag='end')
# 路相对于车移动
def roadmove(self,c,tag_road):
global FLAG,player
self.tag_road = tag_road
if FLAG:
self.road_s += player.car.speed
if self.road_s > 1000:
self.road_s = 0.0
if self.tag_road:
c.delete(self.tag_road.pop(0))
for i in range(1, self.road_number + 1):
c.move(i, -player.car.speed, 0)
c.move(self.c_end, -player.car.speed, 0)
小树类里面与赛道类差不多的,if self.posx >10时,则将会删除掉小树对象,else再self.posx = random.randint(550,950)位置重新产生一棵树。
# 小树类
class Tree:
speed = 0
def __init__(self, posx,posy,filepath,treetag='tree'):
self.posx = posx
self.posy = posy
self.filepath = filepath
self.treetag = treetag
# 创建树
def tree_create(self,c):
self.tree_img = tk.PhotoImage(file=self.filepath)
c.create_image(self.posx, self.posy, image=self.tree_img, tag=self.treetag)
# 树相对于车移动
def treemove(self, c):
global FLAG,player
if FLAG:
if self.posx >10:
self.speed = player.car.speed
self.posx -= self.speed
c.delete(self.treetag)
c.create_image(self.posx, self.posy, image=self.tree_img, tag=self.treetag)
else:
self.posx = random.randint(550,950)
self.speed = player.car.speed
self.posx -= self.speed
c.create_image(self.posx, self.posy, image=self.tree_img, tag=self.treetag)
loading_text()就是加载文本内容(单词),并设置每一页显示20个字(number = 20),其中创建的 self.l1_oop = [] 用于存储提示标签对象并绑定键盘事件。l_bind()方法是判断得到的打字内容(self.anwser = ‘’ # 拼接答案)是否和提示的单词一致。typing_speed()是记录每个一秒检测打字的速度,这里我是取cpm(CPM是Characters Per Minute的缩写,与KPM类似,表示每分钟输入了多少字符,中文名称是字符/分钟。
计算方法:用正确的总输入字符次数除以总花费的时间(以分钟为单位)。)来作为打字的速度。wpm是每分钟打了多少个单词数。
# 打字类
class display_text:
def __init__(self, gw):
self.gw = gw
self.l1_oop = [] # 存储提示标签对象
self.l2_oop = [] # 存储玩家打字时的标签对象
self.cpm_list = [] #用正确的总输入字符次数除以总花费的时间(以分钟为单位)
self.typspeed = 0.0 # 记录打字的速度
self.anwser = '' # 拼接答案
self.text = self.gw.road.text # 单词内容
self.text2 = self.text.copy()
self.text.extend(self.text2) # 单词内容翻倍 x 2
self.text_number = len(self.text) / 2 # 单词个数
self.loading_text()
# 加载打字内容
def loading_text(self):
col = 1 # 列数
number = 20 # 每页展示20个字
for i, text in enumerate(self.text[:number]):
l1 = tk.Label(gw.text_frame, text=text, bg='white', font=('微软雅黑', 15))
l2 = tk.Label(gw.text_frame, text='', bg='white', font=('微软雅黑', 15))
if i < int(number / 2):
l1.grid(row=1, column=col, )
l2.grid(row=2, column=col, )
elif int(number / 2) <= i < number:
l1.grid(row=3, column=col - int(number / 2), )
l2.grid(row=4, column=col - int(number / 2), )
col += 1
l1.focus_set()
l1.bind("" , self.l_bind)
self.l1_oop.append(l1)
self.l2_oop.append(l2)
# 标签绑定键盘事件
def l_bind(self, event):
# print(f"事件触发键盘输入:{event.char},对应的ASCII码:{event.keycode}")
global FLAG
if not FLAG: return
if not self.text: return
if event.keycode == 8:
self.anwser = ''
self.l2_oop[0].configure(text='')
return
if not 65 <= event.keycode <= 90: return
self.anwser += event.char
self.l2_oop[0].configure(text=self.anwser, bg='#FFFAE3')
result = self.text[0]
if self.anwser.strip() == result:
self.cpm_list.append(result)
self.l1_oop[0].configure(fg='red')
self.text.remove(result)
self.l1_oop.pop(0)
self.l2_oop.pop(0)
self.anwser = ''
if not self.l1_oop and len(self.text) != 0:
gw.text_frame.destroy()
gw.display_text_frame()
self.loading_text()
return
if len(self.anwser) >= len(result):
self.anwser = ''
# 检测打字速度, 每分钟输入了多少字符
def typing_speed(self):
global FLAG
time_ = 0
while FLAG:
time_ += 1
try:
self.cpm = round(len(''.join(self.cpm_list)) / time_ * 60)
self.wpm = round(len(self.cpm_list) / (time_ / 60))# 用来表示打字速度,即每分钟打多少个字(或单词)
gw.cpm_label.configure(text=f'cpm:{self.cpm}')
gw.wpm_label.configure(text=f'wpm:{self.wpm}')
except:
self.cpm = 0
self.wpm = 0
self.typspeed = self.cpm / 12
time.sleep(1)