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
В вашей части 'else' вы говорите:« Не понимаю, что вы там делали, снова? ». Глядя на утверждения if, когда у них есть галстук, он попадает сюда. –
Сохраните результаты, открыв файл f = открыть ('scores.txt', 'w'). Затем напишите с помощью f.write ('score'). По завершении не забудьте закрыть файл f.close(). – NegativeFeedbackLoop
В функции 'game' вы непосредственно писали файл ** без ** открытия. Также, когда вы делаете 'filename.write (name" = "score)', программа вызывает ошибку, потому что 'name" = "score" - три ** разных ** строки. Вам нужно добавить оператор '+' между строками. – pyUser