Essence of this code is to depict Rock, Paper and Scissors game using Python language basically with for loop and if...else statements. I used PyScripter to run the code on Python 3.7.2 as engine. The def main() and if __name__ == '__main__' are PyScripter codes for running the machine
import random
def main():
pass
if __name__ == '__main__':
main()
tie_sum, comp_sum, human_sum = 0, 0, 0
name = input('Enter your firstname here: ')
for i in range(5):
tie_sum += tie_sum
comp_sum += comp_sum
human_sum += human_sum
comp_guess = random.randint(1, 3)
print(f'The computer guess option is {comp_guess}')
human_guess = int(input('Enter 1 as (rock), 2 as (paper) or 3 as (scissors):'))
if comp_guess == 1 and human_guess == 3:
comp_sum += 1
elif comp_guess == 1 and human_guess is 2:
human_sum += 1
elif comp_guess == 2 and human_guess == 3:
human_sum += 1
elif comp_guess == 3 and human_guess == 1:
human_sum += 1
elif comp_guess == 3 and human_guess == 2:
comp_sum += 1
elif comp_guess == 2 and human_guess == 1:
comp_sum += 1
else:
tie_sum += 1
print(f'The number of tie in this game is {tie_sum}')
if comp_sum > human_sum:
print('The winner of this game is the Computer.')
print(f'The comp_sum is {comp_sum}')
elif comp_sum < human_sum:
print(f'The winner of this game is {name}.')
print(f'The human sum is {human_sum}')
else:
print('This game ends in tie.')
print(f'The tie sum is {tie_sum}')
The reason for that is the first three lines in the for loop. You are increasing the sum of computer, human and tie while checking the condition and when you the loop iterates again, it sums up again. Here's the modified code:
import random
def main():
pass
if __name__ == '__main__':
main()
tie_sum, comp_sum, human_sum = 0, 0, 0
name = input('Enter your firstname here: ')
for i in range(5):
comp_guess = random.randint(1, 3)
human_guess = int(input('Enter 1 as (rock), 2 as (paper) or 3 as (scissors):'))
print(f'The computer guess option is {comp_guess}')
if comp_guess == 1 and human_guess == 3:
comp_sum += 1
elif comp_guess == 1 and human_guess == 2:
human_sum += 1
elif comp_guess == 2 and human_guess == 3:
human_sum += 1
elif comp_guess == 3 and human_guess == 1:
human_sum += 1
elif comp_guess == 3 and human_guess == 2:
comp_sum += 1
elif comp_guess == 2 and human_guess == 1:
comp_sum += 1
else:
tie_sum += 1
print(f'The number of tie in this game is {tie_sum}')
if comp_sum > human_sum:
print('The winner of this game is the Computer.')
print(f'The comp_sum is {comp_sum}')
elif comp_sum < human_sum:
print(f'The winner of this game is {name}.')
print(f'The human sum is {human_sum}')
else:
print('This game ends in tie.')
print(f'The tie sum is {tie_sum}')
Also, there was another modification, the computer guess is supposed to be printed after human's guess. I fixed that too. Hope that helps.
Related
So I'm trying to make a game in python where you register players at the start and then can play games of odd or even. I wanted a system where the game would loop over for each player and once ever player within the list has been gone through it opens the menu again.
There is a list named players and the following code just results in an endless loop around the first player. I've tried a few different loops such as a for loop and variants of the while loop but none of them are able to do what I want them to.
This is the code that I have:
class OddOrEven(Game):
def oddoreven():
index = 0
print("Hey", players[index], "Odd (o) or Even (e)?")
choice = input('> \u001b[1m')
print('\u001b[0m', end='')
randomdice = d.roll()
while index < len(players):
while choice != "o" or choice != "e":
if choice == "o" and randomdice == 1 or randomdice == 3 or randomdice == 5:
print("Congratulations,", players[index], "You win!")
print()
elif choice == "o" and randomdice == 2 or randomdice == 4 or randomdice == 6:
print("Sorry,", players[index], "You lose!")
print()
elif choice == "e" and randomdice == 2 or randomdice == 4 or randomdice == 6:
print("Congratulations,", players[index], "You win!")
print()
elif choice == "e" and randomdice == 1 or randomdice == 3 or randomdice == 5:
print("Sorry,", players[index], "You lose!")
print()
else:
print("Invalid choice.")
choice = input('> \u001b[1m')
print('\u001b[0m', end='')
index += 1
So I ended up fixing it with some tweaking of the code, turns out I had forgotten to add a loop around where the next player would be asked the question so this is what I now have that is working.
index = 0
for index in range(len(players)):
print("Hey", players[index], "Odd (o) or Even (e)?")
choice = input('> \u001b[1m')
print('\u001b[0m', end='')
power = p.getPower()
randomdice = d.roll()
# If statement that checks what the power is and adds the value to the random dice so that the new dice can be printed
if power == 1:
randomdice + 1
elif power == 2:
randomdice + 2
elif power == 3:
randomdice + 3
elif power == 4:
randomdice + 4
elif power == 5:
randomdice + 5
if randomdice == 1:
print (dice[0])
elif randomdice == 2:
print (dice[1])
elif randomdice == 3:
print (dice[2])
elif randomdice == 4:
print (dice[3])
elif randomdice == 5:
print (dice[4])
elif randomdice == 6:
print (dice[5])
while index < len(players):
if choice == "o" and randomdice == 1 or randomdice == 3 or randomdice == 5:
print("Congratulations,", players[index], "You win!")
print()
break
elif choice == "o" and randomdice == 2 or randomdice == 4 or randomdice == 6:
print("Sorry,", players[index], "You lose!")
print()
break
elif choice == "e" and randomdice == 2 or randomdice == 4 or randomdice == 6:
print("Congratulations,", players[index], "You win!")
print()
break
elif choice == "e" and randomdice == 1 or randomdice == 3 or randomdice == 5:
print("Sorry,", players[index], "You lose!")
print()
break
else:
print("Invalid choice.")
print("Odd (o) or Even (e)?")
choice = input('> \u001b[1m')
print('\u001b[0m', end='')
index += 1
I'm creating a program which I have to put a number and when I run the program, the solution should be the day for that number. But I don't know how to do. The program I did was this:
num = 4
if(num = 1)
print('Monday')
elif(num = 2)
print('Tuesday')
elif(num = 3)
print('Wednesday')
elif(num = 4)
print('Thursday')
elif(num = 5)
print('Friday')
elif(num = 6)
print('Sunday')
elif(num = 7)
print('Saturday')
elif(num < 1)
print('Put a number between 1 and 7')
else(num > 7)
print('Put a number between 1 and 7')
In python, for statements like if, for, etc. You have to add : at the end of it.
And for comparing (for equal) you have to use == and not =
num = 4
if(num == 1):
print('Monday')
elif num == 2:
print('Tuesday')
.....
You can compare without parenthesis and it will work too.
num = 0
while num <= 7:
num += 1
if num == 1:
print('Monday')
elif num == 2:
print('Tuesday')
elif num == 3:
print('Wednesday')
elif num == 4:
print('Thursday')
elif num == 5:
print('Friday')
elif num == 6:
print('Saturday')
elif num == 7:
print('Sunday')
so the ultimate goal is to run best 2 out of 3 games of rock, paper, scissors, lizard, spock. i haven't added a loop yet or anything like that i'm trying to get the game itself running first but I'm coming across a NameError, it's saying the 'result' variable is undefined.
I've tried returning it but that doesn't appear to be working, but I also maybe don't know what I'm doing?
def number_to_name(number):
if number == 1:
return 'scissors'
elif number == 2:
return 'rock'
elif number == 3:
return 'paper'
elif number == 4:
return 'lizard'
elif number == 5:
return 'spock'
else:
print ("Error: Invalid number")
def name_to_number(name):
if name == 'scissors':
return 1
elif name == 'rock':
return 2
elif name == 'paper':
return 3
elif name == 'lizard':
return 4
elif name == 'spock':
return 5
else:
print ("Error: Invalid number")
def rpsls(name):
player_score, computer_score = (0, 0)
player_input = name_to_number(name)
computer_input = random.randint(1,5)
result = (player_input - computer_input) % 5
if result == 1 or result == 2:
print("player wins")
player_score += 1
print("Player {}, Computer {}". format(player_score, computer_score))
elif result == 3 or result == 4:
game = "computer wins"
computer_score += 1
print("Player {}, Computer {}". format(player_score, computer_score))
elif result == 0:
game = "it's a tie"
print("Player {}, Computer {}". format(player_score, computer_score))
else:
print("error")
rpsls("rock")
rpsls("spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
Your conditions should be inside the rpsls function.Because you result variable is local variable. You can't fetch this variable globally.
> def rpsls(name):
> player_score, computer_score = (0, 0)
> player_input = name_to_number(name)
> computer_input = random.randint(1, 5)
> result = (player_input - computer_input) % 5
>
>
> if result == 1 or result == 2:
> print("player wins")
> player_score += 1
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> elif result == 3 or result == 4:
> game = "computer wins"
> computer_score += 1
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> elif result == 0:
> game = "it's a tie"
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> else:
> print("error")
Your variable result is inside the function rpsls. So the scope of result lies to the function only.
A easy solution would be assign a 0 value to result before the function 'rpsls'
This way your updating a globally defined variable inside the function.
result = 0
def rpsls(name):
#Your code
The best way would be to write a class, have a class level variable result, and put all this code into the class.
First of all, since result is only defined in the function, it is only accessable inside that specific function, unless you choose to use the global method, which I wouldn't recommend.
Second, since you called result before you called the function that actually defines result, even if you use global, it will still not be defined for that specific line.
I want it to print a message and change some values when the mario.location values are equal to the coin.location values in python. Why isn't it doing that? It is just printing the regular input. Which is just printing the location values.
class mario:
x_location = 0
y_location = 0
z_location = 0
health = 3
class coin:
x = 1
y = 0
z = 1
rules = [mario.x_location == coin.x,
mario.y_location == coin.y,
mario.z_location == coin.z]
start = input('say yes: ').lower()
while start == 'yes':
command = input('').lower()
if command == 'w':
mario.x_location += 1
print(mario.x_location, mario.y_location, mario.z_location)
elif command == 's':
mario.x_location -= 1
print(mario.x_location, mario.y_location, mario.z_location)
elif command == 'a':
mario.z_location -= 1
print(mario.x_location, mario.y_location, mario.z_location)
elif command == 'd':
mario.z_location += 1
print(mario.x_location, mario.y_location, mario.z_location)
elif all(rules):
if mario.health == 3:
print('you collected a coin')
print('health: ', mario.health)
elif mario.health < 3:
print('You collected a coin and healed')
mario.health += 1
print('Health: ', mario.health)
You are only comparing the values one single time before even starting the while loop. You should be comparing the values every iteration, after a command is chosen.
while start == 'yes':
command = input('').lower()
if command == 'w':
mario.x_location += 1
print(mario.x_location, mario.y_location, mario.z_location)
elif command == 's':
mario.x_location -= 1
print(mario.x_location, mario.y_location, mario.z_location)
elif command == 'a':
mario.z_location -= 1
print(mario.x_location, mario.y_location, mario.z_location)
elif command == 'd':
mario.z_location += 1
print(mario.x_location, mario.y_location, mario.z_location)
rules = [mario.x_location == coin.x,
mario.y_location == coin.y,
mario.z_location == coin.z]
if all(rules):
if mario.health == 3:
print('you collected a coin')
print('health: ', mario.health)
elif mario.health < 3:
print('You collected a coin and healed')
mario.health += 1
print('Health: ', mario.health)
Sample run:
say yes: yes
w
1 0 0
a
1 0 -1
d
1 0 0
d
1 0 1
you collected a coin
health: 3
Okay I'm not sure how to develop another board with hidden spaces for the computers ships per-se, and have it test for hits. Again I'm not even sure how I'm going to test for hits on the board I have now. Make note: The player turn function will be migrated to the computer board since you wouldn't be attacking your own ships. Here is the code. It may not be the best formatting (as in with Methods and objects and such) but I can polish it up a little later. Also would there be another way to make placing the ships all in one function? Or with the way I have it, will it have to stay that way?
class battleship(object):
def __init__(self):
self.board = [["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ]
self.printboard()
self.placeAircraftCarrier()
self.placeBattleShip()
self.placeSubmarine()
self.placeDestroyer()
self.placePatrolBoat()
for i in range(100):
self.playerTurn()
def printboard(self):
print "Game Board\n"
print "1","2","3","4","5","6","7","8","9","10"
for row in self.board:
print "|".join(row)
def placeBattleShip(self):
while True:
self.vOrHPlacement = input("Would you like to place the Battleship (1) Vertically or (2)Horizontally?:")
if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:
break
else:
print "You must press 1 or 2."
while True:
self.battleshipRow = input("With the head as the starting place what row would you like to place the Battleship (Takes 4 Spaces)?:")
self.battleshipCol = input("What column would you like to start the BattleShip at?:")
if self.vOrHPlacement == 1:
if self.battleshipRow > 7 or self.battleshipRow <= 0:
print "\nIf placing vertically you can only choose 1-7 for the row."
elif self.battleshipCol <= 0 or self.battleshipCol > 10:
print "You must choose 1 - 10 for a column."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 2
self.battleshipCol -= 1
for i in range(4):
self.board[self.battleshipRow + 1][self.battleshipCol] = "X"
self.battleshipRow += 1
break
elif self.vOrHPlacement == 2:
if self.battleshipCol > 7 or self.battleshipCol <= 0:
print "\nIf placing horizontally you can only choose 1-7 for a column."
elif self.battleshipRow <= 0 or self.battleshipRow > 10:
print "\n You must choose 1 - 10 as a row choice."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 1
self.battleshipCol -= 2
for i in range(4):
self.board[self.battleshipRow][self.battleshipCol + 1] = "X"
self.battleshipCol += 1
break
self.printboard()
def placeAircraftCarrier(self):
while True:
self.vOrHPlacement = input("Would you like to place the Aircraft Carrier (1) Vertically or (2)Horizontally?:")
if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:
break
else:
print "You must press 1 or 2."
while True:
self.battleshipRow = input("With the head as the starting place what row would you like to place the Aircraft Carrier (Takes 5 Spaces)?:")
self.battleshipCol = input("What column would you like to start the Aircraft Carrier at?:")
if self.vOrHPlacement == 1:
if self.battleshipRow > 6 or self.battleshipRow <= 0:
print "\nIf placing vertically you can only choose 1-6 for the row."
elif self.battleshipCol <= 0 or self.battleshipCol > 10:
print "You must choose 1 - 10 for a column."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 2
self.battleshipCol -= 1
for i in range(5):
self.board[self.battleshipRow + 1][self.battleshipCol] = "X"
self.battleshipRow += 1
break
elif self.vOrHPlacement == 2:
if self.battleshipCol > 6 or self.battleshipCol <= 0:
print "\nIf placing horizontally you can only choose 1-6 for a column."
elif self.battleshipRow <= 0 or self.battleshipRow > 10:
print "\n You must choose 1 - 10 as a row choice."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 1
self.battleshipCol -= 2
for i in range(5):
self.board[self.battleshipRow][self.battleshipCol + 1] = "X"
self.battleshipCol += 1
break
self.printboard()
def placeSubmarine(self):
while True:
self.vOrHPlacement = input("Would you like to place the Submarine (1) Vertically or (2)Horizontally?:")
if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:
break
else:
print "You must press 1 or 2."
while True:
self.battleshipRow = input("With the head as the starting place what row would you like to place the Submarine (Takes 3 Spaces)?:")
self.battleshipCol = input("What column would you like to start the Submarine at?:")
if self.vOrHPlacement == 1:
if self.battleshipRow > 8 or self.battleshipRow <= 0:
print "\nIf placing vertically you can only choose 1-8 for the row."
elif self.battleshipCol <= 0 or self.battleshipCol > 10:
print "You must choose 1 - 10 for a column."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 2
self.battleshipCol -= 1
for i in range(3):
self.board[self.battleshipRow + 1][self.battleshipCol] = "X"
self.battleshipRow += 1
break
elif self.vOrHPlacement == 2:
if self.battleshipCol > 8 or self.battleshipCol <= 0:
print "\nIf placing horizontally you can only choose 1-8 for a column."
elif self.battleshipRow <= 0 or self.battleshipRow > 10:
print "\n You must choose 1 - 10 as a row choice."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 1
self.battleshipCol -= 2
for i in range(3):
self.board[self.battleshipRow][self.battleshipCol + 1] = "X"
self.battleshipCol += 1
break
self.printboard()
def placeDestroyer(self):
while True:
self.vOrHPlacement = input("Would you like to place the Destroyer (1) Vertically or (2)Horizontally?:")
if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:
break
else:
print "You must press 1 or 2."
while True:
self.battleshipRow = input("With the head as the starting place what row would you like to place the Destroyer (Takes 3 Spaces)?:")
self.battleshipCol = input("What column would you like to start the Destroyer at?:")
if self.vOrHPlacement == 1:
if self.battleshipRow > 8 or self.battleshipRow <= 0:
print "\nIf placing vertically you can only choose 1-8 for the row."
elif self.battleshipCol <= 0 or self.battleshipCol > 10:
print "You must choose 1 - 10 for a column."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 2
self.battleshipCol -= 1
for i in range(3):
self.board[self.battleshipRow + 1][self.battleshipCol] = "X"
self.battleshipRow += 1
break
elif self.vOrHPlacement == 2:
if self.battleshipCol > 8 or self.battleshipCol <= 0:
print "\nIf placing horizontally you can only choose 1-8 for a column."
elif self.battleshipRow <= 0 or self.battleshipRow > 10:
print "\n You must choose 1 - 10 as a row choice."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 1
self.battleshipCol -= 2
for i in range(3):
self.board[self.battleshipRow][self.battleshipCol + 1] = "X"
self.battleshipCol += 1
break
self.printboard()
def placePatrolBoat(self):
while True:
self.vOrHPlacement = input("Would you like to place the Patrol Boat (1) Vertically or (2)Horizontally?:")
if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:
break
else:
print "You must press 1 or 2."
while True:
self.battleshipRow = input("With the head as the starting place what row would you like to place the Patrol Boat (Takes 2 Spaces)?:")
self.battleshipCol = input("What column would you like to start the Patrol Boat at?:")
if self.vOrHPlacement == 1:
if self.battleshipRow > 9 or self.battleshipRow <= 0:
print "\nIf placing vertically you can only choose 1-9 for the row."
elif self.battleshipCol <= 0 or self.battleshipCol > 10:
print "You must choose 1 - 10 for a column."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 2
self.battleshipCol -= 1
for i in range(2):
self.board[self.battleshipRow + 1][self.battleshipCol] = "X"
self.battleshipRow += 1
break
elif self.vOrHPlacement == 2:
if self.battleshipCol > 9 or self.battleshipCol <= 0:
print "\nIf placing horizontally you can only choose 1-9 for a column."
elif self.battleshipRow <= 0 or self.battleshipRow > 10:
print "\n You must choose 1 - 10 as a row choice."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 1
self.battleshipCol -= 2
for i in range(2):
self.board[self.battleshipRow][self.battleshipCol + 1] = "X"
self.battleshipCol += 1
break
self.printboard()
def playerTurn(self):
while True:
self.row = input("What row coordinate would you like to hit?:")
self.column = input("What column coordinate would you like to hit?")
if self.row > 10 or self.row < 0:
print "You must pick a row coordinate between 1 and 10."
elif self.column > 10 or self.column < 0:
print "You must pick a column coordinate between 1 and 10."
elif self.board[self.row - 1][self.column - 1] == "*":
print "You have already hit there."
else:
self.board[self.row - 1][self.column - 1] = "*"
break
self.printboard()
b = battleship()
You need a lot of code organisation. I would suggest keeping Classes free from any sort of looping or inputs! Input stuff from the user & then add that to the class instance, not the other way round. Organize your code & add documentation to it so that others can help you.
You can do some stuff like this
class BattleShip:
""" Ship object container"""
def __init__(self, position_x, position_y, size):
""" Necessary variables for the ship go here """
self.position_x = position_x
self.position_y = position_y
self.size = size
def contains(self, position_x, position_y):
""" Returns true if supplied point lies inside this ship """
# code
def destroy(self, position_x, position_y):
""" Destroys the ship's point supplied if it contains it """
assert self.contains(position_x, position_y)
# Now update the gameboard
# code
def isCompletelyDestroyed(self):
""" Returns True if ship is completely destoryed else False """
# code
class GameBoard:
""" The container for the ships """
def __init__(self, size):
"""Initialize clean GameBoard depending on size, etc """
self.occupied = "+" # representation for ships
self.destroyed = 'x' # representation for destroyed area
self.clear = '-' # representation for clear water
def printBoard(self):
""" Print the current gameboard state """
def update(self, ship):
""" Updates the gameboard according to updated ship """
# Now do the mainloop
while game_not_over:
# run game