基于Python实现成语填空游戏的示例代码

目录
  • 前言
  • 一、环境准备
  • 二、代码展示
  • 三、效果展示

前言

成语填空想必大家都是十分熟悉的了,特别是有在上小学的家长肯定都有十分深刻的印象。

在我们的认知里看图猜成语不就是一些小儿科的东西吗?

当然了你也别小看了成语调控小游戏,有的时候知识储备不够,你还真的不一定猜得出来是什么?更重要的是有的时候给你这个提示你都看不懂,那你就拿他没办法。——小学语文必备

成语是小学语文非常重要的一个知识点,几乎是逢考必有,作为基础,自然是需要长期的积累,并且需要积累到一定的数量,有了一定的量才能够产生质变,对于语文成绩才能够有一个分数上的提高。

词汇是语文不变的重点,尤其是成语,在作文中适量运用,可以为作文增加不少情感色彩,丰富情感表达,使内容变得更有味道,更具味道,内涵。

但是对于成语的记忆却是很多同学语文学习中的痛难点,死记硬背效果太差,忙活一天就背了几个词,效率实在是低下。

然而小学正是养成一个良好学习习惯的阶段,所以要找到适合自己的学习方法,这款游戏不仅可以锻炼小孩子的思维能力,更能增加家人之间的娱乐呢!家里有小孩子的可以一起玩儿哦!

一、环境准备

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关

以上就是基于Python实现成语填空游戏的示例代码的详细内容,更多关于Python成语填空的资料请关注我们其它相关文章!

(0)

