the program is supposed to double the number of the player with a 75% chance and decrease by 1 with a 25% chance. If a new player receives a higher score than the last player, save the players name along with score to the file. The program exits once a player loses 5 points.
import random
points = 1
play = "yes"
name = input("what is your name?")
counter = 0
while play.lower() == "yes":
risk = random.randint(0,3)
play = input(name.upper() + "!...want to risk it to bisk it?")
if risk == 0:
points -= 1
counter += 1
if counter == 5:
break
else:
points *= 2
fi = open("score.txt", "r")
score = fi.readlines()
fi.close()
scores = int(score[0])
if (scores > points):
fi = open("score.txt","w")
fi.write(points + ":" + name)
fi.close()
print(score)
On the bottom is the text file "score.txt" which has the following:
0:No Name
you mean read the data back in as an usable int?
with open('score.txt') as F:
scores = F.readlines()
scores = [s.strip().split(':') for s in scores]
Now if you want to loop through the scores data:
for score, name in scores:
print(f"{name} scored:\t {int(score)}")
Related
I am trying to create a word guessing game in python. I can get the program to run once,
but I want it to run five times in a row keeping track of wins and losses, and this is where
I am running into issues. I have tried adding a counter and nesting the while loop but this does not seem to work. Any help or suggestions would be greatly appreciated. Thanks.
Here is the code I have written:
import random
print('Welcome to the word guessing game!')
input("What is your name? ")
print('Try to guess the word letter by letter, you have ten guesses, good luck!')
words = ['cowboy', 'alien', 'dog', 'airplane',
'trees', 'bridge', 'snake', 'snow',
'popcorn', 'apples', 'road', 'smelly',
'eagle', 'boat', 'runner']
word = random.choice(words)
print("Guess the word!")
guesses = ''
trys = 5
wins = 0
losses = 0
rounds = 0
while rounds < 5:
while trys > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end=" ")
else:
print("*")
failed += 1
if failed == 0:
print("You Win")
print("The word is: ", word)
wins = wins + 1
rounds = rounds + 1
break
print()
guess = input("Enter your letter:")
guesses += guess
if guess != word:
trys -= 1
print("Plesae try again, You have", + trys, 'more guesses')
if trys == 0:
print("You Loose, better luck next time")
losses = losses + 1
rounds = rounds + 1
print('Wins:', wins )
print('Losses:', losses)
Basically i need to make a game im python that can have a arbitrarily number of people that alternatly answers a multiplication question. But my issue is that i dont know how to keep it running until i hit 30 points. Ive tried to use dict's where the key is the player name and the value is the score. But it stops after the script only has ran once. I tried with a while loop but it went on forever. please help!
import random as r
n = int(input("Insert number of players: "))
d = {}
for i in range(n):
keys = input("Insert player name: ")
#to set the score to 0
values = 0
d[keys] = values
#to display player names
print("Player names are:")
for key in d:
print(key)
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
break
I think this will work
winner = False
while not winner :
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
winner = True
break
I want to write a program that stimulate a game as follows:
A random number between 1 and 2 is generated to determine which player
starts the game (player1 or player2).
The player who starts the game will now throw a dice repeatedly adding
the points scored in each throwing until either the player collects 20
or more points or until the player gets a 1 point score.
If the player collects 20 or more points, then the score is added to
the total points of the player and it becomes the other player's turn.
If the player gets a 1 point score before reaching 20 or more points,
then the player loses his turn without getting any points and it
becomes the other player's turn.
The other player now starts to play and plays with the same rules as
described above.
Once the second player ends his turn (either after reaching 20 or more
points or loses the his turn), then it becomes the first player's turn
and the game continues.
The first player who reaches a total score of 1000 points wins the
game.
My program works well, but are there any ways that I can solve the problem by defining only Function play without changing its parameters? Can I make Function turnPoint be a part of Function play without using any loops?
import random
def turnPoint(playerTurnPoint):
if (playerTurnPoint >= 20):
return playerTurnPoint
else:
p = random.randint(1, 6)
print(p, end = " ")
if (p == 1):
return 0
else:
playerTurnPoint += p
return turnPoint(playerTurnPoint)
def play(player1Total, player2Total, currentPlayer):
if (player1Total >= 1000):
print("Player 1 won.")
return None
elif (player2Total >= 1000):
print("Player 2 won.")
return None
else:
playerTurnPoint = 0
if (currentPlayer == 1):
print("Player 1 playing...")
print("Points obtained in this turn: ", end = " ")
playerTurnPoint = turnPoint(0)
print()
print("Turn total points = ", playerTurnPoint)
player1Total += playerTurnPoint
print("Player 1 total points = ", player1Total)
play(player1Total, player2Total, 2)
else:
print("PLayer 2 playing...")
print("Points obtained in this turn:", end = " ")
playerTurnPoint = turnPoint(0)
print()
print("Turn total points = ", playerTurnPoint)
player2Total += playerTurnPoint
print("Player 2 total points = ", player2Total)
play(player1Total, player2Total, 1)
#Main Program
player1Total = 0
player2Total = 0
currentPlayer = random.randint(1, 2)
print("Starting the Game")
print("=================")
play(player1Total, player2Total, currentPlayer)
I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')
This is my code:
Guess Song V2
import random
import time
def Game():
x = 0
#AUTHENTICATION
Username = input("What is your username?")
#Asking for an input of the password.
Password = str(input("What is the password?"))
#If password is correct then allow user to continue.
if Password == "":
print("User Authenticated")
#If not then tell the user and stop the program
elif Password != "":
print("Password Denied")
exit()
#GAME
#Creating a score variable
score=0
#Reading song names and artist from the file
read = open("Song.txt", "r")
songs = read.readlines()
songlist = []
#Removing the 'new line' code
for i in range(len(songs)):
songlist.append(songs[i].strip('\n'))
while x == 0:
#Randomly choosing a song and artist from the list
choice = random.choice(songlist)
artist, song = choice.split('-')
#Splitting the song into the first letters of each word
songs = song.split()
letters = [word[0] for word in songs]
#Loop for guessing the answer
for x in range(0,2):
print(artist, "".join(letters))
guess = str(input("Guess the song : "))
if guess == song:
if x == 0:
score = score + 3
break
if x == 1:
score = score + 1
break
#Printing score, then waiting to start loop again.
print("Your score is", score)
print("Be ready for the next one!")
score = int(score)
leaderboard = open("Score.txt", "a+")
score = str(score)
leaderboard.write(Username + ' : ' + score + '\n')
leaderboard.close()
leaderboard = open("Score.txt", "r")
#leaderboardlist = leaderboard.readlines()
Scorelist = leaderboard.readlines()
for row in Scorelist:
Username, Score = row.split(' : ')
Score = int(Score)
Score = sorted(Score)
leaderboard.close()
Game()
So this is my code, for the leaderboard feature in this game, I want to make the list (Which contain both string - Username, and Interger - Score) into descending order of score(Interger). It would look something like this:
Before:
Player1 : 34
Player2 : 98
Player3 : 22
After:
Player2 : 98
Player1 : 34
Player3 : 22
Anyone know who to do this?
scores = {}
for row in score_list:
user, score = row.split(':')
scores[user] = int(score)
highest_ranking_users = sorted(scores, key=lambda x: scores[x], reverse=True)
for user in highest_ranking_users:
print(f'{user} : {score[user]}')