先说一下这个 参考链接
https://www.cnblogs.com/qiu2013/p/6087627.html
最近太忙了 而且心情不是很好 我就直接根据别人的代码改了 以前C和C++ JAVA的代码我也想上传 但是 好像出了bug 代码放着放着也能出bug 也是醉了 然后我也懒上传了 然后 我这个增加了一个 排行榜 添加到数据库里面了
然后背景加了一个图片 然后 就这样
连接数据库成功后 会有一个 排行榜 这个排行榜就是 我们数据库里面的值
我是取出来在 python里面进行排行的
直接看代码把 感觉写的注释还挺清楚的
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import win32api,win32con
import pygame,sys,time,random
from pygame.locals import *
from tkinter import *
import pymysql
# 定义颜色变量
Color=[]
redColour = pygame.Color(255,0,0)
blackColour = pygame.Color(0,0,0)
whiteColour = pygame.Color(0,255,0)
greyColour = pygame.Color(150,150,150)
play_name=""#游戏名
fraction=0#积分
def takeSecond(elem):
return elem[1]
#定义连接数据库的名单
def connectsql():
db = pymysql.connect("localhost","root","","snake" )
cursor = db.cursor()
sql="select * from snake_play where name=\"{}\"".format(play_name)
try:
print(sql)
cursor.execute(sql)
results = cursor.fetchall()
print(results)
l=list(results)
print(l)
if(len(l)==0):
sql="INSERT INTO snake_play(name,fraction) VALUES(\"%s\",%d)"%(play_name,fraction)
try:
print(sql)
cursor.execute(sql)
db.commit()
except:
db.rollback()
else:
if(l[0][1]<fraction):
sql="UPDATE snake_play set fraction=%d where name =\"%s\""%(fraction,play_name)
try:
print(sql)
cursor.execute(sql)
db.commit()
except:
db.rollback()
except:
db.rollback()
#print(1)
sql="""SELECT * FROM snake_play """
print(sql)
try:
cursor.execute(sql)
results = cursor.fetchall()
print(results)
sortsql(results)
except:
print(db.rollback())
#对数据库查询到的内容排序
def sortsql(results):
master=Tk()
master.title("贪吃蛇排行榜")
sb=Scrollbar(master)
sb.pack(side=RIGHT,fill=Y)
thelB=Listbox(master,yscrollcommand=sb.set,selectmode=EXTENDED,height=30,width=50)#2 设置可以多选 3 设置高度
thelB.pack()
l=list(results)
print(l)
l.sort(key=takeSecond)
l=l[::-1]
print(l,len(l))
sum=1
strs="名字"+" "*10+"分数"+" "*10+"排行"
thelB.insert(END,strs)
print(strs)
for i in l:
strs=str(i[0]).ljust(12," ")+str(i[1]).ljust(12," ")+str(sum).ljust(12," ")
print(strs)
sum+=1
thelB.insert(END,strs)
thelB.pack(side=LEFT,fill=BOTH)#控件向什么地方 向什么地方填充
sb.config(command=thelB.yview)
mainloop()
# 定义gameOver函数
def gameOver(playSurface):
win32api.MessageBox(0, "游戏结束", "警告",win32con.MB_OK)
gameOverFont = pygame.font.Font(None,72)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 100)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
connectsql()
time.sleep(0.5)
pygame.quit()
sys.exit()
#定义判断游戏是否结束函数
def ordie(snakePosition,snakeSegments,playSurface):
if snakePosition[0] > 620 or snakePosition[0] < 0:
#print(snakePosition[0])
gameOver(playSurface)
if snakePosition[1] > 620 or snakePosition[1] < 0:
#print(snakePosition[1])
gameOver(playSurface)
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
#print(snakePosition[0],snakePosition[1])
gameOver(playSurface)
#判断是否吃掉了食物
def oreatfood(snakePosition,raspberryPosition,snakeSegments):
raspberrySpawned=1
if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
# 如果吃掉食物,则重新生成食物
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,32)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
return raspberryPosition
# 检测例如按键等pygame事件
def keydown(pygame,changeDirection,snakePosition,direction):
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
# 判断键盘事件
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
# 判断是否输入了反方向
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
# 根据方向移动蛇头的坐标
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
#print(snakePosition)
return direction,snakePosition,changeDirection
# 定义main函数
def main():
# 初始化pygame
global play_name
global fraction
play_name=input("请输入你的名字:")
pygame.init()
fpsClock = pygame.time.Clock()
# 创建pygame显示层
screen=playSurface = pygame.display.set_mode((640,640))
pygame.display.set_caption('pipixia Snake')
# 初始化变量
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
time_game=len(snakeSegments)
background = pygame.image.load('background.jpg').convert()
while True:
screen.blit(background,(0,0))
# 检测例如按键等pygame事件
direction,snakePosition,changeDirection=keydown(pygame,changeDirection,snakePosition,direction)
# 增加蛇的长度
#print(direction,snakePosition)
snakeSegments.insert(0,list(snakePosition))
time_game=(len(snakeSegments)-4)/2+4
fraction=(len(snakeSegments)-4)*100
# 判断是否吃掉了食物
raspberryPosition=oreatfood(snakePosition,raspberryPosition,snakeSegments)
# 绘制pygame显示层
#playSurface.fill(blackColour)
for position in snakeSegments:
pygame.draw.circle(playSurface,(random.randint(0,255),random.randint(0,255),random.randint(0,255)),position,10,0)
pygame.draw.circle(playSurface,redColour,raspberryPosition,10,0)
gameOverFont=pygame.font.Font(None,50)
gameOverSurf = gameOverFont.render('fraction:'+str(fraction), True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop =(320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
# 刷新pygame显示层
#screen.fill()
# 判断是否死亡
pygame.display.update()
ordie(snakePosition,snakeSegments,playSurface)
# 控制游戏速度
fpsClock.tick(time_game)
if __name__ == "__main__":
main()