我仍然是Python的新手,但我一直在使用乌龟进行游戏,你需要在特定时间范围内点击一堆圆圈来获得分数。我想创建一个高分系统,人们也可以决定他们的用户名,但我google的地方对我来说太复杂了,所以我不知道如何在我的代码中实现它。
import turtle
from random import random, randint
import time
CURSOR_SIZE = 20
score=0
while True:
diffSetting=int(input("Set the difficulty(1-5,1 being easiest and 5 being hardest): "))
if diffSetting == 1:
difficulty = 5
break
elif diffSetting == 2:
difficulty = 8
break
elif diffSetting == 3:
difficulty = 12
break
elif diffSetting == 4:
difficulty = 16
break
elif diffSetting == 5:
difficulty = 20
break
else:
print("Please choose a difficulty setting between 1 to 5.")
def addscore():
global score
score += 1
def my_circle(color):
if diffSetting==1:
radius = (50)
elif diffSetting==2:
radius = (40)
elif diffSetting==3:
radius = (30)
elif diffSetting==4:
radius = (20)
elif diffSetting==5:
radius = (10)
circle = turtle.Turtle('circle', visible=False)
circle.shapesize(radius / CURSOR_SIZE)
circle.color(color)
circle.penup()
while True:
nx = randint(2 * radius - width // 2, width // 2 - radius * 2)
ny = randint(2 * radius - height // 2, height // 2 - radius * 2)
circle.goto(nx, ny)
for other_radius, other_circle in circles:
if circle.distance(other_circle) < 2 * max(radius, other_radius):
break
else:
break
circle.showturtle()
circle.onclick(lambda x,y,t=circle: (circle.hideturtle(), addscore()))
return radius, circle
screen = turtle.Screen()
screen.bgcolor("lightgreen")
screen.title("Speed Clicker")
width, height = screen.window_width(), screen.window_height()
circles = []
gameLength = 30
startTime = time.time()
while True:
time.sleep(1/difficulty)
rgb = (random(), random(), random())
timeTaken = time.time() - startTime
circles.append(my_circle(rgb))
screen.title('SCORE: {}, TIME LEFT: {}'.format(score,int(round(gameLength - timeTaken,0))))
if time.time() - startTime > gameLength:
for turtle in screen.turtles():
turtle.reset()
break
screen.title('GG! FINAL SCORE: {}'.format(score))
screen.mainloop()
我一直在尝试将分数保存在文本文件中,但我如何保留用户名?
答案 0 :(得分:0)
您必须了解商店数据
答案 1 :(得分:0)
答案 2 :(得分:0)
我会写一个小片段,按照你的意愿扩展它。
首先,在与游戏相同的文件夹中创建名为“scoreboard.txt”的文件。 在开始游戏之前,请执行以下操作以获取详细信息。
f = open('scoreboard.txt', 'r')
name = f.readline()
high_score = int(f.readline())
f.close()
检查他们是否有高分并获得用户名(new_name):
if current_score > high_score:
f = open('scoreboard.txt', 'w')
f.write(new_name + '\n' + str(current_score))
f.close()
注意:第一次用一些随机数据填写文件,如'BOB'(按回车键),'24'。
希望它有所帮助! 评论是否有任何疑问!