Making a leaderboard which resorts itself everytime someone plays - python

I am learning python coming from C++ and HTML, after studying I decided a good way to exercise was making a simple game then slowly developing. I made it this far, but got stuck on a few things: 1. storing the "player" class and its atributes in a txt file 2. adding the new players everytime someone else with a different name plays 3. sorting the list everytime someone new is added 4. displaying the list when a keyword is input from the keyboard ( split it in small steps as i always do when coding. )
Please help and explain the steps, here is the base code:
input('Welcome to rock, paper, scissors version 1.3!(contact me for updates) Press any key to continue.')
w = 0
l = 0
t = 0
class player:
def __init__(self, name, wins, losses, ties):
self.name = name
self.wins = wins
self.losses = losses
self.ties = ties
def func1():
global w, l, t
x=input('Choose: rock, paper or scissors?')
from numpy import random
y = (random.randint(1, 3))
if (x == "scissors") or (x == "rock") or (x == "paper"):
if y == 1:
y = "scissors"
if y == 2:
y = "rock"
if y == 3:
y = "paper"
else: print("Error: you did not type your answer correctly: check so it is lowercase and spells the word correctly(as described in the question) and try again.")
if x == "rock" :
if y == "paper" :
print("computer chose " + y + " so you lost!")
l = l + 1
else:
if y == "rock" :
print("computer chose " + y + " so it is a tie!")
t = t + 1
else:
print("computer chose " + y + " so you win!")
w = w + 1
if x == "paper" :
if y == "scissors" :
print("computer chose " + y + " so you lost!")
l = l + 1
else:
if y=="paper" :
print("computer chose " + y + " so it is a tie!")
t = t + 1
else:
print("computer chose " + y + " so you win!")
w = w + 1
if x == "scissors" :
if y == "rock" :
print("computer chose " + y + " so you lost!")
l = l + 1
else:
if y == "scissors" :
print("computer chose " + y + " so it is a tie!")
t = t + 1
else:
print("computer chose " + y + " so you win!")
w = w + 1
n=input('Play again?(y/n)')
if n == "y":
n = 0
func1()
if n == "n":
print("You won " + str(w) + " times, lost " + str(l) + " times and it was a tie " + str(t) + " times.")
p1 = player(input("Please type your name:"),w,l,t)
input('Thanks for playing! Press any key to exit.')
func1()

Related

How do i properly call this function in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm a beginner in python and having some difficulties on how to call a function for a rock, paper and scissor game. The code is as below:
def game:
your = input("Rock, Paper or Scissor? ")
your.lower()
list = ["rock", "paper", "scissor"]
import random
a = random.randint(0, 2)
weapon = list[a]
if your == weapon:
print("You chose " + your + " and I chose " + weapon + " so it's a draw.")
elif your == "rock" and weapon == "paper":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "paper" and weapon == "scissor":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "scissor" and weapon == "rock":
print("You chose " + your + " and I chose " + weapon + " so I won.")
else:
print("You chose " + your + " and I chose " + weapon + " so you won.")
choice = input("Would you like to play again?(y/n) ")
if choice == "y":
game()
else:
print("Thank you for playing.")
You need brackets, like this:
def game():
to define a function. And .lower() only returns the string in lower case, it doesn't override.
your = input("Rock, Paper or Scissor? ").lower()
This is how function calls work in Python:
#Defining the function
def myFunction():
print("Hello world")
#Calling the function. Yes, it is this simple.
myFunction()
For creating functions with parameters
def myFuncWithParams(Word):
print("Hello" + Word)
myFuncWithParams("World")
Output:
Hello World
In your case:
def game():
your = input("Rock, Paper or Scissor? ")
your.lower()
list = ["rock", "paper", "scissor"]
import random
a = random.randint(0, 2)
weapon = list[a]
if your == weapon:
print("You chose " + your + " and I chose " + weapon + " so it's a draw.")
elif your == "rock" and weapon == "paper":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "paper" and weapon == "scissor":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "scissor" and weapon == "rock":
print("You chose " + your + " and I chose " + weapon + " so I won.")
else:
print("You chose " + your + " and I chose " + weapon + " so you won.")
choice = input("Would you like to play again?(y/n) ")
if choice == "y":
game()
else:
print("Thank you for playing.")
#Calling the method and staring the game
game()
All you have to do to call a function is type its name and include arguments if required.
In your case, what you have to do is
def game:
your = input("Rock, Paper or Scissor? ")
your.lower()
list = ["rock", "paper", "scissor"]
import random
a = random.randint(0, 2)
weapon = list[a]
if your == weapon:
print("You chose " + your + " and I chose " + weapon + " so it's a draw.")
elif your == "rock" and weapon == "paper":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "paper" and weapon == "scissor":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "scissor" and weapon == "rock":
print("You chose " + your + " and I chose " + weapon + " so I won.")
else:
print("You chose " + your + " and I chose " + weapon + " so you won.")
choice = input("Would you like to play again?(y/n) ")
if choice == "y":
game()
else:
print("Thank you for playing.")
# this is how you call the function
game()