相关推荐

  • 基于Python实现的扫雷游戏实例代码

    本文实例借鉴mvc模式,核心数据为model,维护1个矩阵,0表无雷,1表雷,-1表已经检测过. 本例使用python的tkinter做gui,由于没考虑可用性问题,因此UI比较难看,pygame更有趣更强大更好看,做这些小游戏更合适,感兴趣的读者可以尝试一下! 具体的功能代码如下: # -*- coding: utf-8 -*- import random import sys from Tkinter import * class Model: """ 核心数据类,维护一

  • Python版的文曲星猜数字游戏代码

    复制代码 代码如下: # -*- coding: utf-8 -*- import random #数字类class NumberItem: #数字个数    _GUESS_NUMBER_COUNT_ = 4 def __init__(self):        self._num_ = [] #长度是否标准        def IsFormat(self):        return self._num_.__len__() == self._GUESS_NUMBER_COUNT_ #生成

  • 用Python编写一个简单的俄罗斯方块游戏的教程

    俄罗斯方块游戏,使用Python实现,总共有350+行代码,实现了俄罗斯方块游戏的基本功能,同时会记录所花费时间,消去的总行数,所得的总分,还包括一个排行榜,可以查看最高记录. 排行榜中包含一系列的统计功能,如单位时间消去的行数,单位时间得分等. 附源码: from Tkinter import * from tkMessageBox import * import random import time #俄罗斯方块界面的高度 HEIGHT = 18 #俄罗斯方块界面的宽度 WIDTH = 10

  • Python加pyGame实现的简单拼图游戏实例

    本文实例讲述了Python加pyGame实现的简单拼图游戏.分享给大家供大家参考.具体实现方法如下: import pygame, sys, random from pygame.locals import * # 一些常量 WINDOWWIDTH = 500 WINDOWHEIGHT = 500 BACKGROUNDCOLOR = (255, 255, 255) BLUE = (0, 0, 255) BLACK = (0, 0, 0) FPS = 40 VHNUMS = 3 CELLNUMS

  • python3.3使用tkinter开发猜数字游戏示例

    利用这个小游戏可以学习一下ython3.3中tkinter的使用方法 复制代码 代码如下: # -*- coding: utf-8 -*-import tkinter as tkimport sysimport randomimport re number = random.randint(0,1024)running = Truenum = 0nmaxn = 1024nminn = 0 def eBtnClose(event):    root.destroy() def eBtnGuess(

  • 基于Python实现成语填空游戏的示例代码

    目录 前言 一.环境准备 二.代码展示 三.效果展示 前言 成语填空想必大家都是十分熟悉的了,特别是有在上小学的家长肯定都有十分深刻的印象. 在我们的认知里看图猜成语不就是一些小儿科的东西吗? 当然了你也别小看了成语调控小游戏,有的时候知识储备不够,你还真的不一定猜得出来是什么?更重要的是有的时候给你这个提示你都看不懂,那你就拿他没办法.——小学语文必备 成语是小学语文非常重要的一个知识点,几乎是逢考必有,作为基础,自然是需要长期的积累,并且需要积累到一定的数量,有了一定的量才能够产生质变,对于

  • 基于Python实现24点游戏的示例代码

    目录 1.前言 2.思路 3.代码 1.前言 24数大家之前玩过没有? 规则:一副扑克牌抽走大王,小王,K,Q,J(有的规则里面会抽走10,本文一律不抽走),之后在牌堆里随机抽取四张牌,将这四张牌加减乘除得到24. 如果再高级一点,还会有根号.阶乘.幂之类的算法,别问为啥不能幂运算,问就是懒,自己看思路自己实现去(bushi. 知识点:随机数,列表,嵌套判断,循环,死循环,都是新手接触的东西. 由于不能进行像根号,阶乘高级的运算,改版之后完全可以了. 话不多说,上思路 2.思路 1.随机生成四个

  • Python实现炸金花游戏的示例代码

    今天的第二个作品,哈哈哈哈,搞起来感觉还挺有意思的,不过代码里纸牌J,Q,K,A几个数字被我替换成了11,12,13,14......主要是没有想到简单的办法让其比较,索性都用数字了,我太菜了,希望有大佬指点一下. 代码如下: import random   #导入随机数函数 def puke():     """     生成一副52张的扑克牌(除去大小王)     :return:     """     list1 = ['黑桃', '红桃

  • 通过Python实现猜灯谜游戏的示例代码

    目录 导语 猜灯谜界面 程序讲解 构造初始界面 构造灯谜类对象 监控鼠标事件 源码 导语 新的一年迎来了元宵节,元宵佳节在陪伴家人的同时,自然也少不了赏花灯,猜灯谜的项目.当然,受到疫情的影响,许多地方今年无法出门赏花灯,猜灯谜. 但是不要紧,小编昨晚用Python弄了一猜灯谜的小程序让大家享受一把猜灯谜乐趣 猜灯谜界面 来看一下猜灯谜的小程序是怎么玩的.先看一下效果图: 程序讲解 构造初始界面 对于程序界面的构造,利用的是python3.6版本下安装2.0.1版本的pygame库.其界面的初始

  • 基于JS实现Flappy Bird游戏的示例代码

    前言 Flappy Bird 是一款无尽的游戏,玩家可以控制一只鸟.玩家必须保护小鸟免于与管道等障碍物相撞.每次小鸟通过管道时,分数都会增加一.当小鸟与管道碰撞或因重力而坠落时,游戏结束.以下部分描述了构建此游戏必须采取的步骤. 游戏可以通过这个链接进入 完整源码地址 实现代码 HTML 部分:在此部分中,创建和加载游戏的元素.选择背景.鸟类.障碍和得分元素的图像.接下来,我们创建并链接 style.css 和 index.js 文件. <!DOCTYPE html> <html>

  • 基于Python编写微信清理工具的示例代码

    目录 主要功能 运行环境 核心代码 完整代码 前几天网上找了一款 PC 端微信自动清理工具,用了一下,电脑释放了 30GB 的存储空间,而且不会删除文字的聊天记录,很好用,感觉很多人都用得到,就在此分享一下,而且是用 Python 写的,喜欢 Python 的小伙伴可以探究一下. 主要功能 它可以自动删除 PC 端微信自动下载的大量文件.视频.图片等数据内容,释放几十 G 的空间占用,而且不会删除文字的聊天记录,可以放心使用. 工作以后,微信的群聊实在太多了,动不动就被拉入一个群中,然后群聊里大

  • 基于C语言实现迷宫游戏的示例代码

    目录 C语言迷宫游戏 定义地图 打印地图方法一 打印地图方法二 定义起点和终点位置 实现读取按键 实现小球下向下移动一步 总结小球移动规律 实现重新打印地图 实现连续移动 实现小球下向上下左右移动 实现小球走到终点就胜利 C语言迷宫游戏 这篇文章是给学完并学懂了C语言的分支(选择和循环)结构和二维数组的朋友看的. 要做一个游戏或者程序先要想好有那些要求,以下是我认为一个迷宫必带的要求: 迷宫要先打印出来(要设置墙.空气.小球的起点),是墙就不能,是空气就可以走. 每次输入'w'.'a'.'s'.

  • 基于Vue3实现数字华容道游戏的示例代码

    目录 前言 环境 思路 实现 GameCnt GameTool GamePass GameTip Menu 最后 前言 恰逢春之四月,天气忽热忽凉,遇游戏大赛,以笨拙之技,书一篇小文. 游戏规则:存在n*n的格子,需要将它们按数字顺序或图片顺序一一还原即可. 环境 主要环境: vue3 version:3.2.4 vite version:2.5.0 vue-router version:4.0.14 注:这个游戏的路由使用的是自动路由插件 主要插件: windicss version:3.5.

  • 基于JS实现蜘蛛侠动作游戏的示例代码

    目录 代码结构 代码展示 HTML JS 项目运行 游戏截图 整个游戏源码是由html.js. css.图片等代码完成的,无后端数据保存功能. 代码结构 js文件夹是游戏事件控制文件 vapp文件夹是游戏图片文件 icon.png 是网页游戏图标 index.html 是游戏主页 代码展示 HTML index.html代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:/

  • 基于JS实现飞机大战游戏的示例代码

    目录 演示 技术栈 源码 定义敌方战机 定义我方战机 碰撞检测 演示 技术栈 今天没有什么特别要讲的,要不我们提前介绍下次要做的技术吧.你不说话就是同意了.我们开始了. 下图是正则表达式的一些总结大家可以先看看哦 (function() { /** * 1. JavaScript使用正则式的函数 */ const str = "abchelloasdasdhelloasd"; // 1. 查找 console.log(str.search("h")); // 3 /

随机推荐