Basic python coding

Hello,

if anyone can please help me with this basic python coding style please. The code is accepting an invalid input.
There are PEP8 errors. And its mainly the style of the coding. If I put my code into here: http://pep8online.com/ there are too many errors. The file name is rps.py i have a zip file of it but not sure if I can upload it in here.

This is what is required:
The code style follows the standard Python style guide.

The pycodestyle tool should report zero errors and zero warnings.

If the program is called rps.py, the command to test it is pycodestyle rps.py.
The program does not crash or display any error messages.
The program checks the validity of user input.

The game should not crash, and it should not treat invalid input as a valid move.
If the player enters a move that is not valid, the game should give them the chance to retry that move until they enter a valid move.

The game should not crash, and it should not treat invalid input as a valid move.
Example:
If the player enters “roxk” instead of “rock”, the game should let them try again; it should not crash, and it should not assume they meant “rock”.

#The code should prompt the user on entering a new input.
The code should be thoroughly tested.

Invalid moves should not make the program crash.

This is my code:

"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""

import random

moves = ['rock', 'paper', 'scissors']

"""The Player class is the parent class for all of the Players
in this game"""

class Player():

def __init__(self):
self.score = 0

def move(self):
return moves[0]
def learn(self, learn_move):
pass

class RandomPlayer(Player):
def move(self):
throw = random.choice(moves)
return (throw)

class ReflectPlayer(Player):

def __init__(self):
Player.__init__(self)
self.learn_move = None

def move(self):
if self.learn_move is None:
throw = moves[0]
else:
throw = self.learn_move
return (throw)

def learn(self, learn_move):

self.learn_move = learn_move

class Cycles(Player):

def __init__(self):

Player.__init__(self)
self.step = 0

def move(self):
throw = None
if self.step == 0:
throw = moves[0]
self.step = self.step + 1
elif self.step == 1:
throw = moves[1]
self.step = self.step + 1
else:
throw = moves[2]
self.step = self.step + 1
return throw

class HumanPlayer(Player):

def move(self):

throw = input('rock, paper, scissors?')
while throw != 'rock'and throw != 'paper'and throw != 'scissors':
print('Please try again')
throw = input('rock, paper, scissors?')
return (throw)

class Game():

def __init__(self, p2):
self.p1 = HumanPlayer()
self.p2 = p2

def play_game(self):
print("Rock Paper Scissors, GO! START! GO!")
for round in range(3):
print (f"Round {round}:")
self.play_round()
if self.p1.score > self.p2.score:
print('Player 1 won!')
elif self.p1.score < self.p2.score:
print('Player1 2 won!')
else:
print('Your game was a draw!')
print('The FINAL score ' + str(self.p1.score) + ' TO ' +
str(self.p2.score))

def play_single(self):
print("Rock Paper Scissors, Go!")
print (f"Round 1 of 1:")
self.play_round()
if self.p1.score > self.p2.score:
print('Player 1 won!')
elif self.p1.score < self.p2.score:
print('Player 2 won!')
else:
print('Your game was a draw!')
print('The final score ' + str(self.p1.score) + ' TO ' +
str(self.p2.score))

def play_round(self):
move1 = self.p1.move()
move2 = self.p2.move()
result = Game.play(move1, move2)
self.p1.learn(move2)
self.p2.learn(move1)

def play(self, move1, move2):
print(f"You played {move1}")
print(f"Opponent played {move2}")
if beats(move1, move2):
print ("PLAYER ONE WINS!")
print(f"Score: Player 1: {move1} Player 2: {move2}\n\n")
self.p1.score += 1
return 1
elif beats(move2, move1):
print ("PLAYER TWO WINS!")
print(f"Score: Player 1: {move1} Player 2: {move2}\n\n")
self.p2.score += 1
return 2
else:
print ("IT IS A DRAWBREAKER!!!")
print(f"Score: Player 1: {move1} Player 2: {move2}\n\n")
return 0

def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
if __name__ == '__main__':
answer = [Player(), RandomPlayer(), Cycles(), ReflectPlayer()]
p2 = input('The Rock Paper Scissors Game begins! Please type: 1, 2, 3, or 4 Alright, LETS PLAY: [1]Rock, [2]Paper,\
[3]Scissors, or [4]Blah:')

while p2 != 1 or p2 != 2 or p2 != 3 or p2 != 4:
p2 = random.choice(answer)
break

