Inputting the character onto a map - python

def board10():
from random import randint
coins = 0
board = []
charac = []
for i in range(10):
row = []
for j in range(10):
row.append('O')
charac[x][y] = 'x'
board.append(row)
def print_board(board):
for row in board:
print (" ".join(row))
print ("Let's play Treasure Hunt!")
print_board(board)
print ("Total Coins:", coins)
def random_row1(board):
return randint(O, len(board) - 1)
def random_row2(board):
return randint(O, len(board) - 1)
def random_col1(board):
return randint(O, len(board[0]) - 1)
def random_col2(board):
return randint(O, len(board[0]) - 1)
left_across1 = random_row1(board)
right_across1 = random_row2(board)
up_vertical1 = random_col1(board)
down_vetical1 = random_col2(board)
for turn in range(10):
left_across2 = int(input("How many moves LEFT of the grid would you like to go?:"))
right_across2 = int(input("How many moves RIGHT of the grid would you like to go?:"))
up_vertical2 = int(input("How many moves UP of the grid would you like to go?:"))
down_vertical2 = int(input("How many moves DOWN of the grid would you like to go?:"))
if left_across2 == left_across1 and right_across2 == right_across1 and up_vertical2 == up_vertical1 and down_vertical2 == down_vertical1:
print ("Congratulations! You landed on a Treasure Chest!")
coins + 10
break
else:
if (left_across2 < 0 or left_across2 > 8) or (right_across2 < 0 or right_across2 > 8) or (up_vertical2 < 0 or up_vertical2 > 8) or (down_vertical2 < 0 or down_vertical2 > 8):
print ("Oops, that's not even in the grid. Try Again")
else:
print ("Turn", turn + 1 )
print_board(board)
print ("Total Coins:", coins)
choice = "";
while loop ==1:
print ("Menu")
print ("a.) Play the Game")
print ("b.) Quit the Game")
print ("")
choice = input("Select an option = ")
loop =0
if choice == 'a':
print("You have selected to Play the Game")
print("Select which size grid you would like to play")
print("1.) 8 x 8")
print("2.) 10 x 10")
print("3.) 12 x 12")
choice=input("Select an option = ")
if choice =='1':
board8()
elif choice == '2':
board10()
elif choice == '3':
board12()
else:
print("You've picked an invalid choice")
loop ==1
elif choice == 'b':
print("You have selected to Quit the Game")
quit()
else:
print("You've Picked an invalid Choice")
loop==1
I am currently trying to make a treasure island game whereby the code prints out a 10x10 (trying to get this one to work first and then implement the rest of the sized maps) with an X in the bottom left of the map. The user then tells the program how many positions it wants to move the character up , left, right, and down and it then moves.
It should also have randomly hidden coins in it to allow the character to gain points.
Currently I cannot get the board to print with the X on the board. As it is now it returns the error
Traceback (most recent call last):
File "*file Root*/Controlled Assessment (1).py", line 91, in <module>
board10()
File "*file Root*/Controlled Assessment (1).py", line 17, in board10
charac[x][y] = 'x'
NameError: name 'x' is not defined
Any help would be greatly appreciated!

This comes from the line
charac[x][y] = 'x'
^
When you index a list, as you're doing here, you should be using something that evaluates to a number. For example, if you have a variable named lst which holds the value [1, 2, 3, 4, 5] (a list of 5 numbers), then lst[0] is 1, lst[3] is 4, and so on. In addition to using a literal number, you can also use a variable which holds a number, like if foo is defined as 2 (which you might do with the code statement foo = 2), then lst[foo] is 3. This is what you're trying to do in your code, using the value stored under x to index the list charac. However, you never actually put a number in x, so Python doesn't know what to do with it. That's why you're getting this error.
A very simple program which reproduces this error is
lst = [1, 2, 3, 4, 5]
print(lst[x])
A simplistic way to fix this program would be by changing it to the following:
lst = [1, 2, 3, 4, 5]
x = 2
print(lst[x])
In the future, if you try reducing your program to the smallest possible example that gives the error, one like what I just showed, it will become easy for you to find many of the errors you get.

Related

How to add variables

