2015-05-21 5 views
-2

im, работающий над созданием действительно простой карточной игры в python для школы. Это так же просто, как две карты, одна для дилера и одна для пользователя, и тот, кто получает самую высокую карту, выигрывает в этом раунде. Каждый раунд выиграл баллы пользователей, поднявшись на 1, и когда пользователь не прошел раунд, его/ее высокие баллы записываются в .txt-файл вместе с файлом .py. Ive приходят в некоторые, что, вероятно, очень простые проблемы ... один - когда я выбираю случайную карту для дилера и пользователя и устанавливаю ее в переменную, а другой записывает счет в файле scores.txt. Спасибо за любую помощь! Это может быть немного грязно, но я больше беспокоюсь о том, что он действительно работает. Вот код:Создание простой карточной игры в python 2.7

from sys import argv # imports the opening of two separate files 
import random # imports the 'random' string 
script, filename = argv # sets two variables, one on the py file and the other on the txt file 
txt = open(filename) # opens the txt file 

# card variables assigning values 
Two = 1 
Three = 2 
Four = 3 
Five = 4 
Six = 5 
Seven = 6 
Eight = 7 
Nine = 8 
Ten = 9 
Jack = 10 
Queen = 11 
King = 12 
Ace = 13 
# chooses a random card 
score = 0 # score at game start 
def scores(): # this will print out the current high scores. 
    print "The current scores in file: %r" % filename 
    print txt.read() # prints the open txt file 

def start(): # this is sent after the scores. welcomes play to game. 
    print "Welcome %s, the computer and you will both draw a card. Whoever gets the higher card wins" % name 
    print "Try to in a row to go on the high scores!" 
    print "Good luck %s" % name 
    game() #starts the game 

def game(): # begins the actual game 
    print "The dealer draws a card..." 
    dealer = random.choice([Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace]) # gives the dealer a random card 
    print "You draw a card..." 
    user = random.choice([Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace]) # gives the user a random card 
    if dealer > user: # if dealer wins 
     print "You lose!" 
     if score > 1: # checks if score is better than 1, then writes score to txt doc 
      filename.write("\n") 
      filename.write(name "=" score) 
      filename.close() 
     else: # aren't good enough, game quits 
      print "You didn't get a score over 1, you suck and aren't going to be on high scores." 
      filename.close() 
    elif user < dealer: # if user wins 
     print "Nice! You won that round" 
     score = score + 1 # adds 1 to current score 
     game() # next round 
    else: 
     print "Um no idea what you did there, again?" 
     game() 

scores() # score def 
name = raw_input("First off let's get your name. \n >") # asks the users name for recording high scores 
start() # start def 
+0

В вашей части 'else' вы говорите:« Не понимаю, что вы там делали, снова? ». Глядя на утверждения if, когда у них есть галстук, он попадает сюда. –

+0

Сохраните результаты, открыв файл f = открыть ('scores.txt', 'w'). Затем напишите с помощью f.write ('score'). По завершении не забудьте закрыть файл f.close(). – NegativeFeedbackLoop

+0

В функции 'game' вы непосредственно писали файл ** без ** открытия. Также, когда вы делаете 'filename.write (name" = "score)', программа вызывает ошибку, потому что 'name" = "score" - три ** разных ** строки. Вам нужно добавить оператор '+' между строками. – pyUser

ответ

3

1) Открытие файла:

txt = open(filename) 

В python существует 3 типа открытия файла. Чтение, письмо и добавление. Вы определяете их «г», «W» и «а» в качестве второго аргумента открытой функции:

txt = open(filename, 'r') 

Но если вы хотите читать-писать файл, как в этой карточной игре, вы должны использовать «r +» (или «w +» и «a +»). Затем вы можете также читать-писать, а не только читать этот файл.

2) Неверный синтаксис:

filename.write(name "=" score) 

Вы должны написать:

filename.write("%s=%d" % (name, score)) 

