pygame之连连看

内容目录

main
	void  #音效存放
	picture #图片存放
	need #各种计算相关的函数
	play.py #运行
	db.db #数据库
	loadding.py #对图片进行加载

下面展示的是play部分逻辑
游戏顺序为
打开Play 之后显示 tk界面 连接数据库 点击关卡之后进行游戏fff
在这里插入图片描述

# 屏幕大小650 550 素材大小38x38
import pygame
import tkinter as Tk
from pygame.locals import *
from need.extend import fake_copy,init_pos,get_pos,get_total,is_same,show_pic,wash,get_tip
import sqlite3
import time
from need.tools import tool
from loading import pic,bg,button,top,good,nogood,order,success,over,sorry,false,restart,bg_sound,\
	level__,level___,one,two,three,time_,tick_,score_sep_
import time
sep=38
FPS=30
width=650;height=550
row=12;col=10
click_list=[]
def MainGame(name,level,init_score=0):
	global row,col
	global click_list,total
	if level==1:
		row=one[0]
		col=one[1]
	if level==2:
		row=two[0]
		col=two[1]
	if level==3:
		row=three[0]
		col=three[1]
	total=get_total(row,col,12)
	total_=fake_copy(total) #一个膨胀的total
	start_pos,start,end=init_pos(row,col,width,height) #可以填入get_pos的第二个参数
	index=[]
	tip_pos=[]
	click=False #点击事件失效
	score=init_score
	score_sep=score_sep_  #每一秒增加x分
	timer=0
	time_sep=1150
	choice=[]
	tick=tick_ #提示次数
	time=time_
	time_default=-time_sep*time # 此处时时间的计算公式
	time_count=time_default
	stop=False
	fall_b=False
	default=True
	real_pos=(0,0)
	size=18
	pos__=(18,518)
	checkable=True
	text=pygame.font.SysFont('Kaiti',size, True)
	text_tick=pygame.font.SysFont('Kaiti',14, True)
	start__=text.render('开始',True,(255,255,255))
	end__=text.render('暂停',True,(255,255,255))
	while True:
		for event in pygame.event.get():
			if event.type==QUIT:
				pygame.display.quit()
			elif event.type==MOUSEBUTTONDOWN:
				if suc_b:
					init_score=score + (abs(time_count) // time_sep) * score_sep
					if level==1:
						return MainGame(name,2,init_score=init_score)
					elif level==2:
						return MainGame(name,3,init_score=init_score)
					else:
						return init_score,name
				if fall_b:
					return score,name
				press_list=pygame.mouse.get_pressed()
				for i in range(len(press_list)):
					if press_list[i]==0:
						real_pos=pygame.mouse.get_pos()
						click=True
		screen.blit(bg,(0,0))
		screen.blit(button,(0,508))
		suc_b=suc(total)
		if time_count>0:
			fall_b=True

		if suc_b:
			screen.blit(success,(150,100))
			stop=True
		if fall_b:
			screen.blit(false,(150,100))
			stop=True
		if stop==True: # 如果停止 ,停止贴图,
			screen.blit(start__,(pos__))
		else:#这个如果没有stop 那么就要贴图
			w=clock.get_rawtime()
			time_count+=w
			timer-=w
			if timer<0:
				timer=0
			show_pic(screen,row,col,total,pic,start_pos)
			screen.blit(top,(0,0))
			if time_count>time_default/2: #时间进度条的划分
				color=(255,0,0)
			else:
				color=(0,255,0)
			pygame.draw.rect(screen,color,(410,13,200*((-time_count)/time_default),20),0)

			score_show=text.render(str(score),True,(255,255,255))#写下分数


			screen.blit(score_show,(510,15))
			screen.blit(end__,(pos__))
			if tip_pos:
				tip_pos_1=start_pos[tip_pos[0]]
				tip_pos_2=start_pos[tip_pos[1]]
				pygame.draw.rect(screen, (255, 0, 0), (tip_pos_1[0], tip_pos_1[1], sep, sep), 2)
				pygame.draw.rect(screen, (255, 0, 0), (tip_pos_2[0], tip_pos_2[1], sep, sep), 2)
		if choice and None not in choice:
			real=start_pos[choice[0]]
			pygame.draw.rect(screen,(255,0,0),(real[0],real[1],sep,sep),2)
		# 点击开启点击时间  click_list
		if click:
			if not checkable:
				total=wash(total)
				total_=fake_copy(total_)
			checkable = get_tip(total , total_)
			# print(real_pos)
			if not stop and real_pos:
				#下面是对框架内的内容的删除
				if end[0]>real_pos[0]>start[0] and end[1]>real_pos[1]>start[1]:#此处为一个点击框架
					index=get_pos(real_pos,start_pos,sep)
					tip_pos.clear() #如果存在tip_pos 则消除
					# print(index)
					if index and index!=None and  not total[index[0]][index[1]]=='*':
						if click_list  and click_list[0]!=None and None not in [click_list]:
							w=click_list[0]
							check=tool(total,w[1],w[0],index[1],index[0])
							if is_same(total,click_list[0],index)and (check.main(total_)):
								total[click_list[0][0]][click_list[0][1]]='*'
								total_[click_list[0][0]+1][click_list[0][1]+1]='*'
								total[index[0]][index[1]]='*'
								total_[index[0]+1][index[1]+1]='*'
								score+=10
								# print(timer)
								if timer>time_sep:
									time_count-=time_sep*3
								elif timer>0:
									time_count-=time_sep*2
								timer=time_sep*2
								if level==level__ or level==level___:
									total=wash(total)
									total_=fake_copy(total)
								# print()
								# print('连接成功')
							click_list.clear()
							choice.clear()
						else:
							click_list.clear()
							choice.clear()
							choice.append(index)
							click_list.append(index)
			click=False#不管如何结束点击时间
		screen.blit(text_tick.render(str(tick),True,(0,0,255)),(559,525))
		#下面添加暂停

		if real_pos:
			if real_pos[0] < 72 and real_pos[1] > 509:#暂停位置
				stop = stop ^ default
			if real_pos[0] < 73 and real_pos[1] < 32: #洗牌位置
				total = wash(total)
				total_ = fake_copy(total)
				if tip_pos:
					tip_pos.clear()
			if real_pos[0] > 586 and real_pos[1] < 35:#退出
				return None,name #正式用  None,name
			if not stop and real_pos[0] >588 and real_pos[1]>517: #提示
				if tick>0:
					tick-=1
					tip_pos=get_tip(total,total_)
					if not tip_pos:
						tip_pos=[]
						total=wash(total)
						total_=fake_copy(total_)
		real_pos=None
		clock.tick()
		if not checkable:
			screen.blit(sorry , (150 , 100))
		pygame.display.update()
def suc(total):
	for j in range(len(total)):
		for i in range(len(total[0])):
			if total[j][i]!='*':
				return False
	return True
def showGameover(score=None,name='not found'):
	# print(score,name)
	conn = sqlite3.connect('test.db')
	cursor=conn.cursor()
	sql = '''SELECT * FROM users WHERE name=:username '''
	c=cursor.execute(sql,{'username':name})
	if not score:
		pass
	else:
		info=c.fetchone()
		if not info:
			time_=str(time.strftime("%m %d %X", time.localtime()))
			id = cursor.execute("select count(*) from users ").fetchone()[0] + 1
			sql="INSERT INTO users VALUES (?,?,?,?,?)"
			cursor.execute(sql,(id,name,time_,0,score))
			# print('insert')
		else:
			sql="UPDATE users SET score=:score WHERE name=:name"
			cursor.execute(sql,{'score':score+info[4],'name':name})
			# print('update')
		conn.commit()

	text=pygame.font.SysFont('Kaiti',22, True)
	text1=pygame.font.SysFont('Kaiti',12, True)
	click=False
	sep=50
	top_five_,id=search(cursor)
	five_id=[]
	time_=[]
	top_five=[]
	top_five_active={}
	for i in top_five_:
		top_five.append(list(i))
		five_id.append(i[0])
		z=i[2].split(' ')
		time_.append('——'+z[0]+'月'+z[1]+'日'+z[2])#添加上时间
		top_five_active[i[0]]=nogood
	str_='第{}名:{:^4} 分数是{}'
	while True:
		for event in pygame.event.get():
			if event.type==QUIT:
				pygame.display.quit()
				# print('1')
			elif event.type==MOUSEBUTTONDOWN:
				press_list=pygame.mouse.get_pressed()
				for i in range(len(press_list)):
					if press_list[i]==0:
						real_pos=pygame.mouse.get_pos()
						# print(real_pos)
						click=True
		screen.blit(bg,(0,0))
		screen.blit(over,(220,100))
		screen.blit(restart,(576,27))
		if click:
			if real_pos is not None:
				for i in range(5):
					if 511<real_pos[0]<549 and 178+i*sep<real_pos[1]<203+i*sep:
						top_five_active[five_id[i]]=good
			if 576<real_pos[0]<576+50 and 27<real_pos[1]<27+50:
				return None
			click=False
		# screen.blit(order,(150,-30))
		index=0
		for i in top_five:
			str__=str_.format(index+1,i[1],i[4])
			screen.blit(text.render(str__,True,(0,0,0)),(100,180+sep*index))
			screen.blit(text1.render(str(time_[index]),True,(0,0,0)),(325,210+sep*index))
			screen.blit(top_five_active[i[0]],(520,180+sep*index))
			index+=1
		pygame.display.update()
def search(cursor):
	id = cursor.execute("select count(*) from users ").fetchone()[0] + 1
	c=cursor.execute('select * from users order by score desc ')
	return c.fetchall()[:5],id
def main(name,level):
	global screen,clock
	pygame.init()
	jiange=pygame.time.get_ticks()
	screen=pygame.display.set_mode((width,height))
	clock=pygame.time.Clock()
	pygame.display.set_caption('连连看')
	while True:
		pygame.mixer_music.play(loops=-1)
		score,name=MainGame(name,level)
		showGameover(score,name)
class MyApp(object):
	def __init__( self , parent ):
		#基本定义
		self.root = parent
		self.root.title("欢迎登陆连连看")
		self.canv=Tk.Canvas(self.root)
		# 图片位置
		self.img=Tk.PhotoImage(file='./picture/tkbg300.gif')
		self.img_=self.canv.create_image(0,0,anchor='nw',image=self.img)
		self.canv.place(x=0,y=0,height=300,width=300)

		#输入
		self.input_=Tk.Variable()
		self.input_area=Tk.Entry(self.root,textvariable=self.input_,width=20)
		self.input_area.place(x=105,y=45)

		#按钮
		btn1 = Tk.Button(self.root , text="第一关" , command=lambda :self.openFrame(self.input_.get(),1))
		btn2= Tk.Button(self.root , text="第二关" , command=lambda :self.openFrame(self.input_.get(),2))
		btn3 = Tk.Button(self.root , text="第三关" , command=lambda :self.openFrame(self.input_.get(),3))
		btn1.place(x=50,y=100)
		btn2.place(x=130,y=100)
		btn3.place(x=210,y=100)
	def hide( self ):
		self.root.withdraw()
	def openFrame( self,total ,level):
		self.hide()
		if not total:
			self.root.update()
			self.root.deiconify()
		else:
			main(total,level)
			# print('start')
if __name__=='__main__':
	root = Tk.Tk()
	root.geometry("300x168")
	app = MyApp(root)
	root.mainloop()
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值