Initializing and displaying grid - python - python

I'm attempting to create a game similar to battleship, and I'm having trouble figuring out how I would initialize the board by having each cell begin with an 'O' and displaying it to the user. A requirement for the function player_board() is that it's supposed to take in a grid representing the player's game board as an argument and output it to the user's screen. This is a portion of my code that I'm struggling with. I'm also not sure why it keeps printing out an extra 'O' at the end. Any help or feedback would be appreciated!
import random
sizeof_grid = 9
chance = 10
def mines():
grid = [{("M" if random.randint(0, chance) == 0 else " ") for i in
range(sizeof_grid)} for i in range(sizeof_grid)]
return grid
def initialize_board():
start_board=[["O" for i in range(sizeof_grid)] for i in range(sizeof_grid)]
return start_board
def players_board():
for r in initialize_board():
for c in r:
print (c, end="")
print()
return c
print(players_board())

You get the extra "O: because of the last line of code. You call the function with print(players_board) and in the function itself you return c (which has the value of one "O"). This means you print out the return value of the function which is "O".
You can execute the function with players_board() and remove the print().
Also you can remove the return c at the bottom of the function.

Related

Beginner Python surface calculation of a hut

I'm trying to make a program to calculate the surface area of ​​a shack with a pitched roof. I've only been in this class for 2 weeks and I'm a bit overwhelmed. The program should ask the user via console for the values ​​and then calculate the values ​​using the definition.
I'm not asking for the entire code at all. But I don't understand how I can calculate inputs using a definition and then print them. this is my code so far:
import math
def floorspace(a,b):
G = 0
G = a*b
return (G)
#main program
a = int(input("enter the length of the floor!"))
b = int(input("Enter the width of the floor!"))
print(floorspace, G)
You don't need to import math as basic multiplication is already included. You also don't need to initialize a variable before you assign it so I removed the
G = 0
G = a*b
lines and replaced it with a simple
return a*b
You don't need brackets around a return statement, just a print statement.
The final two issues are that you're printing incorrectly and you used the wrong function parameters. You would need to pass in the same number of parameters that are in the function declaration (so in this case, 2). Pass in a and b from the user inputs into your floorspace() function and then call print(). The code should work now!
def floorspace(a,b):
return a*b
#main program
a = int(input("enter the length of the floor!"))
b = int(input("Enter the width of the floor!"))
print(floorspace(a,b))
in your code print(floorspace,G) G is not defined you must write your it like this print(floorspace(a,b))

Need help making Hilbert Curve with numbers in python

I want to make a function that will create a Hilbert Curve in python using numbers. The parameters for the function would be a number and that will tell the function how many times it should repeat. To make a Hilbert Curve you start with 'L', then that turns into '+RF-LFL-FR+', and then 'R' turns into '-LF+RFR+FL-' How should I do this?
#Here is what I've made so far
def hilbert(num):
s = 'L'
for i in range(num-1):
s = s.replace('L','+RF-LFL-FR+')
b = 'R'
for i in range(num-1):
b = b.replace('R','-LR+RFR+FL-')
end = s + b
return end
It crashes completely when you enter 1, I tried to use to code I made for the Koch snowflake but I wasn't sure how to use the two variables.
#Here is the results for when I use the function
hilbert(1)
#It returns
a crash bruh
hilbert()
#It returns
'+RF-+RF-LFL-FR+F+RF-LFL-FR+-FR+-L-LR+RFR+FL-+-LR+RFR+FL-F-LR+RFR+FL-+FL-'
#Here is what I want it to return
hilbert(1)
'L'
hilbert(3)
'+-LF+RFR+FL-F-+RF-LFL-FR+F+RF-LFL-FR+-F-LF+RFR+FL-+'

Python Turtle: I want to make a function that executes another function depending on what the previously executed function was