Im making a odds even code i'm struggling to add variables
Im pretty new to coding
from random import *
print("This is the game odds, evens")
game = input("Do you choose odds or evens?")
number = input("What number do you choose")
MyNumber = randint(1,10)
num = game + MyNumber
if num % 2 == 0:
print("even")
if num % 2 == 1:
print("odd")
I got
"Traceback (most recent call last):
File "main.py", line 6, in
num = game + MyNumber
TypeError: must be str, not int"
I don't know how to fix it
use int(game) instead of just game to convert it to numeric
My suggestion for your game:
from random import randint
game = input("Odds (1) or evens (2). Please choose 1 or 2.")
my_random = randint(1,10)
print "My random: {}".format(my_random)
if (my_random % 2 == 0 and game == 2) or (my_random % 2 != 0 and game == 1):
print True
else:
print False
The input method by default gets the input as str so we need to convert it to int. Just make this change to your code and you should be fine.
game = int(input("Do you choose odds or evens?"))
number = int(input("What number do you choose"))
Good Luck!!
I understand where you may have been confused. Theoretically if the user enters 6 and the random number is 3 you would expect to get 9 and the code shouldn't break. However, an input will return a string. So the program now thinks you are trying to add 3 + '6'.
To fix this, you can cast the result of the input to int(game) int(number)

Python 3 - Tuple out of range error. But I'm using a dictionary?

I got a Tuple out of range on my battleships program. The reason I got confused is I'm not using a tuple, unless I'm wrong and I'm willing to be corrected. Tuples are not mutable and the dictionary this is referring to has items added to it upon starting the program.
I am a beginner so if I have made a stupid mistake please don't judge!
from random import randint
#empty list to generate the board.
board = []
messages = {
"win" : "Nooo you won!",
"lose" : "Not my ship haha",
"out" : "Oops, that's not even in the ocean.",
"repeat" : "You guessed that one already"
}
ships = {
'shiprows' : [0]
'shipcols' : [0]
}
#generate board and append to board[] As of now it is a 10*10 grid.
for x in range(0, 10):
board.append(["O"] * 10)
#prints the board every turn.
def print_board(board):
for row in board:
print(" ".join(row))
print_board(board)
#computer chooses where to put battleships' rows
def random_row1(board):
return randint(0, len(board) - 1)
def random_col1(board):
return randint(0, len(board) - 1)
#calling above two functions and storing their values for 5 ships.
#creating variables for 5 ships.
vars = 0
for vars in range(0, 5):
print(vars)
if len(ships.keys()) >= 4:
while ships["shiprow{}".format(vars - 2)] == ships["shiprow{}".format(vars - 1)] and ships["shipcol{}".format(vars - 2)] == ships["shipcol{}".format(vars - 1)]:
ships["shiprow{}".format(vars)] = random_row1(board)
ships["shipcol{}".format(vars)] = random_col1(board)
ships["shiprow{}".format(vars)] = random_row1(board)
ships["shipcol{}".format(vars)] = random_col1(board)
else:
ships["shiprow{}".format(vars)] = random_row1(board)
ships["shipcol{}".format(vars)] = random_col1(board)
#program itself
turn = 0
#enforces four turns before game over. Will possibly extend to unlimited with multiple ships.
print(ships)
for turn in range(20):
turn = turn + 1
print ("Turn {}".format(turn))
print ("Ships Left: {}".format(int(len(ships.keys()) / 2)))
guess_row = int(input("Guess Row: "))
guess_col = int(input("Guess Col: "))
#checking stuff.
i = 0
if guess_row == ships["shiprow{}".format(i = range(0, 10))] and guess_col == ships["shipcol{}".format(i)]:
print (messages["win"])
board[guess_col][guess_row] = u"#"
print_board(board)
elif board[guess_col][guess_row] == "X":
print ("You guessed that one already.")
elif guess_row not in range(len(board)) and guess_col not in range(len(board[0])):
print(messages["out"])
else:
print(messages["lose"])
board[guess_col][guess_row] = "X"
print_board(board)
if turn >= 20:
print ("Game Over")
board[ships["ship_col{}".format(range(0, 10))]][ships["ship_row{}".format(range(0, 10))]] = u"#"
print_board(board)
break
Suspect line appears to be line 62 - this one seems sketchy but I don't actually know how to do it. Please advise on what to do:
BTW here is the error:
Traceback (most recent call last):
File "battleship3.py", line 62, in <module>
if guess_row == ships["shiprow{}".format(i = range(0, 10))] and guess_col == ships["shipcol{}".format(i)]:
IndexError: tuple index out of range
Thanks.
You get this error message whenever you use a format string with positional formats specs (like {} or {1}), but pass only keyword arguments.
Similarly, you get a KeyError when you use a format string with only keyword format specs (like {v}), but pass only positional arguments:
>>> '{}'.format(i=1)
IndexError: tuple index out of range
>>> '{i}'.format(1)
KeyError: 'i'
The fix is just to make your specs match your arguments. Either way you like is fine, they just have to be consistent:
>>> '{i}'.format(i=1)
1
>>> '{}'.format(1)
1
All that being said, I'm not sure what the point of this is:
"shiprow{}".format(i = range(0, 10))
You can fix it either way, but is this really a string you want?
>>> "shiprow{i}".format(i = range(0, 10))
'shiprowrange(0, 10)'
>>> "shiprow{}".format(range(0, 10))
'shiprowrange(0, 10)'
If you're curious why you get this error, oversimplifying format a bit, it works like this:
def format(self, *args, **kwargs):
result = ''
index = 0
bits = self.parse_format_stuff()
for bit in bits:
if bit is a regular string:
result += bit
elif bit is empty braces:
result = args[index]
index += 1
elif bit is a number in braces:
result += args[number]
elif bit is a valid identifier string in braces:
result += kwargs[identifier]
else:
raise a ValueError
return result
So, when it sees that {} format spec, it looks for args[0]. Since you didn't pass any positional arguments, args is the empty tuple (), so args[0] is an IndexError.
Arguably it might be better if format handled those errors and turned them into something nicer—but occasionally it's useful to be able to handle the KeyError programmatically. (Not so often the IndexError, but obviously the two have to work the same way.)
Getting:
Traceback (most recent call last):
File "shiptest.py", line 51, in <module>
ships['shiprows'][vars] += random_row1(board)
IndexError: list index out of range
From changing everything after var=0 to:
vars = 0
for vars in range(0, 5):
print(vars)
ships['shiprows'][vars] = random_row1(board)
ships['shipcols'][vars] = random_col1(board)
print(ships)
I think I am making the list in the dictionary wrong.
Should I use .append()?
EDIT: I used .append() I was an idiot. It is working now thanks for your help!

