Identify python errors - python

Can someone assist with identifying the errors in this loop?
I am completely new to Python.
for p in players:
x = len(p)
dice = random.randint(0, x*2)
print p + " rolls a " + dice + " out of " + str(x*2)
if dice > x:
print p + " wins!"
elif dice == x:
print p + "gets a tie."
else:
print p + " loses."}
Thanks!!

Works in Python 3.x
import random
players = ["Player 1", "Player 2"]
for p in players:
x = len(p)
dice = random.randint(0, x*2)
print(str(p) + " rolls a " + str(dice) + " out of " + str(x*2))
if dice > x:
print(p + " wins!")
elif dice == x:
print(p + "gets a tie.")
else:
print(p + " loses.")
For Python 2.x
import random
players = ["Player 1", "Player 2"]
for p in players:
x = len(p)
dice = random.randint(0, x*2)
print(str(p) + " rolls a " + str(dice) + " out of " + str(x*2))
if dice > x:
print p + " wins!"
elif dice == x:
print p + "gets a tie."
else:
print p + " loses."
or add from __future__ import print_function to first example to ensure compability between Python 3 and 2.

Related

Debugging Maze game in Python

Ive been learning python recently and am currently working on a small terminal game that has a character move through a maze. Im having a bug where my character is getting stuck and not allowed to move into the open spaces. Ive checked that all my movements the correct directions, and im not sure why the character is stuck.
App
played = player.Player(3, 2)
while True:
board.printBoard(played.rowPosition, played.columnPosition)
selection = input("Make a move: ")
if selection == "w":
if board.checkMove(played.rowPosition - 1, played.columnPosition):
played.moveUp()
elif selection == "s":
if board.checkMove(played.rowPosition + 1, played.columnPosition):
played.moveDown()
elif selection == "a":
if board.checkMove(played.rowPosition, played.columnPosition - 1):
played.moveLeft()
elif selection == "d":
if board.checkMove(played.rowPosition, played.columnPosition - 1):
played.moveRight()
else:
print("Invalid key")
if board.checkWin(played.rowPosition, played.columnPosition):
print("You Win!")
break;
Player:
class Player:
def __init__(self, intitalRow, initialColumn):
self.rowPosition = intitalRow
self.columnPosition = initialColumn
def moveUp(self):
self.rowPosition = self.rowPosition - 1
def moveDown(self):
self.rowPosition = self.rowPosition + 1
def moveRight(self):
self.columnPosition = self.columnPosition + 1
def moveLeft(self):
self.columnPosition = self.columnPosition - 1
Gameboard
class GameBoard:
def __init__(self):
self.winningRow = 0
self.winningColumn = 2
self.board = [
[" * ", " * ", " ", " * ", " * ", " * "],
[
" * ",
" ",
" ",
" ",
" * ",
" * ",
],
[
" * ",
" ",
" * ",
" * ",
" ",
" * ",
],
[
" * ",
" ",
" ",
" ",
" ",
" * ",
],
[" * ", " * ", " * ", " * ", " * ", " * "],
]
def printBoard(self, playerRow, playerColumn):
for i in range(len(self.board)):
for j in range(len(self.board[i])):
if i == playerRow and j == playerColumn:
print("P", end="")
else:
print(self.board[i][j], end="")
print("")
def checkMove(self, testRow, testColumn):
if self.board[testRow][testColumn].find("*") != -1:
print("Can't move there!")
return False
return True
def checkWin(self, playerRow, playerColumn):
if playerRow == 0 and playerColumn == 2:
return True
else:
return False
When the selection is "d" the same cell is being checked as when the selection is "a". I think you meant for one of these to use played.columnPosition + 1.

I don't know how to make a while loop last until a list doesn't have any values left

