2014-11-24 3 views
1

학교 프로젝트의 경우 스코어 시스템이있는 게임을 만들고 있는데 일종의 리더 보드를 만들고 싶습니다. 일단 끝나면 선생님은 다른 학생이 게임 사본을 다운로드 할 수있는 공유 서버로 파일을 업로드하지만 불행히도 학생은 해당 서버에 저장할 수 없습니다. 가능한 경우 리더 보드가 케이크 조각이 될 것입니다. 대부분 추적 할 수있는 점수는 수백 개에 달하고 모든 컴퓨터는 인터넷에 액세스 할 수 있습니다.Python에서 오프라인 게임용 리더 보드 만들기

저는 서버 또는 호스팅에 대해 많이 알지 못하고 웹 개발에 일반적으로 사용되는 java, html 또는 다른 언어를 모르므로 다른 관련 질문이 도움이되지 않습니다. 내 게임은 득점 정보를 텍스트 파일로 인쇄하고 거기에서 모든 사람이 액세스 할 수있는 온라인 어딘가에 가져 오는 방법을 알지 못합니다.

파이썬으로 이러한 작업을 수행 할 수있는 방법이 있습니까?

여기에는 점수가 있으면 리더 보드 파일을 업데이트하기위한 코드가 있습니다 (텍스트 파일 일 것이라고 가정). 이것은 리더 보드와 스코어 파일의 복사본을 같은 장소에 가지고 있다고 가정합니다.

ABC 
3999 
: 이니셜 및 점수 (log.txt에를) -

Leaderboards 

1) JOE 10001 
2) ANA 10000 
3) JAK 8400 
4) AAA 4000 
5) ABC 3999 

이 로그 파일을 인쇄 할 것입니다 :

내 모의 리더 (Leaderboards.txt)의 형식입니다

def extract_log_info(log_file = "log.txt"): 
    with open(log_file, 'r') as log_info: 
     new_name, new_score = [i.strip('\n') for i in log_info.readlines()[:2]] 

    new_score = int(new_score) 
    return new_name, new_score 

def update_leaderboards(new_name, new_score, lb_file = "Leaderboards.txt"): 
    cur_index = None 
    with open(lb_file, 'r') as lb_info: 
     lb_lines = lb_info.readlines() 
     lb_lines_cp = list(lb_lines) # Make a copy for iterating over 
     for line in lb_lines_cp: 
      if 'Leaderboards' in line or line == '\n': 
       continue 

      # Now we're at the numbers 
      position, name, score = [ i for i in line.split() ] 

      if new_score > int(score): 
       cur_index = lb_lines.index(line) 
       cur_place = int(position.strip(')')) 
       break 

     # If you have reached the bottom of the leaderboard, and there 
     # are no scores lower than yours 
     if cur_index is None: 
      # last_place essentially gets the number of entries thus far 
      last_place = int(lb_lines[-1].split()[0].strip(')')) 
      entry = "{}) {}\t{}\n".format((last_place+1), new_name, new_score) 
      lb_lines.append(entry) 
     else: # You've found a score you've beaten 
      entry = "{}) {}\t{}\n".format(cur_place, new_name, new_score) 
      lb_lines.insert(cur_index, entry) 

      lb_lines_cp = list(lb_lines) # Make a copy for iterating over 
      for line in lb_lines_cp[cur_index+1:]: 
       position, entry_info = line.split(')', 1) 
       new_entry_info = str(int(position)+1) + ')' + entry_info 
       lb_lines[lb_lines.index(line)] = new_entry_info 

    with open(lb_file, 'w') as lb_file_o: 
     lb_file_o.writelines(lb_lines) 


if __name__ == '__main__': 
    name, score = extract_log_info() 
    update_leaderboards(name, score) 

일부 추가 정보를 원하시면 :

01,235

코드 (모두 파이썬 2.7과 3.3 일) 16,

  • 점수는 나는 단지 그들이
  • 을 완료 한 후 사용자가 실행됩니다 실행 파일을 만들 것입니다 수 있도록 미만 1 000 000
  • 이상적으로는,이 솔루션은 단지 게임에 외부 몇 가지 코드 것이다 될 것이다
  • 나는 그것이 매우 안전 소리가 나지 않는다 알 - 그렇지 않은 -하지만 괜찮아, (몽고 DB는
+2

일부 코드 붙여 넣기! –

+2

Python이이를 수행 할 수 있지만 질문에 대해보다 구체적으로 답변 해주십시오. – Garrett

+0

게임이 뱉어 낼 정보의 종류를 알 수 있도록 업데이트했습니다. 또한 모의 리더 보드가 있습니다. – JCK

답변

1

가장 쉬운 그냥 MongoDB를 또는 무언가를 사용하는 아마 hackproof 할 필요가없는 것 사전 데이터를 쉽게 저장할 수있는 nosql 형식 데이터베이스 ...)

당신은

(당신이 easy_install pymongo뿐만 아니라 pymongo해야합니다) (당신에게 충분한 공간을 제공해야합니다 taht를)이

다음 간단하게 저장할 수있는 레코드

from pymongo import MongoClient 
uri = "mongodb://test1:[email protected]:51990/joran1" 
my_db_cli = MongoClient(uri) 
db = my_db_cli.joran1 #select the database ... 

my_scores = db.scores #this will be created if it doesnt exist! 
#add a new score 
my_scores.insert({"user_name":"Leeeeroy Jenkins","score":124,"time":"11/24/2014 13:43:22"}) 
my_scores.insert({"user_name":"bob smith","score":88,"time":"11/24/2014 13:43:22"}) 
from pymongo import DESCENDING 
#get a list of high scores (from best to worst) 
print list(my_scores.find().sort("score",DESCENDING)) 

https://mongolab.com에서 무료 계정을 사용할 수 있습니다 그 자격 증명은 시스템을 테스트하고 싶다면 실제로 작동 할 것입니다. (리로이를 몇 번 추가했음을 기억하십시오)

+0

이 코드는 아마도 사용할 수있는 것처럼 보입니다. 감사합니다! 죄송합니다. 질문이 너무 많으면 저는 여전히 새로운 것입니다. – JCK

+0

완벽한 작품, 감사합니다! – JCK