Use all coordinates in a grid except with certain value - python

For a minesweeper I have created a board using python and pygame. When you flagged all bombs, you win. I have separate functions that contain the (randomised) bomb positions, and create the numbers around the bombs(on the proper coordinates). How do I make sure it checks the coordinates 0 to GRID_TILES(the maximum range) with the exception of all bomb locations? As those should remain flagged.
I got a function where when you click a bomb, you get shown the entire board. I want the same except for when the coordinates are in my BOMBS[].
def show_board():
for x in range(0,GRID_TILES):
for y in range(0, GRID_TILES):
"when" not in BOMBS:
draw_item(CELLS[x][y], x, y, (x+1,y+1))
I want to know if there is a "when" function, and how I could implement it.

If I understand you correctly, then the following should work:
If BOMBS is a list of tuples, then the following test should work if (x, y) not in BOMBS:
The in operator works on lists, as well as dicts, sets and tuples - anything that's iterable actually. In general, using it on lists is not such a great idea, because it needs to look through the whole list, in the worst case, to find an element. But for such small lists, it should not be a problem. If you find that it is, make BOMBS be a set and you should be good.

Related

I want to make sure the code below includes sequences

def reset_score(game):
time.sleep(0.5) # the snake freezes for a moment when hitting a wall then the game resets
head.goto(0, 0)
head.direction = "stop"
score = 0
# I could not find a way to remove the tails once the snake hit the wall
# so I moved the tail to somewhere in the screen that is not visible____This is called creativity
for game in snake_tail:
game.goto(1000, 1000)
score_printer.clear()
score_printer.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("italic", 24, "normal"))
snake_tail.clear()
is "game.goto(1000,1000)" a tuple? or does this code include any other sequence. I am really not sure about a clear definition of sequence so I am not sure whether these are sequences or not?
Let's try to understand Sequence in brief, The main sequence types in Python are lists, tuples, and range objects. The main differences between these sequence objects are:
Lists are mutable and their elements are usually homogeneous (things of the same type making a list of similar objects)
Tuples are immutable and their elements are usually heterogeneous (things of different types making a tuple describing a single structure)
Range objects are efficient sequences of integers (commonly used for loops), use a small amount of memory, and yield items only when needed.
Also regarding game.goto(), goto() is used to move the turtle(pre-installed Python library that enables users to create pictures and shapes by providing them with a virtual canvas) at x and y coordinates.
I hope it is understandable now.

How can I access lists that are generated within a function?

So I'm a bit stuck with some python homework... this is my first question btw sorry if it's formatted wrong.
There is a function "co-ordinates_generator()" that produces a list of co-ordinates, [[x, y], [x, y], [x, y]] etc.
I must create a function that draws upon these co-ordinates and prints pins onto a map accordingly, using those co-ordinates.
I thought I could achieve this by doing:
def place_coords():
for point in co-ordinates_generator():
if point[0] == '1':
place_pin() etc. etc....
This DOES work, however when I do this, the lists produced by "co_ordinates_generator()" are generated TWICE. So in other words, two lists are printed to my screen instead of just a single one that I am supposed to use.
My only assumption is that because in the part:
for point in co-ordiantes_generator():
I call upon co-ordinates_generator() and doing so triggers the function, causing it print and then also print again when I call place_coords(). Is this correct
If so, or otherwise, how would I go about fixing this? I've tried just deleting the "for _ in ____" part entirely but then that creates all sorts of troubles like "'pin' is not defined". And also the fact that I've written a whole heap of for-each loops based around using the "for _ in ___" part.
Sorry it's a long one! And thank you in advance.
In absence of your function I guess you are not returning any value from the function.
def co-ordinates_generator():
.... # your existing code
.... # your existing code
.... # your existing code
return co-ordiantes_variable # whatever name you have defined for the desired result.
result = co-ordinates_generator()
for point in result:
.... # your existing code
.... # your existing code
.... # your existing code

Why use List instead of Tuple to represent a game board?