I am trying to recreate the card game "War" in python and cant figure out how to loop the code under the comment until every value in the list is gone. So basically the code generates a shuffled deck of cards and pops the cards from the list. I want to have the code repeat until all the cards have been popped from the deck and I have no idea how to do that.
import random
def shuffled_deck():
deck = list(range(2, 15)) *4
random.shuffle(deck)
return deck
userdeck = shuffled_deck()
print("welcome to War!")
user1 = input("Player-1 name: ")
user2 = input("Player-2 name: ")
u1points = 0
u2points = 0
drawturns = 0
# - I want to loop the segment of code under this comment
usercard = userdeck.pop()
u1card = usercard
print(user1 + ": " + str(u1card))
usercard = userdeck.pop()
u2card = usercard
print(user2 + ": " + str(u2card))
if u1card > u2card:
print(str(u1card) + " is greater than " + str(u2card) + ".")
print(user1 + " won this round.")
u1points +=1
elif u2card > u1card:
print(str(u2card) + " is greater than " + str(u1card) + ".")
print(user2 + " won this round.")
u2points +=1
else:
print("It's a draw, try again.")
while u1card == u2card:
drawturns +=1
usercard = userdeck.pop()
u1card = usercard
print(user1 + ": " + str(u1card))
usercard = userdeck.pop()
u2card = usercard
print(user2 + ": " + str(u2card))
if u1card > u2card:
print(str(u1card) + " is greater than " + str(u2card) + ".")
print(user1 + " won this round.")
u1points +=1
u1points + drawturns
elif u2card > u1card:
print(str(u2card) + " is greater than " + str(u1card) + ".")
print(user2 + " won this round.")
u2points +=1
u1points + drawturns
else:
print("It's a draw, try again.")
if u1card == u2card == False:
drawturns = 0
break
You can do:
while len(userdeck)>0:
or, you can write smartly as:
while userdeck:
This is because an empty list is considered as False, whereas a non empty list is considered as True. So, when userdeck is empty, while loop will assume it to be False case, so the loop will stop. This same concept can also be applied for if statements.

Connect4 in Python - Pieces doesn't drop into the board