Skipped If Statement/unstripped input data in Python

I'm updating a crack the code game I made in Python so that you can play a single-player game against the computer. For some reason, the interpreter either doesn't use the data stripped from the input used to determine player count or skips the if statement that uses the stripped data from the input. Either way, after you input the player number it goes straight to the guessing code with an empty list of correct code characters.
My code for the player count determining and code creation is:
plyrs = 0
correctanswer = []
print('Welcome!')
plyrs = str(input('How many players are there? (minimum 1, maximum 2) '))
if plyrs == 2:
print("I'm gonna ask you for some alphanumerical (number or letter characters to make a code for the other player to guess.")
input('Press enter when you are ready to enter in the code!') #Like all of my games, it has a wait.
i = 0
while i < 4:
correctanswer.append(input('What would you like digit ' + str(i + 1) + " to be? "))
i = i + 1
print("Ok, you've got your code!")
i = 0
while i < 19: #Generates seperator to prevent cheating
print('')
i = i + 0.1
print("Now, it's the other player's turn to guess!")
elif plyrs == 1:
import random
characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
i = 0
while i < 4:
correctanswer.append(characters[randint(0,36)])
i = i + 1
print('Time for you to guess!')
print('')
No other skipping if statement questions apply to this so please help.
plyrs is a string, and you're comparing it to an int. "2" == 2 will always be false. Same with plyrs == 1, this will be false throughout.

Bulls and Cows Game - Python programming for beginners