if p2 == '1':
p2 = Player()
elif p2 == '2':
p2 = RandomPlayer()
elif p2 == '3':
p2 = blah()
elif p2 == '4':
p2 = ReflectPlayer()

rounds = input('Do you want a [S]ingle or a completely [F]ull game? Please type the letter [S] or [F] to continue:')
Game = Game(p2)
while True:
if rounds == 's':
Game.play_single()
break

elif rounds == 'f':
Game.play_game()
break

else:
print('Can you try again please?')
rounds = input('Enter 1 for a single\
game and 2 for a full game:')

Moderator edit to format code made on 11/20/2019.

1 Like

You seem to have a couple of different questions. Is your question about your coding style, or about the functionality of your program? In either case, it’s very difficult to tell what’s going on with unformatted code within your posting. If you wouldn’t mind editing your question to format your code, it will be easier to see what’s going on. See How do I format code in my posts?

4 Likes

Hello, @code3145024129. I formatted your code to appear in your post as code with your original indentation, white space, blank lines, etc. intact. Please refer to the link in @chuckwondo’s post for future reference when posting code. Now that we see your code it is immediately obvious that not only will it not pass the PEP8 requirements, it won’t execute since there is no indentation whatsoever. I don’t know if the indentation was somehow lost when you copied/pasted it here, or if it wasn’t indented to begin with. In either case, we cannot test is without it being properly indented first. If you have a version that is properly indented, please include it in a new post following the guidelines referenced by @chuckwondo.

1 Like

The input function always accepts a string, and here you are comparing it with an integer, which is always true. So that is why your game is always choosing a random strategy instead of the ones specified in the code. All you need is to include the numbers here inside inverted commas and that should work?

I only saw 14, but in any case, you’ll need to fix those yourself. The output from running the check gives you line numbers, and tells you specifically what is wrong:
image

Line 11 is: class Player():
The text is saying there should have been 2 blank lines preceding line 11, but there’s only 1.

After that, the first of your recent posts references this:

See my comments added to your code (all the way to the end). Start with these suggestions, and we can go from there if you need more help.

1 Like

A couple of other things I noticed:

"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""

import random

moves = ['rock', 'paper', 'scissors']

"""The Player class is the parent class for all of the Players
in this game"""

class Player():


    def __init__(self):
        self.score = 0

    def move(self):
        return moves[0]
    def learn(self, learn_move):
        pass

class RandomPlayer(Player):
    def move(self):
        throw = random.choice(moves)
        return (throw)

class ReflectPlayer(Player):

    def __init__(self):
        Player.__init__(self)
        self.learn_move = None

    def move(self):
        if self.learn_move is None:
            throw = moves[0]                      
        else:
            throw = self.learn_move               
            return (throw)                        

    def learn(self, learn_move):

        self.learn_move = learn_move

class Cycles(Player):

    def __init__(self):

        Player.__init__(self)
        self.step = 0

    def move(self):
        throw = None
        if self.step == 0:
            throw = moves[0]
            self.step = self.step + 1
        elif self.step == 1:
            throw = moves[1]
            self.step = self.step + 1
        else:
            throw = moves[2]
            self.step = self.step + 1
        return throw

class HumanPlayer(Player):

    def move(self):

        throw = input('rock, paper, scissors?')
        while throw != 'rock'and throw != 'paper'and throw != 'scissors':
            print('Please try again')
            throw = input('rock, paper, scissors?')
        return (throw)

class Game():

    def __init__(self, p2):
        self.p1 = HumanPlayer()
        self.p2 = p2

    def play_game(self):
        print("Rock Paper Scissors, GO! START! GO!")
        for round in range(3):
            print (f"Round {round}:")
            self.play_round()
        if self.p1.score > self.p2.score:
            print('Player 1 won!')
        elif self.p1.score < self.p2.score:
            print('Player1 2 won!')
        else:
            print('Your game was a draw!')
        print('The FINAL score ' + str(self.p1.score) + ' TO ' +
              str(self.p2.score))

    def play_single(self):
        print("Rock Paper Scissors, Go!")
        print (f"Round 1 of 1:")
        self.play_round()
        if self.p1.score > self.p2.score:
            print('Player 1 won!')
        elif self.p1.score < self.p2.score:
            print('Player 2 won!')
        else:
            print('Your game was a draw!')
        print('The final score ' + str(self.p1.score) + ' TO ' +
              str(self.p2.score))

    def play_round(self):
        move1 = self.p1.move()
        move2 = self.p2.move()
        result = Game.play(move1, move2)
        self.p1.learn(move2)
        self.p2.learn(move1)

    def play(self, move1, move2):
            print(f"You played {move1}")
            print(f"Opponent played {move2}")
            if beats(move1, move2):
                print ("PLAYER ONE WINS!")
                print(f"Score: Player 1: {move1}  Player 2: {move2}\n\n")
                self.p1.score += 1
                return 1
            elif beats(move2, move1):
                print ("PLAYER TWO WINS!")
                print(f"Score: Player 1: {move1}  Player 2: {move2}\n\n")
                self.p2.score += 1
                return 2
            else:
                print ("IT IS A DRAWBREAKER!!!")
                print(f"Score: Player 1: {move1}  Player 2: {move2}\n\n")
                return 0

