I wanted to make a bot that plays Rock, Paper, Scissors with the player.
But every time I try to run the script, and type in Stein (German for rock),
the if statement doesn't detect it or doesn't take any action.
Here's my code so far:
import random
import time
print("Anfangs Buchstaben immer groß schreiben!")
time.sleep(2)
outcomes2 = ("Stein")
Runde = 0
while True:
Player = input("Deine Wahl: ")
for i in range(1):
outcomes = print(random.choice(outcomes2))
if outcomes == Player:
print("draw")
Runde + 1
continue
Issue 1
>>> outcomes2 = ("Stein")
>>> print(random.choice(outcomes2))
n
You're iterating over a string and selecting a character at random.
I'm assuming you want:
>>> outcomes2 = ("Stein", )
>>> print(random.choice(outcomes2))
Stein
Now, by specifying the ,, you're iterating over a tuple of strings (tuple of size 1). You'll end up getting "Stein" only unless you add more strings, like
outcomes2 = ("Stein", "Name2", "Name3", ...)
Issue 2
You want outcomes = random.choice(outcomes2). Do not assign the value to the print statement, because print returns None.
Putting it together...
outcomes2 = ("Stein", )
Runde = 0
while True:
Player = input("Deine Wahl: ")
outcomes = random.choice(outcomes2)
if outcomes == Player:
print("draw")
Runde + 1
continue
`import time
import random
comp_score=0
play_score=0
outcome=('rock','paper','scissor')
while True:
player = raw_input("Enter any?");
out=random.choice(outcome)
print "COMP->"+out
if out==player:
print "draw"
elif out=="rock"and player=="scissor":
comp_score+=1;
elif out=="scissor" and player=="rock":
play_score+=1;
elif out=="rock" and player=="paper":
play_score+=1;
elif out=='paper' and player=='rock':
comp_score+=1;
elif out=="scissor" and player=="paper":
play_score+=1;
elif out=='paper' and player=="scissor":
comp_score+=1;
elif player=="quit":
break;
print "GAME over"
print "PLayer score: ",play_score
print "Comp score ",comp_score`
Related
I need a help with a certain situation.
We have the following code:
import random
Genre = ["Power metal", "Melodic death metal", "Progressive metal", "Rock"]
Power_metal = ["Helloween", "Dragonforce", "Hammerfall"]
Melodic_death_metal = ["Kalmah", "Insomnium", "Ensiferum", "Wintersun"]
Progressive_metal = ["Dream theater", "Symphony X"]
Rock = ["Bon Jovi", "Nirvana"]
a = ["Pumpkins united", "Halloween"]
Helloween = set(a)
Music = input("\nSelect a music genre from available: %s:" % (Genre))
def bands(Music):
while True:
if Music == "Melodic death metal":
return (Melodic_death_metal)
elif Music == "Power metal":
return (Power_metal)
elif Music == "Progressive metal":
return (Progressive_metal)
elif Music == "Rock":
return (Rock)
else:
Music = input("\nYou entered the wrong name. Please, enter again: %s:" % (Genre))
Band = input("\nReffering to chosen genre, I have bands such as: %s. Choose a specific band and I'll suggest a random song:\n" % bands(Music))
def fate(Band):
while True:
if Band == "Helloween":
if len(Helloween) != 0:
print("Suggested song: ", Helloween.pop())
break
elif len(Helloween) == 0:
print("I don't have more songs to propose. Enjoy your music")
break
fate(Band)
while True:
next = input("\nWould you like me to suggest one more song from the band of your choice ? Answer yes or no:\n")
if next == "no":
print("Enjoy your music")
break
elif next == "yes":
fate(Band)
The problem is: when we get to the point where the program has no more songs to offer, it should print: "I don't have more songs to propose. Enjoy your music"and break. But instead of this, it goes all the way to the last loop and doesn't end until I type in the console no.
Can I make somehow the statement inside loop to end program even if I type in console yes?
Cause it will keep printing:
I don't have more songs to propose. Enjoy your music.
Would you like me to suggest one more song from the band of your choice ? Answer yes or no:
Thanks for the help.
I have pretty much finished this Rock Paper Scissors program, but one of the final steps is to add a counter to print the Win, Loss, and Tie ratio after the user is done playing.
I tried in the count_win_loss() function to enumerate the messages index that I pass to it in the play_game() function, but all it is returning zeros
import random
def count_win_loss(messages_from_result):
player_wins = 0
cpu_wins = 0
ties = 0
#This is supposed to get the index value position of this list, which
should be defined at the end of `play_game()` function.
for index in enumerate(messages_from_result):
new_index = index
#NOT WORKING NEEDS TO BE FIXED
if new_index == 0:
ties += 1
elif new_index == 1:
player_wins += 1
elif new_index == 2:
cpu_wins += 1
else:
ties += 0
player_wins += 0
cpu_wins += 0
#NOT WORKING NEEDS TO BE FIXED
print(player_wins)
print(cpu_wins)
print(ties)
#print('\nHuman Wins: %d, Computer Wins: %d, Ties: %d' % (player_wins, cpu_wins, ties))
This elif statement appears at the end of my game function. It executes when a user inputs '2' which ends the loop.
#Creates a format that can be passed to the results matrix.
#Additionally creates an index 3 that I will reference as the error value.
guesses_index = guess_dict.get(user_guess, 3)
computer_index = guess_dict.get(computer_guess)
result_index = results[guesses_index][computer_index]
final_result = result_messages[result_index]
elif play_again == '2':
count_win_loss(result_messages) #NOT WORKING NEED HELP
print('Thanks for playing!')
continue_loop = False
I pass it this messages list:
result_messages = [
"You tied!",
"You win!",
"The Computer won. :(",
"Invalid weapon, please try again."
]
As mentioned in the title, I need a win/loss counter, which I thought my calc_win_loss() would do
New_Index variable is not defined inside this function, therefore global to where ever you defining the value and get in the starting of this function
For ex:-
def a():
b = 2
def c(): . print(b) . Whenever you will call c() it will cause an error because b is a local variable
in side function a() however if you do
def a():
global b
b = 2
def c():
print(b)
Now when you call a() and then c(). Th error will go away
This is my first project, I used a lot of resources from others with the same project and this is what I have come up with. I am using Jupyter notebook. I am not getting any more error messages in my code, but for some reason I can't get it to run? Also, any advice or improvements in my code would also be appreciated.
I've tried to just call the tic_tac_toe() command but nothing comes up and I'm not sure why.
def tic_tac_toe():
brd = [None] + list(range(1,10))
end = False
winner = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9), (3,5,7))
from IPython.display import clear_output
def show_board():
print(brd[1]+'|'+brd[2]+'|'+brd[3])
print(brd[4]+'|'+brd[5]+'|'+brd[6])
print(brd[7]+'|'+brd[8]+'|'+brd[9])
print()
def player_input():
marker = ''
while marker != 'x' and marker != 'o':
marker = input('Do you want to be x or o?: ')
player1 = marker
if player1 == 'x':
player2 ='o'
else:
player2 = 'x'
player_markers = [player1,player2]
def choose_number():
while True:
try:
val = int(input())
if val in brd:
return val
else:
print('\n Please choose another number')
except ValueError:
print('\n Please choose another number')
def game_over():
for a, b, c in winner:
if brd[a] == brd[b] == brd[c]:
print("{0} wins!\n".format(board[a]))
print("Congrats\n")
return True
if 9 == sum((pos == 'x' or pos == 'o') for pos in board):
print("The game ends in a tie\n")
return True
for player in 'x' or 'o' * 9:
draw()
if is_game_over():
break
print("{0} pick your move".format(player))
brd[choose_number()] = player
print()
while True:
tac_tac_toe()
if input("Play again (y/n)\n") != "y":
break
I'm not sure why it is not running normally.
There's a couple things wrong with your code here. Your indentation for one. Also wondering why your functions are all in another function. You also create a bunch of functions but never call most of them. And have some functions that do not seem to exist. There are also a lot of logic errors here and there.
Try this instead:
# numpy is a package that has a lot of helpful functions and lets you manipulate
# numbers and arrays in many more useful ways than the standard Python list allows you to
import numpy as np
def show_board(brd):
print(brd[0]+'|'+brd[1]+'|'+brd[2])
print(brd[3]+'|'+brd[4]+'|'+brd[5])
print(brd[6]+'|'+brd[7]+'|'+brd[8])
print()
def player_input():
marker = ''
while marker != 'x' and marker != 'o':
marker = input('Do you want to be x or o?: ')
player1 = marker
if player1 == 'x':
player2 ='o'
else:
player2 = 'x'
player_markers = [player1,player2]
return player_markers
def choose_number(brd):
while True:
try:
val = int(input())
if brd[val-1] == "_":
return val
else:
print('\nNumber already taken. Please choose another number:')
except ValueError:
print('\nYou did not enter a number. Please enter a valid number:')
def is_game_over(winner, brd):
for a, b, c in winner:
if brd[a] != "_" and (brd[a] == brd[b] == brd[c]):
print("{} wins!\n".format(brd[a]))
print("Congrats\n")
return True
if 9 == sum((pos == 'x' or pos == 'o') for pos in brd):
print("The game ends in a tie\n")
return True
# I split this function in two because the "is_game_over" code was included here
# instead of being by itself.
def game_over(winner, brd, player_markers):
last = 0
# The first player is the one stored in "player_markers[0]"
player = player_markers[0]
# There are nine turns so that is what this is for. It has nothing to do with
# 'x' or 'o'. And one more turn is added for the "is_game_over" to work in
# case of a tie.
for i in range(10):
if is_game_over(winner, brd):
break
print()
print("{0} pick your move [1-9]:".format(player))
brd[choose_number(brd)-1] = player
show_board(brd)
# This is added to change from one player to another
# by checking who was the last one (look up ternary operators)
player = player_markers[1] if last==0 else player_markers[0]
last = 1 if last==0 else 0
def tic_tac_toe():
brd = ["_"] * 9
end = False
winner = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7))
winner = np.array([list(elem) for elem in winner]) - 1
player_markers = player_input()
show_board(brd)
game_over(winner, brd, player_markers)
while True:
tic_tac_toe()
if input("Play again (y/n)\n") != "y":
break
I am trying to create this game for guessing songs however it will not allow me to have over one song even after i change the range I also would like to know how to add the code to do scores for guessing the write song.
import random
for x in range(0,1):
randNum = int(random.randint(0,1))
song = open("Songs.txt", "r")
songname = str(song.readlines()[randNum])
print(songname[0])
song.close()
artist = open("Artists.txt", "r")
artistname = artist.readlines()[randNum]
print(artistname[0])
artist.close()
y = 0
songGuess = input("What is the song called?")
while(y<=2):
if songGuess == songname:
print("Answer correct!")
break
else:
y = y + 1
songguess = input("Incorrect! Try again:")
if y == 2:
print("GAME OVER")
break
You need to change your random.randint range to random.randint(0,len(song.readlines())-1), so that you are chosing a random index from all listed songs,and do the same thing with artists.
A better approach is to choose a random element from the list using random.choice .
Your for range range(0,1) will cause your loop to run just once, update the range accordingly
You can use with keyword to automatically close the file instead of explicitly closing it.
So according to above changes, the fixed code might look like
import random
num_attempts = 10
#Run loop for num_attempts times
for x in range(0, num_attempts):
songname = ''
artistname = ''
#Use with to open file
with open('Songs.txt') as song:
#Read all songs into a list
songs = song.readlines()
#Choose a random song
songname = random.choice(songs)
print(songname)
with open('Artists.txt') as artist:
# Read all artists into a list
artists = artist.readlines()
# Choose a random artist
artistname = random.choice(artists)
print(artistname)
y = 0
#Play your game
songGuess = input("What is the song called?")
while(y<=2):
if songGuess == songname:
print("Answer correct!")
break
else:
y = y + 1
songguess = input("Incorrect! Try again:")
if y == 2:
print("GAME OVER")
break
I'm new to coding, especially in python. I started learning python using codeacademy about 1 day ago and I have progressed quickly. After reaching the end of the battleship unit, it challenged me to challenge myself by seeing what I can do. So, I set out to make the game two-player. However, after finishing the program, it tells me that the column variable on the second player's ship is not defined. Why?
Here is the code:
board1 = []
board2 = []
for i in range(5):
board1.append(["O"] * 5)
board2.append(["O"] * 5)
# Creates 2 boards, one for each player to view
def printboard(board):
for row in board:
print " ".join(row)
# Prints one of the boards, depending on which player is meant to see it
def boardset1():
print "Player 1, set your coordinates!"
ship_col1 = int(raw_input("X:"))
ship_row1 = int(raw_input("Y:"))
if ship_col1 not in range(1,6) or ship_row1 not in range(1,6):
print "Invalid coordinates!"
boardset1()
else:
ship_col1 = abs(ship_col1 - 5)
ship_row1 = abs(ship_row1 - 5)
for i in range(10):
print ""
print "Coordinates set!"
def boardset2():
print "Player 2, set your coordinates!"
ship_col2 = int(raw_input("X:"))
ship_row2 = int(raw_input("Y:"))
if ship_col2 not in range(1,6) or ship_row2 not in range(1,6): #< Issue is here, I think
print "Invalid coordinates!"
boardset2()
else:
ship_col2 = abs(ship_col2 - 5) #< Might be here
ship_row2 = abs(ship_row2 - 5)
for i in range(10):
print ""
print "Coordinates set!"
# 2 above functions set coordinates based on player input
def play1():
printboard(board1)
print "Player 1: Where is the opponent's ship?"
guess_col1 = int(raw_input("X:"))
guess_row1 = int(raw_input("X:"))
if guess_col1 not in range(1,6) or guess_row1 not in range(1,6):
print "Invalid coordinates!"
play1()
else:
guess_col1 = abs(guess_col1 - 5)
guess_row1 = abs(guess_row1 - 5)
if board1[guess_col1][guess_row1] == "X":
print "You already guessed here!"
play1()
elif guess_col1 == ship_col2 and guess_row1 == ship_row2:
win = True
print "You have won!"
else:
board1[guess_col1][guess_row1] = "X"
print "You have missed!"
def play2():
if win == False:
printboard(board2)
print "Player 2: Where is the opponent's ship?"
guess_col2 = int(raw_input("X:"))
guess_row2 = int(raw_input("X:"))
if guess_col2 not in range(1,6) or guess_row2 not in range(1,6):
print "Invalid coordinates!"
play2()
else:
guess_col2 = abs(guess_col2 - 5)
guess_row2 = abs(guess_row2 - 5)
if board2[guess_col2][guess_row2] == "X":
print "You already guessed here!"
play2()
elif guess_col2 == ship_col1 and guess_row2 == ship_row1:
win = True
print "You have won!"
else:
board2[guess_col2][guess_row2] = "X"
print "You have missed!"
# Play functions are for gameplay
win = False
boardset1()
boardset2()
for i in range(25):
if win == False:
play1()
play2()
else:
break
Immediately after player 1 makes a guess, this error occurs:
Traceback (most recent call last):
File "python", line 97, in <module>
File "python", line 59, in play1
NameError: global name 'ship_col2' is not defined
Any advice or solution is welcome. The more detailed, the better, as I am still learning.
Thanks!
Your problem is that the variable ship_col2 is defined within a function. That means that it only exists until that function is done running, and then it is deleted. In order to make it available outside that function and in other functions, you must declare it as a global variable, which you can do by defining it with a default value under board1 and board2 at the top of the file. You must define all variables that you want to use in multiple functions like that.
Here is some further reading that might help you understand better: http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html