In the Tetris game in the PyGame book, they create a board using:
board = []
for i in range(BOARDWIDTH):
board.append([BLANK] * BOARDHEIGHT)
return board
While that's fine, a list of lists, I was thinking about how they usually represent that in Java and other languages, as an array with set index - for example, int board[][] = new int[8][8]; // create 64 integers (a 2d array example).
From what I understand, tuples are more similar to the array (vs List which is more like ArrayList or LinkedList of Java). They have set number of elements and can't be added to, and hold a set number of items.
Why would we not create a tuple of tuples for a board, for example
board = ( (BLANK,)*10 ,)*10
Do they use lists of lists for some optimization in Python's internal representation of the board, or just because they assume users know List more commonly than Tuple?
This has the added benefit of being functional and making immutable objects. If you want to make a board with a state in which you moved in tic tac toe for example, you could try something like:
tictac = ((0,0,0),)*3
vals = (tuple((tictac[r][c]) if r!=1 or c!=1 else 'x' for (r,row) in enumerate(tictac)) for c in range(3))
for i in vals: print i
to move a 1 to the center.
List comprehensions are quite flexible in Python and this is more functionally-correct.
The difference between list and tuple in python is that tuple is immutable. That's why you can't change the size of a tuple (since you can't change it at all).
So the reason one normally would chose a list in this case is that you normally want to change the contents of the game board.
The benefits of having a matrix of fixed size may be slim. One could of course argue that one might get some performance benefit, but AFAIK the built in types are anyway of dynamic size in the sense that the size is determined at runtime and each time you access the container. In this aspect the list and tuple does not differ, that is when you write board[3][4] python would first access board check if it's length is larger than 3 so it can deliver the [3] element, then that element happens to be a list/tuple which is then checked for it size so it's larger than 4 so it can deliver the [4] element.
One could also argue that it would be for safety reasons or that it's "good practice" to not allow the board to be resized, and I could agree on that. What one then would do to allow modification is to wrap it all in a class that doesn't allow for resizing. One should bear in mind however that python doesn't provide very hard protection of classes that prohibit you from fiddling with internals - rather python trusts the programmer to not doing ugly things instead of trying to forbid.

Python recursive call for list elements

I've tried to create a rough implementation of g-means to break a sample down into clusters where the clusters are gaussian using recursion, but my program seems to be going in only one direction (downward). The input values of this method were a data set, X, and a list of centers.
I'm having trouble figuring out how to solve the recursive bit of this method (the last for loop and beyond). After all of the recursive calls, I want to have a list of centers in C that can be returned to the main method.
So here's what happens in the last for loop. I'm iterating through a list of clusters (found using my cluster centers), clust, that contain all the values in each cluster. I run a test to see if there is significant evidence that the values in each cluster are gaussian. If there is evidence, then I want to remove that cluster center and add two new centers above and below. I then want to run through another recursive call and then evaluate these new center to see if the clusters they match to are gaussian or not.
The problem is my program is only evaluating the lower center bound. It seems to never reach the upper center as though the return statement means the program will stop the upper center from ever being reached.
Does anyone know how I can get my method to cover both the lower and upper sides of the cluster? (The for loop usually only makes 1 iteration ( for i in range(len(clust))) even when the length of clust = 2.
Another problem I'm having is that my method is simply overwriting the centers list instead of adding to it with each recursive call. Does anyone know how I can make recursive calls while appending to a list? I'm inserting items into the list and passing part of the list to a deeper level, but on return, I only get two values (both really low).
def gMean(X,C):
label=vq.kmeans2(X,np.array(C))
#take care of centers that do not match to clusters in kmeans2
while(len(set(range(len(C))))!=len(set((label[1])))):
emptyK=set(range(len(C)))- set(range(len(C))).intersection(set(label[1]))
emptyK=list(emptyK)
emptyK.reverse()
for i in range(len(emptyK)):
C.pop(emptyK[i])
label=vq.kmeans2(X,np.array(C))
#clust is a 2D list and holds all the values for given cluster
clust=[[] for x in range(max(label[1])+1)]
for i in range(len(label[1])):
for j in range(len(clust)):
if j==label[1][i]:
clust[j].append(X[i])
for i in range(len(clust)):
transClust=np.transpose(clust[i])
notGausFlag=False
for j in range(len(transClust)):
if stats.anderson(transClust[j])[1][2]<stats.anderson(transClust[j])[0]:
notGausFlag=True
if notGausFlag==True:
upper,lower=findCenter(clust[i],C[i])
C.pop(i)
C.insert(i,upper)
C.insert(i,lower)
for j in range(len(clust[i])):
clust[i][j]=clust[i][j].tolist()
clust[i]=np.array(clust[i])
return gMean(clust[i],C[i:i+2])
if notGausFlag==False:
return C
So I think I realize the error in my code I'm calling a recursive method and passing a cluster with two cluster centers, but when I go to step into the next level of the recursive loop, I only ever step in with the first center because the second one isn't reached in the for loop (for i in range(len(closet)):).
What I should have done was call the recursive method like this.
return gMean(clust[i],C[i])+gMean(clust[i],C[i+1])

How To Get A For Loop To Affect Each Individual Object

folks! My question deals with a Python exercise that I'm currently trying to work out (well, to be more specific, the program is Autodesk Maya, but I'm using Python coding). The exercise involves taking a number of objects (spheres) contained in an array/list, and then using an increment variable to have them move in an offset animation. In other words, I want the first sphere to move, then the next spheres to move in a delayed time, then the next sphere with a more delayed time, etc.
The code that I have is as follows:
spheres = mc.ls(selection=True)
count=0
for i in range(len(spheres)):
count+=2
mc.selectKey(spheres)
mc.keyframe(edit=True, relative=True, timeChange=count)
print spheres(i)
The spheres are my objects, and as I said, I want the first to move normally in the timeline, then the next sphere to move with a delayed time of two, then the next to move with a delayed time of four, so on and so forth.
Any help with this would be much appreciated.
Thanks,
E
You're not actually setting the keyframe on the individual sphere; it looks like you're setting it on all spheres
Your for loop is generally bad form, but also less useful. Try changing it to this:
spheres = mc.ls(selection=True)
count=0
for sphere in spheres:
count += 2
mc.selectKey(sphere) # only selecting the one sphere!
mc.keyframe(edit=True, relative=True, timeChange=count)
print sphere # no need to look up the element
# which by the way should have been [i] not (i)
Output:
The keyframes were all lined up originally, but now offset by two frames each from the previous.
You haven't told us what the problem is, but I have a guess. (If I've guessed wrong, please elaborate your question, and I'll delete my answer.)
Are you getting an exception like this?
TypeError Traceback (most recent call last)
----> 1 print spheres(i)
TypeError: 'list' object is not callable
You claim that you have an "array/list" of spheres. If spheres is a list (or array or almost any other kind of collection) you index it using the [] operator. The () operator is used for function calls, not indexing. You're trying to call that list as if it were a function, passing it i as an argument, instead of trying to access that list as a sequence, getting the ith element.
To fix it:
print spheres[i]

Categories