Assign value to elements of a list in Python (Yahtzee game)

I am trying to build a Yahtzee game in Python.
The code works - but I have two fundamental problems:
Can't seem to make a hierarchy of scores, e.g.: Yahtzee is the best, then comes three of a kind, two pairs etc..
Can't seem to make 6's matter more than 5's and so forth..
My program looks like this:
import random
dice_sp1 = [0, 0, 0, 0]
dice_sp2 = [0, 0, 0, 0]
for x in range (4):
dice_sp1[x] = random.randint(1,6)
dice_sp2[x] = random.randint(1,6)
dice_sp1.sort()
dice_sp2.sort()
def roll():
print("Player 1, you rolled", dice_sp1)
print("Player 2, you rolled", dice_sp2)
roll()
def score_Board(user = dice_sp1, player = "Player 1"):
if dice_sp1[0] == dice_sp1[3]:
print("Gratz" + player +" - you have Yahtzee!")
elif (user[0] == user[2]) or (dice_sp1[1] == dice_sp1[3]):
print(player + " you have three of a kind")
elif (user[0] == user[1]) and (user[2] == user[3]):
print(player + " you have two pair")
elif (user[0] == user[1]) or (user[1] == user[2]) or (user[2] == user[3]):
print(player + " you have one pair",)
else:
print(player + " No match - highest value is", max(user))
score_Board()
score_Board(dice_sp2, "Player 2")
def win():
if dice_sp1[x] > dice_sp2[x]:
print("Player 1 wins")
elif dice_sp1[x] < dice_sp2[x]:
print("Player 2 wins")
else:
print("draw")
win()
You could use your score_Board function to set each players result to a variable then compare the results in your win function.
def score_Board():
if dice_sp1[0] == dice_sp1[3]:
print("Gratz" + player +" - you have Yahtzee!")
return 'Yahtzee'
elif (user[0] == user[2]) or (dice_sp1[1] == dice_sp1[3]):
print(player + " you have three of a kind")
return 'three of a kind'
elif (user[0] == user[1]) and (user[2] == user[3]):
print(player + " you have two pair")
return 'two pair'
elif (user[0] == user[1]) or (user[1] == user[2]) or (user[2] == user[3]):
print(player + " you have one pair",)
return 'one pair'
else:
print(player + " No match - highest value is", max(user))
return max(user)
sp1 = score_Board()
sp2 = score_Board(dice_sp2, "Player 2")
...
win(sp1, sp2)

Python SyntaxError: invalid syntax [elif my_move == 'rock']

I'm developing a rock paper scissors on python and I'm getting this syntax error
any help is appreciated
class Player:
def move(self):
return 'rock'
def learn(self, my_move, their_move):
self.my_move = my_move
self.their_move = their_movee here
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def play_round(self):
move1 = input("Pick something!\n")
move2 = self.p2.move()
print(f"Player 1: {move1} Player 2: {move2}")
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
my_score = 0
computer_score = 0
if beats(move1, move2):
my_score = my_score + 1
print ("You win")
print ("Human score = " + str(my_score) + " " + "Computer score = " + str(computer_score) )
elif beats(move2,move1):
computer_score = computer_score + 1
print ("Computer wins")
print ("Human score = " + str(my_score) + " " + "Computer score = " + str(computer_score) )
else:
print ("Draw")
print ("Human score = " + str(my_score) + " " + "Computer score = " + str(computer_score) )
def play_game(self):
print("Game start!")
for round in range(3):
print(f"Round {round}:")
self.play_round()
print("Game over!")
class cycleplayer(Player):
def move(self):
if round == 0 :
return 'rock'
elif self.my_move == 'rock'
return "paper"
elif self.my_move == 'paper'
return "scissors"
else self.my_move == 'scissors'
return "rock"
on the cycleplayer subclass I want the program to take the previous move and use it in the current round
I get an error on the first elif in the subclass cycleplayer
the error points on "rock"
invalid syntax ()
In addition to the missing colons after your elif's and the disallowed condition following else, this might have an issue because of the white space. Be sure to indent the member functions within your classes!

Questions about a tic-tac-toe program I am writing

