如何创建高分系统?

问题描述 投票:-1回答:1

这是python蛇游戏的代码,我试图使用搁板和泡菜没有成功……我还能尝试什么?我已经省略了“ [...]”所示的一些代码如果您想看到它的其他部分,我很乐意向您展示...

import pygame
import tkinter as tk
import random
import math
from tkinter import messagebox 


[…]

def main():
    global width, rows, s, snack
    width=500
    rows=20
    win = pygame.display.set_mode((width, width))
    s = snake ((0,255,0),(10,10))
    snack = cube(randomSnack(rows, s), color=(255,0,0))
    flag = True

    clock=pygame.time.Clock()

    while flag:
        pygame.time.delay(50)
        clock.tick(10)
        s.move()
        if s.body[0].pos == snack.pos:
            s.addCube()
            snack = cube(randomSnack(rows, s), color = (255,0,0))

        for x in range(len(s.body)):
            if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])): 
                print('Score: ', len(s.body))
                message_box('You Lost!', 'Try again')
                s.reset((10,10))
            break    

        redrawWindow(win)

    pass



main()
python tkinter
1个回答
0
投票

您可以使用JSON文件存储高分。该文件将类似于:

{
  "highscore": 7,
  "player": "alice"
}

要在python中打开JSON文件:

import json

fileContents = json.load(open("file.json", 'r'))

print(fileContents["highscore"])
#outputs "7"
print(fileContents["player"])
#outputs "alice"

print(fileContents) #will output the entire JSON data structure

要保存数据:

fileContents = {
  "highscore": 8,
  "player": "bob"
}

json.dump(fileContents, open("file.json", 'w'))

将其用于更完整的高分系统:

import json

score = 9

#open the highscore file for reading
fileContents = json.load(open("file.json", 'r'))


if score > fileContents["highscore"]:
  print("you beat the highscore of {} with a new score of {}"
    .format(fileContents["highscore"], score))

  print("Enter your name: ")
  name = input()

  #set the highscore
  fileContents["highscore"] = score
  fileContents["player"] = name

  #save the file. The indent=2 makes the file easier to read
  json.dump(fileContents, open("file.json", 'w'), indent=2)
  print("highscore saved")
© www.soinside.com 2019 - 2024. All rights reserved.