I am facing a problem while trying to assign materials "on the go" to a set of cubes in Blender3D. I know it comes from the fact that the objects data names are being incremented when generated (Cube, Cube.001, cube.002...) but I don't know the way to have the name of the object being interactive with the loop. I'd really appreciate if someone could give me a tip !!
Dark = bpy.data.materials['Dark']
Light= bpy.data.materials['Light']
for x in range(4):
for y in range(4):
for z in range(4):
bpy.ops.mesh.primitive_add_cube(radius=.049, location=(x,y,z))
a = bpy.data.object['Cube']
if (x+y+z) % 2 == 0:
a.data.materials.append(Dark)
else:
a.data.materials.append(Light)
Related
I need a loop over all of my clans, which are instances of a class. Each clan needs to be assigned a position, a x and a y coordinate. Preferably as two lists or as a single tuple (but no idea how I specify that). This is how it works for the 1st clan. Afterwards I always have to check, if the position is already assigned. If so, you have to search for a new position until it is free.
I then coded my class like this:
width = 20
height = 20
no_of_clans = 50
import random
class clan:
def __init__(self, index, position_list):
self.index = index
self.position_list = position_list
def index(no_of_clans):
return list(range(1, no_of_clans +1))
def position_list(self):
for i in range(1, no_of_clans +1):
positions = ()
if i ==1: #i can do it either like this
positions = [(random.randint(0, width)), (random.randint(0, height))]
positions.append(x,y)
else: #or like this, I do not know, which one is better, both are running
x = (random.randint(0, width))
y = (random.randint(0, height))
#check if x and y not already used
#assert
positions.append(x,y)
return positions
print(positions)
how can I assign positions randomly when also using 0.5 steps? I always get an error message.
I never get a list of my positions back, but I do not know what I did wrong.
I know those are probably fairly basic questions but I am quite new to python an already searched for 5h today and I really do ot know where to start anymore. I would be really happy if someon could help me. Thank you so much in advance <3
I found the answer to my original question in this post:
Coordinates of the edges of a honeycomb grid in python
Will update if I am finished with the class-thing :)
Example:
import time
# [...]
for x in range(3):
x = "Loading" + "."
print(x, end="\r")
x += 1
time.sleep(1.2)
I tried to make a loading bar and i got this error:
x += 1
TypeError: can only concatenate str (not "int") to str
I want this output:
>>>Loading.
>>>Loading..
>>>Loading...
What do I do?
for x in range(3):
x = "Loading" + "."
print(x, end="\r")
x += 1
You need to return to your tutorial materials and learn how to use your basic programming building blocks. First of all, you have given the name x to two different programming ideas; this is the main source of your trouble.
In the for statement, you say that you want x to be a counter from 0 through 2.
In the final statement of the loop, you insist that you will control the value of x in a different way.
In the other two statements, you say that you want x to be the string Loading.
You cannot have all of this at once. Please see How do Python variables work?.
Instead,
get your concepts straight, and use a separate variable for each concept;
give each concept a meaningful name;
learn to trace your own work -- See this lovely debugging site for help.
Here's a starting point:
bar = "Loading"
for count in range(3):
bar += '.' # Append one more dot to the bar
print(bar, end='\r')
There is more work to do; I leave that up to you.
What do you mean by x+=1?
If you want to add 1 as a character do x+=str(1)
If you want to add a dot do x+='.'
zazz and 9769953 already provided the fix, but you'll actually have to make some slight changes to your existing code to implement the fix correctly. Here's an example:
import time
# [...]
x = "Loading" # move outside the loop so we don't overwrite it
for _ in range(3): # the loop variable isn't used, so use `_`
x += "." # append a dot to `x`
print(x, end="\r")
time.sleep(1.2)
So, I'm brand new to programming, and this is frustrating me! What I want to do is be able to import a 4x8 text file, and turn the text into a 2D list so that I can swap two characters. For example, if the imported text file looks like this:
OOOOOOOO
OOOXOOOO
OOOOOOOO
OOOOOOOO
then I would like to be able to change the position of the X (the row/column location) when user input is entered, such that an O will get put in its place to preserve formatting. So, for exapmle, the program will prompt the user for their input and if the user enters "up," then the X will move one space up.
OOOXOOOO
OOOOOOOO
OOOOOOOO
OOOOOOOO
I want it to repeatedly prompt for a new move after each time one is made, and display the new grid each time (so you can see the X in its new position each time you enter a movement).
This is all I have so far. I know I need to first find the X, but I really don't know how to. I'm stuck here. Any help is appreciated.
#Global variables for the movements
UP = 8
DOWN = 2
RIGHT = 6
LEFT = 4
#Dimensions of grid
ROWS = 4
COLUMNS = 8
def start():
filename = input("Enter the name of the Start Positions file: ")
textFile = open(filename)
aMaze = [line.strip() for line in textFile]
for r in range(ROWS):
for c in range(COLUMNS):
print(aMaze[r][c], end="")
print()
def moveType():
while (True):
try:
move = input("ENTER YOUR MOVE: ")
except ValueError:
print("unimportant error message")
continue
if ((int(move)) in (DOWN, LEFT, RIGHT, UP)):
playerMove(move)
continue
else:
print("unimportant error message")
continue
return(move)
def playerMove(move):
move = (int(move))
if (move == DOWN):
#need help here
elif (move == UP):
#and here
elif (move == LEFT):
#don't know what i'm doing
elif (move == RIGHT):
#also here
start()
moveType()
This is a perfect opportunity to learn about abstraction. To solve your problem, think about the sub problems you could solve (with functions) that would make your final problem easier.
In your specific instance, wouldn't it be easier to write a program to find the Cartesian coordinates of where X is? With an (x,y) coordinate, you could then make a function to turn that coordinate (likely stored as a tuple) into a 2d array where that coordinate is an X an everything else is a zero.
Hint 1:
x =0
y =0
for row in numrows:
for col in numcols:
if array[row][col] == X
y = row
x = col
Hint 2:
for row in numrows:
for col in numcols:
if col is x and row is y:
place X
else:
place O
Note: if this were an application where you wanted to eek out every bit of performance, you certainly would not need to iterate through your array every time to find X. You could (and should) opt to store the location of X and then use two accesses into your array to flip X's and O's. But seeing as this is likely one of your first problems you are solving this is of course not a concern.
Hope this helps! Good luck starting to code!
I have a simple question.
Here is my story game so far:
x = 0
y = 0
coords = (x,y)
def move(player) :
while 1 :
global x
global y
global coords
user_in = raw_input()
if user_in == "w":
y += 1
elif user_in == "d":
x += 1
elif user_in == "a":
x -= 1
elif user_in == "s":
y -= 1
else :
print "Thats not an assigned key"
coords = (x,y)
print player, "moved to", coords
move("Mason")
I know that I could make an if statement for each set of coordinates, but I'm feeling pythonic, and I would like to find a fast and efficient way to do this. Thanks in advance for the help!
Like #isedev said in a comment, I recommend using a dictionary that maps location tuples to data about what is found in that location.
I would make a class called Room or Area that defines what exists at that location. Then make a dictionary called world or something that maps all the locations a player can go. If there is no Area object at a given location, then it is impossible to go there (maybe it's impassible forest, solid rock, or whatever makes sense in your game).
I suggest you read through a tutorial on how to write an adventure game in Python. The book Learn Python the Hard Way has a chapter devoted to this, and you can get that book for free on the Internet:
http://learnpythonthehardway.org/book/ex43.html
It might make more sense if you read through the whole book in order.
If you don't like that one, try a Google search for "adventure game tutorial Python" and you will find others.
Good luck and have fun.
I am working on a python tetris game that my proffessor assigned for the final project of a concepts of programming class. I have got just about everything he wanted to work on it at this point but I am having a slight problem with one part of it. Whenever I start moving pieces left and right I keep getting "index out of range error". This only happens when it is up against a piece. Here are the culprits that are giving me grief.
def clearRight(block=None):
global board, activeBlock, stackedBlocks
isClear = True
if(block == None):
block = activeBlock
if(block != None):
for square in block['squares']:
row = square[1]
col = square[0]+1
if(col >= 0 and stackedBlocks[row][col] !=None):
isClear=False
return isClear
def clearLeft(block=None):
global board, activeBlock, stackedBlocks
isClear = True
if(block == None):
block = activeBlock
if(block != None):
for square in block['squares']:
row = square[1]
col = square[0]-1
if(col >= 0 and stackedBlocks[row][col] !=None):
isClear=False
return isClear
I am not looking to get anyone to fix it for me, I'm only looking for tips on how to fix it myself. Thanks in advance for any help that is given.
There a typo that would cause that problem in the first method.
When you're checking each cell in the block shifted one right, you don't check if they are off the grid.
if (col >= 0 and ...)
probably should be
if (col < num_cols and ...)
I also agree with CrazyDrummer, make a generic clear function
Spoilers ...
def clear(x_offset, block=None):
if not block:
block = activeBlock
if not block: return True
for x,y in block:
x += x_offset
if not (0 <= x < num_cols) or stackedBlocks[x, y]:
return False
return True
Look at what's different when you're getting the exception. Try printing out program state information to help you zero in. There's only one place where you access an array with variable indexes, so you can narrow your search radius a bit.
Separate suggestion: Make a generic clear that takes determines what direction you want to clear from by the parameters.
I highly recommend the book debugging rules!, it will aid you in searching out and properly fixing problems. :D