I'm writing Connect4 in Python. My problem is the function of player_one and player_two don't seem to be working, so the no piece is drop onto the board after player was asked to give input. I also wonder if my code to return the board after player has dropped is correct; I suspect that my present code doesn't return the board updated with a player's piece but being new, I'm not sure what to do.
Please take a look!
def field(field):
for w in range(14):
if w % 2 == 0:
usable_w = int(w/2)
for h in range(15):
if h % 2 == 0:
usable_h = int(h/2)
if h != 14:
print(field[usable_h][usable_w], end="")
else:
print(" ")
else:
print("|", end="")
else:
print("_"*13)
PlayField = [[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "]]
field(PlayField)
def player_one(field):
MoveColumn = int(input("Enter the column 1 - 7\n"))
MoveRow = 6
for row in PlayField:
if MoveColumn >= 1 and MoveColumn <= 7:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = "X"
break
MoveRow -= 1
return field(PlayField)
else:
print("Column outside range, please enter valid move")
def player_two(field):
MoveColumn = int(input("Enter the column 1 - 7\n"))
MoveRow = 6
for row in PlayField:
if MoveColumn >= 1 and MoveColumn <= 7:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = "O"
break
MoveRow -= 1
return field(PlayField)
else:
print("Column outside range, please enter valid move")
def launch_play():
while True:
Player = 1
print("Player's turn", Player)
player_one(field)
player_two(field)
launch_play()
Well, your player_... functions contain suitable statements, but in an unsuitable order; and since they operate on the global PlayField, returning it is pointless. Besides that, it's ugly having two nearly identical functions. A rearranged variant where the only difference between player one and two is passed as an argument (instead of the useless field) works as you expect:
def player(xo):
while (MoveColumn := int(input("Enter the column 1 - 7\n"))) < 1 or \
MoveColumn > 7:
print("Column outside range, please enter valid move")
MoveRow = 6
for row in PlayField:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = xo
field(PlayField)
break
MoveRow -= 1
In your launch_play loop you can now call
player('X')
player('O')
Now it's up to you to complete the program by checking when the game is over.
I came up with two solutions (before you modified the codes) to prevent players' turn from changing, but which couldn't work:
def player(xo):
while MoveColumn := int(input("Enter the column 1 - 7\n")):
MoveRow = 6
for row in PlayField:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = xo
field(PlayField)
break
Return True
MoveRow -= 1
else:
print("Column outside range, please enter valid move")
Return False
def launch_play():
while True:
Player = 'X'
print("Player's turn", Player)
player('X')
Player = '0'
print("Player's turn", Player)
player('0')
launch_play()
The other solution is to introduce player variables in the player functions (also didn't work) :
def player(xo):
while MoveColumn := int(input("Enter the column 1 - 7\n")):
MoveRow = 6
Player = 'X'
for row in PlayField:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = xo
field(PlayField)
break
MoveRow -= 1
Player = '0'
else:
print("Column outside range, please enter valid move")

connect four: asking for inputs without printing

I am making a connect four type game. I am trying to set up the simple playability of the game. I don't get an error, but it does keep sending me into a input when I want it to print out the board. When I type in a number for the column, it doesn't print anything, it just gives me another input I should fill, this continues until i exit the program.. I am trying to stay away from classes, given that I am not very good at programming these yet. I would like to know why this is happening, and what to do to fix it, or if I just need to reprogram the whole thing.
a = [" ", " ", " ", " ", " ", " ", " "]
b = [" ", " ", " ", " ", " ", " ", " "]
c = [" ", " ", " ", " ", " ", " ", " "]
d = [" ", " ", " ", " ", " ", " ", " "]
e = [" ", " ", " ", " ", " ", " ", " "]
f = [" ", " ", " ", " ", " ", " ", " "]
board = [a, b, c, d, e, f] # sets up the board
print("What is player 1's name?")
player1 = input()
print("What is player 2's name?")
player2 = input()
plays = 0
def print_board(): # prints the board
p = 0
for x in board:
for i in x:
print(i, end=" | ")
print()
p += 1
if p != 6:
print("- "*15)
else:
print()
def win(): # defines a boolean if one player has won
i = 0
k = 0
while i != 5:
while k != 6:
if board[i][k] == "o" or board[i][k] == "x":
if board[i+1][k] == board[i][k] == board[i+2][k] == board[i+3][k]:
return False
elif board[i][k] == board[i][k+1] == board[i][k+2] == board[i][k+3]:
return False
elif board[i][k] == board[i+1][k+1] == board[i+2][k+2] == board[i+3][k+3]:
return False
elif board[i][k] == board[i-1][k-1] == board[i-2][k-2] == board[i-3][k-3]:
return False
else:
return True
def play(): # defines the part you play.
if plays % 2 == 0:
player = "o"
else:
player = "x"
print_board()
x = int(input("Where would you like to put your chip?"))
i = 0
while i < 5:
if board[i][x] == " ":
if board[i+1][x] == "x" or board[i+1][x] == "o":
board[i][x] = player
print_board()
if win():
print(player+" won!")
play()
play() # runs the script
try this for your play loop - hopefully it will help you fix the win check also:
def play(): # defines the part you play.
plays = 0
while True:
if plays % 2 == 0:
player = "o"
else:
player = "x"
x = int(input("Where would you like to put your chip?"))
i = 0
for i in range(5):
if board[i][x] == " ":
if board[i+1][x] == "x" or board[i+1][x] == "o":
board[i][x] = player
else:
board[5][x] = player
print_board()
#if win():
# print(player+" won!")
# break
plays += 1
print_board()
play() # runs the script
i commented out the win check because it doesn't work yet

Dependent probability in Python

I'm trying to make something in Python, just for myself, which will determine the likelihood of, in my case, drawing a certain card in a deck. The deck's size is determine by a raw_input, as is the number of cards of which you are trying to calculate probability of drawing. Right now, I have:
from __future__ import division
t = True
while True:
if t == True:
numCards = int(raw_input("How many cards in your deck? Type here: "))
print "There are " + str(numCards) + " cards in your deck."
whatCards = raw_input("What card are you testing for how likely it is to draw them? Type here: ")
whatCards = whatCards.capitalize()
print whatCards + " is a great card!"
if whatCards.endswith("s"):
numCards2 = int(raw_input("How many " + whatCards + " are in it? "))
whatCards = whatCards + "s"
elif whatCards.endswith("y"):
numCards2 = int(raw_input("How many " + whatCards[:-1] + "ies are in it? "))
else:
numCards2 = int(raw_input("How many " + whatCards + "s are in it?"))
if numCards2 > 1:
print "Ok! There are " + str(numCards2) + " " + whatCards + "s" + "!"
else:
print "Alright. There is " + str(1) + " " + whatCards + "!"
'''probability = (numCards2 / numCards) + (numCards2 / (numCards-1)) + (numCards2 / (numCards-2)) + \
(numCards2 / (numCards-3)) + (numCards2 / (numCards-4)) + (numCards2 / (numCards-5))\
+ (numCards2 / (numCards-6))'''
probability = numCards2 / numCards
print "Results are approximate"
print "Decimal: " + str(probability)
if len(str(probability)) <= 3:
print "Percentage: " + str(probability)[2] + str(0) + "%"
else:
print "Percentage: " + str(probability)[2] + str(probability)[3] + "%"
print "Fraction: " + str(numCards2) + "/" + str(numCards)
t = False
if t == False:
numCards = int(raw_input("How many cards in your deck? Type here: "))
print "There are " + str(numCards) + " cards in your deck."
whatCards = raw_input("What card are you testing for how likely it is to draw them? Type here: ")
whatCards = whatCards.capitalize()
print whatCards + " is a great card!"
if whatCards.endswith("s"):
numCards2 = int(raw_input("How many " + whatCards + " are in it? "))
whatCards = whatCards + "s"
elif whatCards.endswith("y"):
numCards2 = int(raw_input("How many " + whatCards[:-1] + "ies are in it? "))
else:
numCards2 = int(raw_input("How many " + whatCards + "s are in it?"))
if numCards2 > 1:
print "Ok! There are " + str(numCards2) + " " + whatCards + "s" + "!"
else:
print "Alright. There is " + str(1) + " " + whatCards + "!"
'''probability = (numCards2 / numCards) + (numCards2 / (numCards-1)) + (numCards2 / (numCards-2)) + \
(numCards2 / (numCards-3)) + (numCards2 / (numCards-4)) + (numCards2 / (numCards-5))\
+ (numCards2 / (numCards-6))'''
probability = numCards2 / numCards
print "Results are approximate"
print "Decimal: " + str(probability)
if len(str(probability)) <= 3:
print "Percentage: " + str(probability)[2] + str(0) + "%"
else:
print "Percentage: " + str(probability)[2] + str(probability)[3] + "%"
print "Fraction: " + str(numCards2) + "/" + str(numCards)
t = True
As you can see, what it's currently solving is likelihood of only one draw. However, my goal is to make it so that the user can input their own number of card draws, so, say, they have a 60 card deck, with 15 Swamp cards in it, and 7 draws. The problem is that if I wanted to draw a hand's worth of cards (7), I couldn't just make it calculate the probability of drawing out of 60, then 59, then 58, down to 53. That's because if they were to draw the Swamp, the probability goes down, which going down from 60 to 53 wouldn't do. What would I have to make so that it randomly selected x cards out of y (deck size), with z amount of draws as well as decremented the number of x when it was "drawn", and changed y for each "draw". And it would have to work any number of times, depending on what the user wanted. Thanks! (hope this makes sense...)
Let's say you have n cards and you are drawing m of them. The possible combinations are n!/(n-m)! If you are looking for the probability to draw y cards ( y<=m ) of a kind which makes up x of the total n cards. You have to consider 2 quantities:
1. The possible ways to pick y cards out of x cards which is x!/(x-y)! And then the possible ways to lay this ordered sets into m slots, or else where to put the other m-y cards into the set of m cards which is m!/(m-y)!
The product of these 2 quantities gives you the favorable events, while the first number gives you the total event. So your probability is
P = x!m!(n-m)!/(n!(x-y)!(m-y)!)
I hope I did not miss anything :)

Categories

Resources