3) 'оценка' переменной:

В функции игры возникает ошибка:

if score > 1: # checks if score is better than 1, then writes score to txt doc 
UnboundLocalError: local variable 'score' referenced before assignment 

У вас есть для установки переменной оценки в глобальную переменную (внутри игровой функции). Таким образом, сфера применения не только для самой функции игры:

global score 

4) небольшой ошибки в «игровой логике»:

В вашем случае-то еще заявлении вы делаете это:

if dealer > user: 
    ... 
elif user < dealer: 
    ... 
else 

Условие elif совпадает с условием if. Вы должны изменить его к этому:

if dealer > user: 
    ... 
elif user > dealer: 
    ... 
else 

5) Чтение файла записи:

Вы писали, например:

filename.write("\n") 

Но имя файла только строка. Вы должны использовать переменную txt, возвращаемую функцией open().

txt.write("\n") 

После всех этих изменений, код выглядит следующим образом:

from sys import argv # imports the opening of two separate files 
import random # imports the 'random' string 
script, filename = argv # sets two variables, one on the py file and the other on the txt file 
txt = open(filename, 'r+') # opens the txt file 

# card variables assigning values 
Two = 1 
Three = 2 
Four = 3 
Five = 4 
Six = 5 
Seven = 6 
Eight = 7 
Nine = 8 
Ten = 9 
Jack = 10 
Queen = 11 
King = 12 
Ace = 13 
# chooses a random card 
score = 0 # score at game start 
def scores(): # this will print out the current high scores. 
    print "The current scores in file: %r" % filename 
    print txt.read() # prints the open txt file 

def start(): # this is sent after the scores. welcomes play to game. 
    print "Welcome %s, the computer and you will both draw a card. Whoever gets the higher card wins" % name 
    print "Try to in a row to go on the high scores!" 
    print "Good luck %s" % name 
    game() #starts the game 

def game(): # begins the actual game 
    global score 
    print "The dealer draws a card..." 
    dealer = random.choice([Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace]) # gives the dealer a random card 
    print "You draw a card..." 
    user = random.choice([Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace]) # gives the user a random card 
    if dealer > user: # if dealer wins 
     print "You lose!" 
     if score > 1: # checks if score is better than 1, then writes score to txt doc 
      txt.write("\n") 
      txt.write("%s=%d" % (name, score)) 
      txt.close() 
     else: # aren't good enough, game quits 
      print "You didn't get a score over 1, you suck and aren't going to be on high scores." 
      txt.close() 
    elif user > dealer: # if user wins 
     print "Nice! You won that round" 
     score = score + 1 # adds 1 to current score 
     game() # next round 
    else: 
     print "Um no idea what you did there, again?" 
     game() 

scores() # score def 
name = raw_input("First off let's get your name. \n >") # asks the users name for recording high scores 
start() # start def 

Я надеюсь, что я могу вам помочь!

+0

Большое спасибо за эту помощь, что все работало довольно много, но иногда я столкнулся с ошибкой «IOError: [Errno 0] Error« Я чувствую, что это может быть связано с соединением игрока и дилера. – Shadex

+0

Извините, я не могу воспроизвести ошибку ... если вы ее получите снова, можете ли вы опубликовать весь текст? Может быть, это было бы полезно. Другая информация: в вашей игре, где вы используете '' 'random.choic ([Two, Three, ..., Ace])' '', вместо этого вы можете использовать '' 'random.choice (диапазон (1, 14)) '' '. '' 'range''' создает массив от 1 до 13. Поэтому вам не нужно инициализировать переменные и записывать их снова в массивы. –

0

Если вы хотите записать в файл, вы должны открыть его в режиме записи:

txt = open(filename, mode='w') 
+0

Но когда я меняю файл на запись, я не могу его прочитать в моих оценках def – Shadex

+0

Использовать mode = 'rw', тогда вы можете делать как –