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
Related
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 wanted to make a bot that plays Rock, Paper, Scissors with the player.
But every time I try to run the script, and type in Stein (German for rock),
the if statement doesn't detect it or doesn't take any action.
Here's my code so far:
import random
import time
print("Anfangs Buchstaben immer groß schreiben!")
time.sleep(2)
outcomes2 = ("Stein")
Runde = 0
while True:
Player = input("Deine Wahl: ")
for i in range(1):
outcomes = print(random.choice(outcomes2))
if outcomes == Player:
print("draw")
Runde + 1
continue
Issue 1
>>> outcomes2 = ("Stein")
>>> print(random.choice(outcomes2))
n
You're iterating over a string and selecting a character at random.
I'm assuming you want:
>>> outcomes2 = ("Stein", )
>>> print(random.choice(outcomes2))
Stein
Now, by specifying the ,, you're iterating over a tuple of strings (tuple of size 1). You'll end up getting "Stein" only unless you add more strings, like
outcomes2 = ("Stein", "Name2", "Name3", ...)
Issue 2
You want outcomes = random.choice(outcomes2). Do not assign the value to the print statement, because print returns None.
Putting it together...
outcomes2 = ("Stein", )
Runde = 0
while True:
Player = input("Deine Wahl: ")
outcomes = random.choice(outcomes2)
if outcomes == Player:
print("draw")
Runde + 1
continue
`import time
import random
comp_score=0
play_score=0
outcome=('rock','paper','scissor')
while True:
player = raw_input("Enter any?");
out=random.choice(outcome)
print "COMP->"+out
if out==player:
print "draw"
elif out=="rock"and player=="scissor":
comp_score+=1;
elif out=="scissor" and player=="rock":
play_score+=1;
elif out=="rock" and player=="paper":
play_score+=1;
elif out=='paper' and player=='rock':
comp_score+=1;
elif out=="scissor" and player=="paper":
play_score+=1;
elif out=='paper' and player=="scissor":
comp_score+=1;
elif player=="quit":
break;
print "GAME over"
print "PLayer score: ",play_score
print "Comp score ",comp_score`
I am new to python and trying to make a simple game using simplegui in python. In this game, a number is guessed between either 0-100 or 0-1000 (depending upon user's choice) and then the user guess that number. The user gets maximum 7 attempts. The new game starts after the user lose or guess the correct number. The game should run continously.
Problem: When the first game finishes...second game normally and then third game starts which prints the message You lose!.
My code is following:
import simplegui
import random
import math
# initialize global variables used in your code
numOfTurns = 0
numberThought = 2000
maxAllowedTurns = 0
flag = 0 # 1: range is (0, 100] and 2: range is (0,1000]
# define event handlers for control panel
def range100():
# button that changes range to range [0,100) and restarts
global flag
flag = 1
new_game()
def range1000():
# button that changes range to range [0,1000) and restarts
global flag
flag = 2
new_game()
def input_guess(string_guess):
guess = int(string_guess)
global numberThought , numOfTurns, maxAllowedTurns, flag
numOfTurns = numOfTurns + 1
if ( numberThought > 1000 ):
print "Please Select the Range First"
print
return
# main game logic goes here
guessLeft = maxAllowedTurns - numOfTurns
if(numberThought < guess):
print "Your guess was = ", guess
print "Number of Guesses remaining = ", (maxAllowedTurns - numOfTurns)
print "Lower !"
print
if (guessLeft == 0):
print "You Lose!!"
print "The Number was = ", numberThought
print "<<<<<<<<<<<<<<<<<<<<<<<<",">>>>>>>>>>>>>>>>>>>>"
print
print
new_game()
elif (guess < numberThought):
print "Your guess was = ", guess
print "Number of Guesses remaining = ", (maxAllowedTurns - numOfTurns)
print "Higher !"
print
if (guessLeft == 0):
print "You Lose!!"
print "The Number was = ", numberThought
print "<<<<<<<<<<<<<<<<<<<<<<<<",">>>>>>>>>>>>>>>>>>>>"
print
print
new_game()
elif (guess == numberThought):
print "Your guess was = ", guess
print "Correct !"
print
new_game()
if (guessLeft == 0):
print "You Lose!!"
print "The Number was = ", numberThought
print "<<<<<<<<<<<<<<<<<<<<<<<<",">>>>>>>>>>>>>>>>>>>>"
print
print
new_game()
# create frame
frame = simplegui.create_frame("Guess The Number", 300, 300)
# register event handlers for control elements
frame.add_button("range (0,100]", range100)
frame.add_button("range (0,1000]", range1000)
frame.add_input("Enter",input_guess, 100)
# call new_game and start frame
# helper function to start and restart the game
def new_game():
global numberThought , numOfTurns , flag, maxAllowedTurns
numOfTurns = 0
print "<<<<<<<<<<<<<<<<<<<<<<<<",">>>>>>>>>>>>>>>>>>>>"
print "NEW GAME !!!!"
# Defining the number of turns allowed based upon the range type
if(flag == 1):
maxAllowedTurns = 7
numberThought = random.randrange(0,100)
print "Range is from 0 - 100"
print "Max allowed turns = " , maxAllowedTurns
print "Number of Guesses remaining = " , maxAllowedTurns-numOfTurns
print
elif(flag == 2):
maxAllowedTurns = 10
numberThought = random.randrange(0,1000)
print "Range is from 0 - 1000"
print "Max allowed turns = " , maxAllowedTurns
print
frame.start()
(Copy-pasted comment)
I only looked at the code, I didn't test it (didn't want to install simplegui), but I think it prints you lose when you guess the correct number using exactly the allowed turns. Try removing the if block "if (guessLeft == 0): ... " in the last elif block in input_guess.
While working on my program I have run into a problem where the information stored in Menu option 1 is not being transferred to Menu option 2. As you can see it is correctly stored when in menu one. When it returns to go to menu option 2 its like it never went to option 1.
update #1:
some suggestions I've had is to understand scope? from what I can tell the program is not passing the data along to its parent program even though I've typed out return in each of the definitions.
#Must be able to store at least 4 grades
#Each class can have up to 6 tests and 8 hw's
#Weighted 40%*testavg 40% hw average attendance is 20%
#User must be able to input a minimum grade warning
#after each test the your program must calculate the students average and issue warning if necessary
##Define the Modules##
import math
def menu (a): #2nd thing to happen
menuend = 'a'
while menuend not in 'e':
menuend = raw_input("Type anything other then 'e' to continue:\n")
print "What would you like to do ?"
menudo = 0
print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
menudo = input("Enter Selection:")
if (menudo == 1):
menuchck = 0
menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
if menuchck in ["Yes","yes","y","Y"]:
x = m1()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 2):
menuchck1 = 0
menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
if menuchck1 in ["Yes","yes","y","Y"]:
x = m2()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 3):
print "Entered 3"
elif (menudo == 4):
print "Entered 4"
else:
print "Anything Else Entered"
def course(): #3rd thing to happen
b = {}
while True:
while True:
print "\n",name,", please enter your courses below ('e' to end):"
coursename = raw_input("Course Name:")
if (coursename == 'e'):
break
will = None
while will not in ('y','n'):
will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
if will=='y':
b[coursename] = {}
print "\n",name,", current course load:\n",b
coursechck = None
while coursechck not in ('y','n'):
coursechck = raw_input("Are your courses correct (y/n)")
if coursechck =='y':
return b
else:
b = {}
print
##Menu Options##
def m1():
a = course()
return a
def m2():
print "Excellent",name,"lets see what courses your enrolled in\n"
print x
return x
###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)
raw_input("This is the end, my only friend the end")
In your if-elif blocks in the do==1 case, you write m1(), but for the last case, you write x=m1(). You should have the latter everywhere (by typing m1() you only run the function, but do not store the returned x anywhere).
By the way, you can avoid this if-elif confusion using if chck in ["Yes","yes","Y","y"]:
I'm new to programming, and I tried to make a python program. Here it is:
import time
gravity = 0
space = 0
print "Welcome to the 'Find out who is in space' program"
person_messy = raw_input("Enter a name:")
person = person_messy.lower()
if len(person) < 5:
print "Make sure you put the first AND last name"
else:
space = 1
print "Searching database....."
if person == "oleg kotov" or "mike hopkins" or "sergey ryazanskiy" or "fyodor yurchikhin" or "karen nyberg" or "luca permitano":
gravity = 1
else:
gravity = 0
time.sleep(1)
if space == 1:
print "loading..."
time.sleep(1)
if space == 1:
print "loading..."
time.sleep(1)
if space == 1:
print "loading..."
if gravity == 1:
print person + "is in space!"
else:
print "You and " + person + "are on the same planet."
this is the error I got:
Internal error: ReferenceError: _select is not defined
I had the same problem on similar code... You can't use time.sleep or it gives this. I don't know why, but that fixed my code(not using time.sleep)