I'm drawing my name using turtles and I have a bunch of different functions for each of the letters
like so (for letter r)
def letter_r(t):
def letter_r_top(t):
turtle.lt(90)
turtle.fd(150)
turtle.rt(90)
turtle.circle(-37.5,180)
turtle.lt(130)
def letter_r_leg(t):
csquare = ((75**2) + (37.5**2))
sidec = math.sqrt(csquare)
turtle.fd(sidec)
letter_r_top(rob)
letter_r_leg(rob)
After each letter, i need to move the turtle into the right place to setup for the next letter. Because each of the letters are different sizes I need to make custom movements depending on what the previous letter is but I dont want to make separate functions for each of those movements.
At the end of my code I have the list of functions to be called in the correct order to spell my name
letter_t(rob)
letter_setup(rob)
letter_r(rob)
letter_setup(rob)
.....
Is there a way that I can do something like this so that I will only need 1 setup function.(Not real code, just a conceptualization of what I'm thinking
def letter_setup(t):
if previously executed function A
turtle.fd(75)
if previously executed function B
turtle.fd(75)
turtle.lt(90)
if previously executed function C
turtle.fd(75)
turtle.lt(90)
Why not the movement to the right place for the next letter at the end of the previous letter?
Perhaps there is a better way to do this but you could make a variable last_function_called and in each function you give it a different value then you'll know wich one was the last called :
last_function_called = NONE;
def function1():
last_function_called = FUNCTION1
blablabla
...
if (last_function_called == FUNCTION1):
call another one
and before of course something like :
NONE = 0
FUNCTION1 = 1
FUNCTION2 = 2
ect...

How to delay blits being iterated from a list

I'm trying to create a typewriter effect for text being blitted. By typewriter effect, I simply mean that Im trying to avoid the entirety of the text being blitted on screen at once. Instead, im trying to have each letter appear individually, with a slight delay before the next character in the string appears.
The catch is that im not using pygame's font.render. Instead, i've made my own custom fonts, each letter being saved as a separate image file. Now each alphanumeric character has it's own variable to which it's image is attached and each is appended to a list.
e.g:
letter_IMGs = []
a = "a" == pygame.image.load("IMG/letter_a.gif)
letter_IMG.append(a)
Lower, I have something along these lines:
letter_pos_x = 0
text = "Hello"
for i, c in enumerate(text):
screen.blit(letter_IMGs[i], (letter_pos_x,0))
letter_pos_x += 20
scroll_wait #this is a clock.delay variable. It's value was set outside the loop. I'm just calling it here.
Now as you'd guess, the result with that code is that the entire line of text appears simultaneously after the delay. I've been trying to code it as needed from there, but most of what I come up with returns with a "cannot iterate through surface objects" error.
I'm pretty much at a loss on how I should proceed next. Note that, ive been learning a bit of code on my own, on and off, for the past year and that I don't really know what im doing yet. Any and all help will be much appreciated.
Thanks in advance for your time.
Without getting into the pygame specifices too much, you just need to change the iterator so it returns substrings rather than letters:
def iterate_text(text):
for r in range(len(text)):
yield text[:r + 1]
which will return the substring iteratively:
for t in iterate_text('hello'):
print t
# h
# he
# hel
# hell
# hello
use a separate function to draw the string:
def draw_text(x, y, text):
characters = [letter_IMGs[t] for t in text]
cursor = x
for char in characters:
screen.blit(char, cursor, y)
cursor += 20
in your main loop you can decide when to get the next character. You'll basically do something like:
typewriter = iter_text('hello world')
text_to_draw = None
advance_text = False
at a level outside the loop that survive from frame to frame. When you want to draw the next character, you set advance_text to True, in and in the main loop:
if typewriter and advance_text:
text_to_draw = typewriter.next()
advance_text = False # until you set it again
if text_to_draw :
draw_text(0,0, draw_text)
You can start over by resetting the typewriter with new text, and control the timing of the new character appearing by setting advance_text to True before the next frame

Any reason why my Python code is not showing up?

I am learning how to code in Python and using the IDLE, I have put in this code, however when I hit F5, nothing happens... no output occurs.
Is this due to maybe the fact that the code I have put in doesn't need an output? Or maybe I am saving it wrongly. Would love to know the reason as it is slightly upsetting.
X = "X" #This is to indicate one piece of the game
O = "O" #this is to indicate another piece of the game
EMPTY = "" # an empty square on the board.
TIE = "TIE" #represents a tie game
NUM_SQUARES = "9" #number of squares on the board
def display_instruct(): #this is a function with the name display_instruct.
"""display game instructions."""
print \
""" Welcome to the greatest challenge of all time: Tic-tac toe. This would be a showdown betweene your human brain
and my silcon processor You will mkae your move known by entering a number
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 |8
Prepare yourself, human. The ultimate battle is about to begin. \n """
def ask_yes__no(question):
"""Ask a yes or no question"""
response = None
while response not in ("y", "n"):
response = raw_input(question).lower()
return response
#this produces a function. It receives a question and thenn responds with an answer which is either yes or not
def ask_number(question, low, high):
"""Ask for a number within the range"""
response = None
while response not in range(low, high):
response - int(raw_input(question))
return response
#remember that when defining the functions, you have to put in colons. The user recieves a question and then has to give an answer.
def pieces():
"""Determine if player or computer goes first""" #docstrings are used to name the functions.
go_first = ask_yes_no("Do you requre the first move?y/n: ")
if go_first == "y": #important to have two equal signs because you are giving a variable a name. Notice that one function callled another.
print "\n Then take the first move, you will need it."
human = X
computer = 0
else:
print "\n Your bravery will beyour undoing .... I will go first."
computer = X
human = O
return computer, human
You need to define and call a main function
def main():
display_instruct()
#the rest of the code
if __name__ == "__main__":
main()
The reason your code doesn't run is because what you have is function definitions
def func() ...
and value assignments
x=5
To actually run something you will either need to define a main function that takes all the things you have defined and combines them in a meaningful way or append to the bottom of the code something similar to what you would write in the main function.

Categories