I am making a tic-tac-toe program in python.
I have two questions:
How to create a trick to terminate the move() when we have created a diagonal or a line(xxx or OOO) in the game.
In my program some error is occurring::in line 28::(UnboundLocalError: local variable 'stop' referenced before assignment)
My code is::
import random
board = {"top-l":" ","top-m":" ","top-r":" ","mid-l":" ","mid-m":" ","mid-r":" ","low-l":" ","low-m":" ","low-r":" "}
def print_board(board):
print( board["top-l"] + "|" + board["top-m"] + "|" + board["top-r"])
print("--------")
print( board["mid-l"] + "|" + board["mid-m"] + "|" + board["mid-r"])
print("--------")
print( board["low-l"] + "|" + board["low-m"] + "|" + board["low-r"])
if random.randint(0,1) == 1:
turn = "X"#user
else:
turn = "O"# computer
def instructions():
print("TYPE top FOR TOP ROW, mid FOR MIDDLE ROW AND low FOR LOWEST ROW")
print(" ")
print("TYPE -l FOR LEFT CORNER, -m FOR MIDDLE CORNER AND -r FOR RIGHT CORNER")
print(" ")
print("SO COMMAND FOR TOP RIGHT CORNER SHOULD BE top-r ")
print("AN EMPTY BOARD LOOKS LIKE::")
print_board(board)
def move():
for i in range(10):
print_board(board)
print("CHANCE NO. " + str(i))
if turn == "O":
if i == 1:
print("COMPUTER WILL TAKE THE FIRST TURN(FOR " + turn + ")")
else:
print("IT'S COMPUTER TURN NOW")
y = random.randint(0,9)
move = str(board_list[y])
elif turn == "x":
if i == 1:
print("USER WILL TAKE THE FIRST TURN(FOR " + turn + "). PLEASE ENTER YOUR MOVE")
else:
print("IT'S USERS TURN NOW. PLEASE ENTER YOUR MOVE")
move = input()
print("STEP TAKEN IS ::" + move)
board["move"] = turn
if turn == "x":
tu = 0
turn = "O"
elif turn == "O":
tu = 1
turn = "X"
if board["top-l"] == board["top-m"] == board["top-r"] or board["mid-l"] == board["mid-m"] == board["mid-r"] or board["low-l"] == board["low-m"] == board["low-r"] or board["mid-l"] == board["top-l"] == board["low-l"] or board["mid-m"] == board["top-m"] == board["low-m"] or board["mid-r"] == board["top-r"] == board["low-r"] or board["top-l"] == board["mid-m"] == board["low-r"] or board["top-r"] == board["mid-m"] == board["low-l"]:
stop = 1
else:
stop = 0
if __name__ == "__main__":
board_list = list(board.keys())
tu = int(0)# 0 for computer
# 1 for user
stop = int(0)# 0 = continue
print("PRESENTING YOU TIC-TAC-TOE GAME v1.0 BY DK SHARAMA")
print("PLEASE ENTER YOUR NAME::")
user = str(input())
print("WELCOME " + user)
instructions()
print("TO PLAY PRESS 1 ELSE 0")
play = int(input())
if play == 1:
move()
if stop == 1:
print("GAME OVER")
if tu == 0:
print("COMPUTER WON")
elif tu == 1:
print("USER WON")
elif stop == 0:
print("IT'S A TIE :: NO ONE WON")

Win Count and Loop Help (Python 3)

I found a basic rock-paper-scissors game and wanted to know how to create a score table for it. Also, I'm confused how to make the game last forever until the player wants to end it. Here is the coding for the game:
import random;
wins_history = [0]
ties_history = [0]
losses_history = [0]
def initial_wins():
return wins_history[0]
def cur_wins():
return wins_history[-1]
def affect_wins(delta):
wins_history.append(cur_wins() + delta)
return cur_wins()
def initial_ties():
return ties_history[0]
def cur_ties():
return ties_history[-1]
def affect_ties(delta):
ties_history.append(cur_ties() + delta)
return cur_ties()
def initial_losses():
return losses_history[0]
def cur_losses():
return losses_history[-1]
def affect_losses(delta):
losses_history.append(cur_losses() + delta)
return cur_losses()
while True:
player = input("Enter your choice (rock/paper/scissors): ");
player = player.lower();
while (player != "rock" and player != "paper" and player != "scissors"):
print(player);
player = input("That choice is not valid. Enter your choice (rock/paper/scissors): ");
player = player.lower();
computerInt = random.randint(0,2);
if (computerInt == 0):
computer = "rock";
elif (computerInt == 1):
computer = "paper";
elif (computerInt == 2):
computer = "scissors";
else:
computer = "Huh? Error...";
if (player == computer):
print("Draw!");
affect_ties(+1)
print ("Your new tie score is, cur_ties()")
elif (player == "rock"):
if (computer == "paper"):
print("Computer wins!");
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
else:
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")
elif (player == "paper"):
if (computer == "rock"):
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")
else:
print("Computer wins!")
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
elif (player == "scissors"):
if (computer == "rock"):
print("Computer wins!");
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
else:
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")

Categories

Resources