def beats(one, two):
    return ((one == 'rock' and two == 'scissors') or
            (one == 'scissors' and two == 'paper') or
            (one == 'paper' and two == 'rock'))
if __name__ == '__main__':
    answer = [Player(), RandomPlayer(), Cycles(), ReflectPlayer()]
    p2 = input('The Rock Paper Scissors Game begins! Please type: 1, 2, 3, or 4 Alright, LETS PLAY: [1]Rock, [2]Paper,\
[3]Scissors, or [4]Blah:')

    while p2 != 1 or p2 != 2 or p2 != 3 or p2 != 4:
        p2 = random.choice(answer)
        break

    if p2 == '1':
        p2 = Player()
    elif p2 == '2':
        p2 = RandomPlayer()
    elif p2 == '3':
        p2 = Cycles()
    elif p2 == '4':
        p2 = ReflectPlayer()

    rounds = input('Do you want a [S]ingle or a completely [F]ull game? Please type the letter [S] or [F] to continue:')
    Game = Game(p2)
    
    while True:
        if rounds == 's':
            Game.play_single()
            break
        
        elif rounds == 'f':
            Game.play_game()
            break

        else:
            print('Can you try again please?')
            rounds = input('Enter [S]ingle or [F]ull game:')



-----------------------------------
This is my new code above. I edited some of the things you mentioned. I dont know where to put the lower one. I dont understand this part: while p2 != 1 or p2 != 2 or p2 != 3 or p2 != 4: 
I am struggling to understand almost everything you have written and maybe i should start the code again........ i dont know. Im very confused. This is the PEP8 errors I am getting with the current code. I dont understand the whitespaces. 
![print|690x363](upload://mvKiq1ZkV7foicqeqpOzsBXkkQw.png) 

Is that something your teacher wrote to you? You don’t get to bounce that off to other people. If you want to cheat, fine, nobody cares, but nobody is interested in helping you with that.

If you are looking to learn then there are plenty of people eager to be part of that and help you along, but that seems to be exactly what you’re not doing.

The whole point of exercises is for you to work through them, to find out where you get stuck so that you can identify what knowledge you’re missing, find it, and then carry on.
If you don 't care, then just don’t do it.
But if you get stuck, then explain to somebody in what way you’re stuck and then they can point you in the right direction. By the looks of things you already have access to people willing to do that for you.

2 Likes

Whitespace is spaces or tabs that are in our code. The whitespace that you need to remove is either on blank lines (like the example below) or at the end of lines of code.

If you look closely at the image above, you can see a faint vertical line just to the right of the red arrow. That indicates there are 4 spaces on that line. If you use your mouse, and select that line, then hit the <end> button on your keyboard, your cursor will move to the end of the line. It’s actually a few spaces past the faint vertical line. Then hit <backspace> on your keyboard until your cursor is all the way back to the left. Same process for trailing whitespace. Put your cursor on the line, hit <end>, backspace to where the end of your code is.

As far as the other issues, I’m not sure what more help I can provide. The comments I added to your code, pretty well explain what you need to do. If you have specific questions regarding pieces of your code, feel free to ask, and I or someone else will try to help you. We won’t just write your code for you, but we’ll try to guide you along.

That is disrespectful. I am not cheating. You are accusing me of an outrageous act. I was genuinely asking for help and I am a beginner at Python I am no expert and finding it hard. I would like you to apologize to me for this accusation.

Thank you, that makes sense now. I appreciate all your help.

1 Like