I am a beginer programming Python and for a evaluation assignment I was asked to program a Bulls and Cows game using very simple code.
I have some code already written, but can't seem to make the function work. The function should be able to compare the four digit number the user wrote (num_guess) to the random number generated by the program (stored in a list called num).
I can input the value, but have no further feedback from the program.
Could you please check my code and help me?
Thanks!
import random
guess = raw_input("What is your guess? ")
if (len(guess) != 4):
guess = raw_input("Your guess must be 4 characters long! What is your guess?")
num_guess = []
for c in guess:
num_guess.append(int(c))
def compare(num_guess):
num = []
for i in range(4):
n = random.randint(0, 9)
while n in num:
n = random.randint(0, 9)
num.append(n)
if num_guess == num:
print "Congratulations! Your guess is correct"
output = []
if num_guess[0] == num [0]:
output.append["B"]
else:
output.append["C"]
if num_guess[1] == num [1]:
output.append["B"]
else:
output.append["C"]
if num_guess[2] == num [2]:
output.append["B"]
else:
output.append["C"]
if num_guess[3] == num [3]:
output.append["B"]
else:
output.append["C"]
return output
nguesses = 0
while nguesses < 11:
nguesses = nguesses + 1, compare
Without giving you the corrected code you will want to call the function at the end of your code. If you want to see result do:
print compare(num_guess)
This will show you an additional issue with all of these parts
output.append[]
I'm not sure if it is just how you pasted it but you may want to clean up the indentation. Also:
while n in num:
n = random.randint(0, 9)
This above section is not needed. Have fun and figure out how to make it work well.

Creating a python game, dealing with lists

So I'm creating a very basic python game and I need some help with this step I'm stuck at. The concept of the game is for the program to roll two die and add the sums. With that number they can choose a number available from the number list (1-10) to "peg". They keep going until all numbers are pegged or are out of options. Earlier in the program I created two functions that I'm using in this step. Those two are ask_number and valid_moves. Basically the ask number just asks them which number they want to peg but it doesn't actually peg the number yet. The valid_moves function just checks which numbers are still available for the player to select.
The game pretty much just looks like this halfway through:
------------------------------
(1)(2)(3)(4)(X)(6)(7)(X)(9)(X)
------------------------------
The X are the numbers that were already pegged. In this part of the game I need to figure out how to replace the number with "X". I have this so far but I know I am way off and I am having trouble with figuring out what to do. (pegholes is the name of the list and move is the number they picked in the ask_number function). Thanks so much!
PEGGED = "X"
def enter_peg(pegholes, roll, total):
ask_number()
if ask_number == valid_moves():
pegholes.append(ask_number(PEGGED))
return pegholes, move
I am really not sure how your game is supposed to work, but this may help you out:
#!/usr/bin/env python
import random
import sys
pegs = range(2, 11)
def roll_dice():
return random.randint(1, 5) + random.randint(1, 5)
while True:
roll = roll_dice()
print "You rolled %s" %roll
available_choices = set(p for p in pegs if p != 'X') - set(range(roll+1, 11))
if len(available_choices) == 0:
print "FAIL SAUCE"
sys.exit()
while True:
choice = raw_input("Choose a number %s: " % (", ".join(str(x) for x in sorted(list(available_choices)))))
if choice == 'q':
sys.exit()
choice = int(choice)
if choice in available_choices:
break
print "Nice try buddy... pick a number in range, that hasn't been picked"
pegs[choice - 2] = 'X'
print "".join("(%s)" % p for p in pegs)
if len([x for x in pegs if x == 'X']) == 9:
print "WINNER!"
sys.exit()
I'm not clear on what you're trying to do...
When you say "add the sum" you mean add them together to get a sum, right?
Standard dice add up to 12 and two dice can't total 1 so for a fair game you want to go from 2 - 12
You could try something like this:
import random
#set up list of numbers from 2 to 10
numlist = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#create a roll dice function, producing the sum of two random integers 1-6
def rolldice():
return (random.randint(1,6) + random.randint(1,6))
#run the rolldice function
roll = rolldice()
#set up a loop for while the sum of the roll appears in the list
while roll in numlist:
print "Your rolled %s" %roll
print "Your list was", numlist
print "Replacing %s with X" %roll
numlist[numlist.index(roll)]="X"
print "Your new list is", numlist
raw_input("Press enter to roll again")
roll = rolldice()
#once a roll not in the list show up:
print "Your roll was %s" %roll
print "This is not in your list"
You could also add another if statement to ask the user if they want to try again if the roll is not on the list... and then go back through the while loop.
Keep trying -- I was new to all of this last summer and am still learning. Just keep trying different things... you will learn from your mistakes.

Categories

Resources