基于Python实现成语填空游戏的示例代码
作者:木木子学python 发布时间:2021-09-17 18:09:05
前言
成语填空想必大家都是十分熟悉的了,特别是有在上小学的家长肯定都有十分深刻的印象。
在我们的认知里看图猜成语不就是一些小儿科的东西吗?
当然了你也别小看了成语调控小游戏,有的时候知识储备不够,你还真的不一定猜得出来是什么?更重要的是有的时候给你这个提示你都看不懂,那你就拿他没办法。——小学语文必备
成语是小学语文非常重要的一个知识点,几乎是逢考必有,作为基础,自然是需要长期的积累,并且需要积累到一定的数量,有了一定的量才能够产生质变,对于语文成绩才能够有一个分数上的提高。
词汇是语文不变的重点,尤其是成语,在作文中适量运用,可以为作文增加不少情感色彩,丰富情感表达,使内容变得更有味道,更具味道,内涵。
但是对于成语的记忆却是很多同学语文学习中的痛难点,死记硬背效果太差,忙活一天就背了几个词,效率实在是低下。
然而小学正是养成一个良好学习习惯的阶段,所以要找到适合自己的学习方法,这款游戏不仅可以锻炼小孩子的思维能力,更能增加家人之间的娱乐呢!家里有小孩子的可以一起玩儿哦!
一、环境准备
1)运行环境
本文用到的环境如下——
Python3、Pycharm社区版,第三方模块:pygame等部分自带的库只 要安装完 Python就可以直接使用了
一般安装:pip install +模块名
镜像源安装:pip install -i pypi.douban.com/simple/+模块名…
(之前有说过安装报错的几种方式跟解决方法,不会安装的可以去看下,还有很多国内镜像源 也有文章的)
2)素材图片等
二、代码展示
import sys
import random
import pygame
from pygame.locals import *
reload(sys)
sys.setdefaultencoding('utf-8')
f = open('words.txt')
all_idiom = f.readlines()
f.close()
word_dic = {}
for idiom in all_idiom:
idiom = idiom.strip().decode('utf-8')
for word in idiom:
if word not in word_dic:
word_dic[word] = [idiom]
else:
word_dic[word].append(idiom)
word_arr = list(word_dic.keys())
header_height = 30
main_space = 20
block_size = 36
block_num=12
bspace = 2
space = 20
width = block_size * block_num + main_space * 2
height = header_height + block_size * block_num + main_space * 2 + (block_size+space) * 3
pygame.init()
screen = pygame.display.set_mode((width,height))
screencaption = pygame.display.set_caption(u'成语填空')
font = pygame.font.Font(u'syht.otf', int(block_size*0.8))
dray_gray = 50,50,50
white = 255,255,255
#textImage = font.render(u'你好', True, white)
class IdiomInfo(object):
def __init__(self,idiom):
self.idiom = idiom
self.dire = 0
self.word_arr = []
class WordInfo(object):
def __init__(self, word, i, j):
self.i = i
self.j = j
self.word = word
self.is_lock = True
self.state = -1
self.hide_index = -1
self.op_hide_index = -1
class Matrix(object):
rows = 0
cols = 0
data = []
def __init__(self, rows, cols, data=None):
self.rows = rows
self.cols = cols
if data is None: data = [None for i in range(rows * cols)]
self.data = data
def set_val(self, x, y, val):
self.data[y * self.cols + x] = val
def get_val(self, x, y):
return self.data[y * self.cols + x]
def exist_val_four_around(self, x, y, ignore_set):
move_arr = [(-1,0),(1,0),(0,-1),(0,1)]
for dx,dy in move_arr:
tx = x + dx
ty = y + dy
if (tx,ty) in ignore_set: continue
if tx < 0 or tx >= self.cols or ty <0 or ty >= self.rows: continue
if self.data[ty * self.cols + tx]: return True
return False
def check_new_idiom(matrix, new_idiom, new_dire, word_info):
windex = new_idiom.index(word_info.word)
cx,cy = word_info.i, word_info.j
ignore_set = set([(cx,cy)])
new_idiom_word_arr=[]
for i in range(-windex,-windex+len(new_idiom)):
if i==0:
new_idiom_word_arr.append(word_info)
else:
tx = cx+i if new_dire == 0 else cx
if tx < 0 or tx >= block_num: return None,None
ty = cy if new_dire == 0 else cy+i
if ty < 0 or ty >= block_num: return None,None
if matrix.exist_val_four_around(tx, ty, ignore_set): return None,None
old_word_info = matrix.get_val(tx, ty)
if old_word_info:
return None,None
new_word_info = WordInfo(new_idiom[i+windex], tx, ty)
new_idiom_word_arr.append(new_word_info)
return new_idiom_word_arr,windex
def add_idiom_to_matrix(matrix, word_dic, idiom_dic, idiom_num):
if idiom_num == 0: return 0
for idiom,idiom_info in idiom_dic.items():
dire = idiom_info.dire
new_dire = 1 - dire
for word_info in idiom_info.word_arr:
word = word_info.word
idiom_list = word_dic[word]
for new_idiom in idiom_list:
if new_idiom in idiom_dic: continue
new_idiom_word_arr,windex = check_new_idiom(matrix, new_idiom, new_dire, word_info)
if new_idiom_word_arr:
new_idiom_info = IdiomInfo(new_idiom)
new_idiom_info.dire = new_dire
for new_index in range(len(new_idiom_word_arr)):
new_word_info = new_idiom_word_arr[new_index]
if new_index == windex:
new_idiom_info.word_arr.append(word_info)
else:
matrix.set_val(new_word_info.i, new_word_info.j , new_word_info)
new_idiom_info.word_arr.append(new_word_info)
idiom_dic[new_idiom] = new_idiom_info
return len(new_idiom) -1 + add_idiom_to_matrix(matrix, word_dic, idiom_dic, idiom_num - 1)
return 0
def get_idiom_matrix(word_arr, word_dic, idiom_num):
cx = 4
cy = 4
matrix = Matrix(block_num, block_num)
n = random.randint(0,len(word_arr)-1)
word = word_arr[n]
idiom = word_dic[word][0]
idiom_dic={}
idiom_dic[idiom] = IdiomInfo(idiom)
wn = len(idiom)
last_i = -100
for i in range(len(idiom)):
word_info = WordInfo(idiom[i],cx-1+i,cy)
matrix.set_val(cx-1+i,cy,word_info)
idiom_dic[idiom].word_arr.append(word_info)
wn += add_idiom_to_matrix(matrix, word_dic, idiom_dic, idiom_num-1)
return matrix, idiom_dic, wn
bg_image = pygame.image.load('bg.jpeg')
bg_image = pygame.transform.scale(bg_image,(width, height))
bg2_image = pygame.image.load('bg2.jpeg')
bg2_image = pygame.transform.scale(bg2_image,(block_size*block_num,block_size*block_num))
block_bg_image = pygame.image.load('tzg.jpg')
block_bg_image = pygame.transform.scale(block_bg_image,(block_size-bspace*2,block_size-bspace*2))
def get_hide_arr(matrix, idiom_dic, all_word_num, percent):
hide_arr = []
for k,v in idiom_dic.items():
n = random.randint(0, len(v.word_arr)-1)
word_info = v.word_arr[n]
if word_info.hide_index != -1:continue
word = word_info.word
info = matrix.get_val(word_info.i,word_info.j)
info.word = ''
info.hide_index = len(hide_arr)
info.is_lock = False
hide_arr.append([word_info.i,word_info.j,word,None])
tmp_arr = []
for i in range(block_num):
for j in range(block_num):
info = matrix.get_val(i,j)
if info and info.word:
tmp_arr.append((i,j,info.word))
while len(hide_arr) < all_word_num*percent:
n = random.randint(0,len(tmp_arr)-1)
i,j,word = tmp_arr.pop(n)
info = matrix.get_val(i,j)
info.word = ''
info.hide_index = len(hide_arr)
info.is_lock = False
hide_arr.append([i,j,word,None])
return hide_arr
def get_next_select(matrix, x, y):
arr = []
for i in range(block_num):
for j in range(block_num):
info = matrix.get_val(i, j)
if info is not None and len(info.word) == 0:
dist = (i-x)*(i-x)+(j-y)*(j-y)
if i<x: dist+=0.2
if j<y: dist+=0.4
arr.append((i,j,dist))
if len(arr) == 0:
return None
arr.sort(cmp=lambda x,y:cmp(x[-1],y[-1]))
return (arr[0][0],arr[0][1])
def check_idiom():
for idiom, idiom_info in idiom_dic.items():
tmp_idiom_str = ''
word_arr = idiom_info.word_arr
for word_info in word_arr:
word = word_info.word
if len(word) > 0:
tmp_idiom_str+=word
if len(tmp_idiom_str) == len(idiom):
state = 1 if tmp_idiom_str == idiom else 2
else:
state = 0
for word_info in word_arr:
if word_info.state != 1: word_info.state = state
for idiom, idiom_info in idiom_dic.items():
word_arr = idiom_info.word_arr
for word_info in word_arr:
if word_info.state != 1:
return False
return True
stage = 1
def init(new_stage):
idiom_num = (new_stage/5)+3
if new_stage>100:
percent = 0.7
else:
percent = 0.2+(new_stage*1.0/100)*(0.7-0.2)
matrix,idiom_dic,all_word_num = get_idiom_matrix(word_arr, word_dic, idiom_num)
hide_arr = get_hide_arr(matrix, idiom_dic, all_word_num, percent)
select_rect = hide_arr[0][0],hide_arr[0][1]
stage_textImage = pygame.font.Font(u'syht.otf', 30).render(u'第%s关'%new_stage, True, dray_gray)
return matrix,idiom_dic,all_word_num,hide_arr,select_rect,stage_textImage
matrix,idiom_dic,all_word_num,hide_arr,select_rect,stage_textImage = init(stage)
stage_font_width, stage_font_height = stage_textImage.get_size()
stage_x = (width - stage_font_width)/2
stage_y = (header_height - stage_font_height)/2+main_space/2
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == MOUSEBUTTONDOWN:
pressed_array = pygame.mouse.get_pressed()
if pressed_array[0]:
x, y = pygame.mouse.get_pos()
for i in range(block_num):
for j in range(block_num):
bx = main_space + block_size*i+bspace
by = header_height + main_space + block_size*j+bspace
if x >= bx and x <= bx+block_size-bspace*2 and y >= by and y<= by+block_size-bspace*2:
info = matrix.get_val(i, j)
if info and info.state != 1 and info.hide_index >= 0:
if info.op_hide_index>=0:
hide_arr[info.op_hide_index][-1] = None
info.word = ''
info.op_hide_index=-1
check_idiom()
select_rect = i,j
break
sx = main_space
sy = header_height + main_space+ block_size*block_num +space
n = 0
for hi in range(len(hide_arr)):
tmp_x = sx + (n%block_num)*block_size
tmp_y = sy + (n/block_num)*block_size
if hide_arr[hi][-1] is None and x >= tmp_x and x <= tmp_x+block_size-bspace*2 and y >= tmp_y and y<= tmp_y+block_size-bspace*2:
info = matrix.get_val(select_rect[0],select_rect[1])
info.word = hide_arr[hi][2]
info.op_hide_index = hi
info.state = 0
hide_arr[hi][-1] = select_rect
new_select_rect = get_next_select(matrix, select_rect[0],select_rect[1])
select_rect = new_select_rect
flag = check_idiom()
if flag:
stage += 1
matrix,idiom_dic,all_word_num,hide_arr,select_rect,stage_textImage = init(stage)
break
n += 1
screen.blit(bg_image, (0,0))
screen.blit(stage_textImage, (stage_x,stage_y))
panel = screen.subsurface((main_space,header_height+main_space,block_size*block_num,block_size*block_num))
panel.blit(bg2_image, (0,0))
for i in range(block_num):
for j in range(block_num):
info = matrix.get_val(i,j)
if info is not None:
bx = block_size*i+bspace
by = block_size*j+bspace
panel.blit(block_bg_image, (bx,by))
if info.state == 1:
textImage = font.render(info.word, True, (30,144,30))
elif info.state == 2:
textImage = font.render(info.word, True, (255,0,0))
elif info.is_lock == 1:
textImage = font.render(info.word, True, (150,150,150))
else:
textImage = font.render(info.word, True, dray_gray)
tw, th = textImage.get_size()
dx=(block_size-bspace*2-tw)/2
dy=(block_size-bspace*2-th)/2
panel.blit(textImage, (bx+dx,by+dy))
if (i,j) == select_rect:
pygame.draw.rect(panel,(255,0,0),(bx,by,block_size-bspace*2,block_size-bspace*2),2)
sx = main_space
sy = header_height + main_space+ block_size*block_num +space
n = 0
for i,j,word,op in hide_arr:
screen.blit(block_bg_image, (sx + (n%block_num)*block_size,sy + (n/block_num)*block_size))
if op is None:
textImage = font.render(word, True, dray_gray)
tw, th = textImage.get_size()
dx=(block_size-bspace*2-tw)/2
dy=(block_size-bspace*2-th)/2
screen.blit(textImage, (dx+sx+ (n%block_num)*block_size,dy+sy+ (n/block_num)*block_size))
n+=1
pygame.display.update()
三、效果展示
1)成语填空第2关
2)成语填空第56关
来源:https://juejin.cn/post/7200591001904431162
猜你喜欢
- 前言视图是数据库系统中一种非常有用的数据库对象。MySQL 5.0 之后的版本添加了对视图的支持。认识视图视图是一个虚拟表,其内容由查询定义
- 一、官方文档介绍官网nn.Conv2d:对由多个输入平面组成的输入信号进行二维卷积二、torch.nn.Conv2d()函数详解参数详解to
- 第一种方法:****1.****打开SQL Server,写好登录名和密码点击连接.****2.****打开数据库,右键某一个数据库,选择&
- 人生苦短,菜鸟学Python!今天,我们会一次性分享6个堪称神仙的内置函数。在很多计算机书籍中,它们也通常作为高阶函数来介绍。而我自己在日常
- 目录1、准备基础数据2、一次性展示数据3、引入分页器附:drf分页器的使用1.1 PageNumberPagination1.2 Limit
- 首先,在数据库中创建一个表,用于存放图片:CREATE TABLE Images(Id INT PRIMARY KEY AUTO_INCRE
- 我就废话不多说了,大家还是直接看代码吧~//isSymbol表示有无符号func BytesToInt(b []byte, isSymbol
- 按照下面一步一步来,安 * p就是这么简单。脚本之家下载渗透测试软件Burp Suite Professionalhttps://www.jb
- 我的操作系统为centos6.51 首先选择django要使用什么数据库。django1.10默认数据库为sqlite3,本人想
- 新年礼,提供简单、易套用的 jQuery AJAX 上传示例及代码下载。后台对文件的上传及检查,以 C#/.NET Handler 处理 (
- 本文实例讲述了JS实现获取毫秒值及转换成年月日时分秒的方法。分享给大家供大家参考,具体如下:时间日期对象创建方式一var date=new
- 起步在Python中,对于一个对象的属性访问,我们一般采用的是点(.)属性运算符进行操作。例如,有一个类实例对象foo,它有一个name属性
- NextGEN Gallery是Wordpress中著名的相册插件,遗憾的是不支持中文等unicode字符,本文将介绍如何将目录转换为拼音(
- 问题你想定义跟actor模式中类似“actors”角色的任务解决方案actor模式是一种最古老的也是最简单的并行和分布式计算解决方案。 事实
- # coding:utf-8 import os import sys def cut_and_paste_file(source, des
- 当我们花费大量的精力训练完网络,下次预测数据时不想再(有时也不必再)训练一次时,这时候torch.save(),torch.load()就要
- 本文实例为大家分享了python实现简单学生管理系统的具体代码,供大家参考,具体内容如下学生管理系统相信大家学各种语言的时候,练习总是会写各
- 前言mysql是高版本,当执行group by时,select的字段不属于group by的字段的话,sql语句就会报错。错误提示:this
- 本文实例实现的功能是监控一个文件或目录的变化,如果有变化,把文件上传备份至备份主机,并且要监控上传过程是否有问题等,具体内容如下#!/usr
- 众所周知,随着数据库体积的日益庞大,其备份文件的大小也水涨船高。虽然说通过差异备份与完全备份配套策略,可以大大的减小SQL Server数据