I don't know why but my counter won't stop although I think I have it coded right to stop after three iterations. Any ideas on why it wont work? #Ayush The counter is intialised to 1 at the beginning of the programme which is not included here. Where will I place the conditions? As I've tried using both "for counter in range(3) and while counter in range(3) however in the case of the while counter it runs for 3 iterations and then begins a fourth which gives me an error saying:
Traceback (most recent call last):
File "C:\Python32\Final Year Project\Build 6 (MiniMax input).py", line 311, in <module>
print('The ' + turn + ' has been chosen this time, what move will they make first?!.')
TypeError: Can't convert 'NoneType' object to str implicitly
#CyberGeekk.exe Here's a description of 'turn' and as turn = whoGoesFirst() I've included that aswell.
def whoGoesFirst():
if (counter==1):
if random.randint(1,1) == 0:
return 'computer'
else:
return 'player'
if (counter==2):
if random.randint(1, 1) == 0:
return 'computer'
else:
return 'player'
if (counter==3):
if random.randint(1, 1) == 0:
return 'computer'
else:
return 'player'
theBoard = [' '] * 10
playerLetter, computerLetter = inputPlayerLetter()
turn = whoGoesFirst()
print('Now For Level ' +str(counter)+ '!!')
print('--------------------')
print('The ' + str(turn) + ' has been chosen to go first, what will they do?')
gameIsPlaying = True
while gameIsPlaying:
while counter in range(3):
if turn == 'player':
# Player's turn.
drawBoard(theBoard)
move = getPlayerMove(theBoard)
makeMove(theBoard, playerLetter, move)
if isWinner(theBoard, playerLetter):
counter=counter+1
drawBoard(theBoard)
print('--------------------')
print("No, no! It cannot be! Somehow you tricked me, human. \n"
"But never again! I, the computer,will increse my skill level for round "+str(counter)+" and beat you")
print('--------------------')
print('Now For Level ' +str(counter)+ '!!')
#print('-------------------')
gameIsPlaying = True
theBoard = [' '] * 10
playerLetter, computerLetter = inputPlayerLetter()
turn = whoGoesFirst()
print('The ' + turn + ' has been chosen this time, what move will they make first?!.')
gameIsPlaying = True
The loop breaks on if (counter<=4): because 1 is less then 4. To make the loop go 3 times, simply change the code on that line to look like this: if (counter == 4):. I tried this while commenting out all the unprovided methods and got the loop to go around 3 times.
Hope this helps you in your project, and please leave a comment if you need more help. Your welcome.
Related
Trying to figure out why the program won't run.
This is the error code I am getting:
update_position (random_roll_1, random_roll_2)
builtins.NameError: name 'random_roll_1' is not defined
I thought I had all the correct parameters but I guess not. Any help would be really appreciated
import random
from random import randint
#both of the players are able to roll out their turs
this is the function where the players can roll their dice and receive a random number
def roll_die(p1_move,p2_move):
if p1_move is True:
input('Press enter to roll the die for player 1')
random_roll_1 = randint(1,6)
random_roll_1 = str(random_roll_1)
print('Player 1 rolled ' + random_roll_1)
random_roll_1 = int(random_roll_1)
return random_roll_1
elif p2_move is true:
input('Press enter to roll the die for player 2')
random_roll_2 = randint(1,6)
random_roll_2 = str(random_roll_2)
print('Player 2 rolled ' + random_roll_2)
random_roll_2 = int(random_roll_2)
return random_roll_2
This part updates the position on where each player is after it rolls the dice. The players have to roll exactly 8 in order to win. Anything higher than that will cause the player to stay in its position
def update_position(random_roll_1, random_roll_2):
player_1_position = 0
player_2_position = 0
max_score = 8
if player_1_position < max_score:
if player_1_position + random_roll_1 > 8:
print('The roll was too high, player 1 stays in the same spot')
else:
player_1_position += random_roll_1
print('Player 1 moved up ' + random_roll_1 + ' spots!')
return player_1_position
elif player_2_position < max_score:
if player_2_position + random_roll_2 > 8:
print(' The roll was too high, player 2 stays in the same spot')
else:
player_2_position += random_roll_2
print('Player 2 moved up ' + random_roll_2 + ' spots!')
return player_2_position
this function checks to see if one of the players hit 8 as their score
#checks to see if any of the players have managed to reach the end of the game
def check_game_over(player_1_position, player_2_position):
if player_1_position == 8:
print('Player 1 has won!')
print('Thank you for playing!')
continue_game = False
return continue_game
elif player_2_position == 8:
print('Player 2 has won!')
print('Thank you for playing!')
continue_game = False
return continue_game
This function is what controls who's turn it is. I added in the roll dice function along with the update spot function as it would be easier to include them in one whole function together. This is where I am getting my problem.
#random_roll_1,random_roll_2, player_1_position, player_2_position
#change the turn over to the next player
def opponent():
p1_move = True
p2_move = False
if p1_move is True:
roll_die (p1_move, p2_move)
update_position (random_roll_1, random_roll_2)
p1_move = False
p2_move = True
return p1_move, p2_move
elif p2_move is True:
roll_die(p1_move, p2_move)
update_position (random_roll_1, random_roll_2)
p1_move = True
p2_move = False
return p1_move, p2_move
This function basically shows the user which location they are currently sitting at.
def display_state (player_1_position, player_2_position, p1_move, p2_move):
if p1_move is True:
player_1_position = str(player_1_position)
print('Player 1 is in ' + player_1_position + ' spot')
player_1_position = int(player_1_position)
elif p2_move is True:
player_2_position = str(player_2_positon)
print('Player 2 is in ' + player_2_position + ' spot')
player_2_position = int(player_2_position)
Not entirely sure if this function is right at all because I still don't understand main functions completely so not sure if this main function works
def main():
#display instructions
continue_game = True
while continue_game:
opponent()
display_state (player_1_position, player_2_position, p1_move, p2_move)
check_game_over(player_1_position, player_2_position)
main()
So there are a few errors in your program above. The runtime error you stated above is caused when you try to pass 2 variables into the update_position function before they have been defined.
roll_die (p1_move, p2_move)
## random_roll_1 and random_roll_2 have not been defined
update_position (random_roll_1, random_roll_2)
However, before you deal with this error, there is a key programming concept to understand. Global and Local variables.
A Global variable is one which the entire program can use. They are normally defined at the top of your program:
p1_move = True
p2_move = False
def roll_die(): ...
def main(): ...
etc
A Local variable is one which can only be used inside of the function it was created in.
def foo():
x = 10
y = 5
return x + y
In this example, the variables x and y are local variables and cannot be used in other functions of your program (as they only exist inside the function foo).
One thing to note, in the case where you pass a variable as a functional argument, then modify that variable in the function without returning the modified variable. That variable will only be modified inside that function, no where else. This is true for primitive data types (variables not passed by reference).
def foo(z):
z += 1
z = 5
foo(z)
print(z)
In this example, the output would be 5, not 6 as the modified z variable in the function foo has not been returned.
For this reason alone, global variables may seem like the better option, however in general global variables are a bad idea and it is recommended that you stick to using local variables.
More information about Global and Local variables.
With this knowledge, some of your errors may seem more obvious.
For example, in your function roll_die, you define 2 variables random_roll_1 and random_roll_2. However you try to use these variables in other functions, update_position for example.
I realise that you have tried to return each random_roll variable independently from the roll_die function, however you do not store these returned values.
# Original
roll_die (p1_move, p2_move)
# Correctly returned
random_roll = roll_die(p1_move, p2_move)
In the next line, you then try to use both random_roll_1 and random_roll_2 variables, even though you only know 1 of those variables at that stage.
# Original
update_position (random_roll_1, random_roll_2)
# Possible Correction
update_position(random_roll)
You would then have to redefine the update_position function, thinking about each player's go as if it happened one after another, and not both at the same time.
I would also like to emphasize the importance of reducing the amount of duplicate code in your program.
Your opponent function could instead be written as:
def opponent(p1_move, p2_move):
random_roll = roll_die(p1_move, p2_move)
update_position(random_roll)
p1_move = not p1_move
p2_move = not p2_move
return p1_move, p2_move
This refactoring has changed a few details, most importantly, the use of the not. This operator will turn True->False and False->True. For example, if p1_move is false, not p1_move is True.
In addition, the function has parameters p1_move, p2_move, as these variables will be required in other parts of your program, you should define them outside of this functions scope, and pass them as arguments into your other functions. And don't forget to store the return values!
Just to note, this function refactoring is an example of how to reduce duplicate code, and is designed to be used with your modified program.
There are a few more modifications required to make your program run, but I will let you work them out for yourself.
import random
def shuffled_deck():
basic_deck = list(range(2, 15))
random.shuffle(basic_deck)
return basic_deck
print(shuffled_deck())
def suits():
Suits_Deck = list('Spades','Hearts','Clubs','Diamonds')
random.shuffle(Suits_Deck)
return(Suits_Deck)
e = random.randint(0,3)
f = random.randint(0,3)
a = random.randint(0,11)
b = random.randint(0,11)
c = str(input("What is Player 1's name? "))
d = str(input("What is Player 2's name? "))
print(c+ ' drew card ' + shuffled_deck[a] + 'of'+ suits[e])
print(d+ ' drew card ' + shuffled_deck[b] + 'of'+ suits[f])'''
Okay so basically I need to make a deck of cards. I also have to have the code select a card at random and assign it to a player. For some reason when I try to run the code this error appears.
Traceback (most recent call last):
File "main.py", line 17, in <module>
print(c+ ' drew card ' + shuffled_deck[a] + 'of'+ suits[e])
TypeError: 'function' object is not subscriptable
Instead of shuffled_deck[a] use shuffled_deck()[a] and
Instead of suits[a] use suits()[a]
Both shuffled_deck and suits are functions that return list, so call function then use index to get the element fun()[index]
You need to get the list by calling the shuffled_deck function, then index the returned list, i.e. shuffled_deck()[a] instead of shuffled_deck[a].
The same applies for suits[a] - this should be written as suits()[a] to first call the function.
this is elaboration version from #dspencer and #Praveen answer.
so you want to print like :
player A drew card 5 of Clubs
player B drew card 3 of Spades
If this what you want, you might edit your code.
import random
def shuffled_deck(n):
basic_deck = list(range(2, 15))
random.shuffle(basic_deck)
return basic_deck[n]
def suits(n):
Suits_Deck = ['Spades','Hearts','Clubs','Diamonds']
random.shuffle(Suits_Deck)
return Suits_Deck[n]
e = random.randint(0,3)
a = random.randint(0,11)
#first attempt
print(' drew card ' + str(shuffled_deck(a)) + ' of '+ suits(e))
#second attempt
print(' drew card ' + str(shuffled_deck(a)) + ' of '+ suits(e))
note in the suits() fucntion, directly make a list using '[ ]' Python list
also your shuffled_deck[a], its not a proper way to call a function, use shuffled_deck(a). 'a' from randomint will be the index of basic_deck List.
Hope it help
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'm writing my first short programs with Python. This program should stop after the third wrong guess. The program works as expected with the first question, and stops itself after three wrong guesses.
However, I cannot understand why, with the second question, after the third wrong guess, the first question is repeated.
easy_text = '''Hello __1__!' In __2__ this is particularly easy; all you
have to do is type in: __3__ "Hello __1__!" Of course, that isn't a very
useful thing to do. However, it is an example of how to output to the user
using the __3__ command, and produces a program which does something, so it
is useful in that capacity..'''
def split_string():
global easy_text_splitted
easy_text_splitted = easy_text.split(" ")
return None
def level1():
print """You will get 3 guesses per problem
The current paragraph reads as such:"""
print easy_text
return first_question(3)
def first_question(guesses):
while guesses > 0:
split_string()
first_answer = raw_input("What should be substituted in for __1__?")
if first_answer.lower() == "world":
easy_text_splitted[1] = first_answer
easy_text_splitted[19] = first_answer
new_easy_text = " ".join(easy_text_splitted)
print new_easy_text
second_question(3)
else:
guesses -= 1
print "That's not the answer I expected. You have " +
str(guesses) + " guess(es) left"
return first_question(guesses)
def second_question(guesses):
while guesses > 0:
split_string()
second_answer = raw_input("What should be substituted in for 2?")
if second_answer.lower() == "python":
easy_text_splitted[4] = second_answer
new_easy_text = " ".join(easy_text_splitted)
print new_easy_text
else:
guesses -= 1
print "That's not the answer I expected. You have \n " +
str(guesses) + " guess(es) left"
return second_question(guesses)
def level_selection(index):
level = raw_input("Choose the desired level of difficulty: easy, \n
medium, or hard ")
if level.lower() == "easy":
return level1()
if level.lower() == "medium":
return level2
if level.lower() == "hard":
return level3
else:
print "Error"
index -= 1
if index > 0:
return level_selection(index)
return "Bye!"
print level_selection(3)
level2 = "You selected medium"
level3 = "You selected hard"
Whatever the value of guesses was in first_question when second_question was called, it is the same when it returns, so the loop continues, and repeats the first question.
Using a debugger will help you follow how this works.
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