Checked if the coordinates of a position are within a boundaries - python

I have created a function that is trying to figure out if the coordinates of a position are within the checkerboard boundaries (between 0 inclusive and the number
Below is my attempt:
def position_is_in_game(self, position):
# Replace self with a Game type object
one_game = Game()
#Replace position with an object of type Position
one_position = Position()
return one_game.position_is_in_game(one_position)
I feel my code is incomplete.

Assuming that your Position and Piece functions are coded correctly, the issue lies within the checking algorithm's syntax.
Try it like this:
def position_is_in_game(position_tuple):
game = Game()
game_positions = game.cases.keys()
for i in game_positions:
if i == position_tuple:
return True
else:
return False

Here is how I would check to see if a position in on the gird:
class Game :
def __init__(self):
self.n_lignes = 8
self.n_colonnes = 8
def position_is_in_game(self, x, y):
return x > 0 and x < self.n_lignes and y > 0 and y < self.n_colonnes
mygame = Game ()
print (mygame.position_is_in_game(1, 8))

Related

Problem with passing parameters and scopes, how can I fix this?

I'm making a password generator and strength checker (I'm new to coding), and my problem is that I can't get a function working that generates a password, calls the function that checks the strength, and have the strength checking function return back to the generating function.
Sorry if that was a bad explanation, please check the code for clarification.
Everything I've tried has partially worked or not worked at all, including using globals; even then I couldn't get it functioning properly.
import random
allchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$%^&*()_-=+"
def generatePassword():
generatedPass = ""
while points < 20:
for i in range(random.randint(8, 12)):
generatedPass += random.choice(allchars)
checkFunc(generatedPass)
points = 0
print(generatedPass)
def checkFunc(password):
numberofTriples = 0
consecChars = []
points = 0
allCrit = 0
(Redacted code that just calculates the points of the password)
(Redacted code that just calculates the points of the password)
return points
I want it to take the password it randomly generates, and check its strength, if it falls under a certain point threshold, to generate another until it is above the threshold, and print it.
Your generatedPassword function doesn't ever set the value of points in the while loop, thus it is never failing the condition of points < 20.
You'd want to change checkFunc(generatedPass) to points = checkFunc(generatedPass). This will properly set the value of points, and break from the loop.
So here are couple issues with your code:
import random
allchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$%^&*()_-=+"
def generatePassword():
#note you should have initiated ***points*** to 0 before using it in your while loop
generatedPass = ""
while points < 20:
for i in range(random.randint(8, 12)):
generatedPass += random.choice(allchars)
checkFunc(generatedPass)
points = 0 #points here has no value assignment you want to assign checkFunc()'s return value to points like this: points = checkFunc(generatedPass), or else you'll have an infinite loop.
print(generatedPass)
def checkFunc(password):
numberofTriples = 0
consecChars = []
points = 0
allCrit = 0
## (Redacted code that just calculates the points of the password)
## (Redacted code that just calculates the points of the password)
#Just be sure you have points variable here being updated according to the strength before you return it.
Here is an example of the same code but instead of strength, we are checking length:
import random
allchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$%^&*()_-=+"
def generatePassword():
generatedPass = ""
points = 0
while points < 20:
for i in range(random.randint(8, 12)):
generatedPass += random.choice(allchars)
points = checkLength(generatedPass)
print(generatedPass)
def checkLength(password):
return len(password)
Input:
generatePassword()
Output:
1Aid0%7tZYo0Ip(u_zeCQo=I
I hope you are doing great.
Here is a corrected code that should work:
Corrections done:
points was not declared before usage
points were not updated after call of checkFunc
N.B: to simulate the computing of the score, I used the random function.
Here is the full code:
import random
allchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$%^&*()_-=+"
def generatePassword():
generatedPass = ""
# We set points to 0 to start the while loop
points = 0
while points < 20:
for i in range(random.randint(8, 12)):
generatedPass += random.choice(allchars)
# We set points to the score computed by checkFunc to know if we need to trigger the generation of a new password.
points = checkFunc(generatedPass)
print(generatedPass)
def checkFunc(password):
numberofTriples = 0
consecChars = []
points = 0
allCrit = 0
# Simulating point computation
points = random.randint(10,30)
return points
I hope it helps,
Have a lovely day,
G

Trying to properly iterate through pygame sprite group

So I am building a simple infinite run game for school and I am stuck on trying to spawn the obstacles. I am trying to check each obstacle sprite and if it has gone off the screen (the background and obstacles move from right to left). If it has gone off screen, I want to remove the sprite and set up another one on the right side of the screen. But every time an obstacle goes off the left side of the screen, an infinite amount of obstacles start spawning. I am new to pygame and python in general. Any help would be greatly appreciated. Thanks in advance.
def obstacle_off_screen(self):
numDeleted = 0
for cur_sprite in self.all_objects_list:
print("first loop")
if cur_sprite.rect.x < 0:
print("second")
cur_sprite.kill
numDeleted += 1
while numDeleted != 0:
print("third")
self.add_obstacle()
numDeleted -= 1
def add_obstacle(self):
#add parameters
if self.get_Speed() == 15:
x = 1000
y = 400
elif self.get_Speed() == 20:
x = 1000
y = 400
elif self.get_Speed() == 25:
x = 1000
y = 400
elif self.get_Speed() == 30:
x = 1000
y = 400
self.all_objects_list.add(Obstacle('src/paw.gif', [x, y]))
For now, I only have one obstacle that I initially spawn
cur_sprite.kill is a function, so when you want to call it use (), like cur_sprite.kill().
That's your problem. The obstacles out of screen don't get removed from their sprite groups.

addObject() in blender with python

I ran into a little wall here:
my point is, for a empty, to move, then add a plane on the spot, then move, then add a plane etc, and then will end up with a 100X100 plain, so i scripted:
import bge
dunWidth = 100 #meters/tiles
dunHeight = 100 #meters/tiles
b = 0
a = 0
add= bge.logic.getCurrentScene().addObject
def main():
global b, a
cont = bge.logic.getCurrentController()
dunMarker = cont.owner
#Movement Calculation: (X, Y, Z)
while b < dunWidth:
b += 1
add("FloorTile", "DunMarker",0)
dunMarker.applyMovement((1,0,0), False)
while a < dunHeight:
add("FloorTile", "DunMarker",0)
a += 1
dunMarker.applyMovement((0,1,0), False)
#dunMarker.applyMovement((0,-dunHeight,0), False)
main()
but instead, to my surprise, it First add the tile, then goes through the loop ignoring the add(), so the result is a 1x1 tile at 0x0y and the empty ends at 100x100y... how many things Im doing wrong here?Aaaand, since we are here, how would you improve the coding?(trying to learn here ;) )
pd, yeah, Roguelike 3D project
Try positioning dunMarker with worldPosition you may also want to use for loops to get a grid instead of two edges.
import bge
dunWidth = 100 #meters/tiles
dunHeight = 100 #meters/tiles
a=0
b=0
add= bge.logic.getCurrentScene().addObject
def main():
global a,b
cont = bge.logic.getCurrentController()
dunMarker = cont.owner
for b in range(0,dunWidth,2):
dunMarker.worldPosition=(b,a,0)
t=add("FloorTile", "DunMarker",0)
for a in range(0,dunHeight,2):
dunMarker.worldPosition = (b,a,0)
add("FloorTile", "DunMarker",0)
main()

Touring a chess board with multiple pieces [Python]

I have been trying to solve this for 2 days straight and I just can't find a valid algorithm. Given a Chess board, and a number of pieces, I have to check if said board can be toured by the pieces, with the condition that each piece can only visit an square once. I know it's some kind of multiple backtracking, but I can't get it to work. (I only have been able to implement a general knight's tour for individual pieces)
tablero is a class of the board, that holds a name, a list of pieces, a list with prohibited positions, a list with the free positions, and a tuple with the dimensions of the board.
ficha is the class of a piece, it holds a name (nombre), a tuple with its position (posicion), a list with its valid movements (movimientos) (For example, a pawn's list would be [ [0,1] ], meaning it can only move forward 1)
Any insight is welcome.
Here are the classes (Feel free to add/remove any method).
def legal(pos,dimensiones):
if pos[0] >= 0 and pos[0] < dimensiones[0] and pos[1] >= 0 and pos[1] < dimensiones[0]:
return True
else:
return False
class board:
def __init__(self,name,pieces,dimention,prohibited_positions):
self.name = name
self.pieces = pieces
self.dimention = dimention
self.prohibited_positions = prohibited_positions
self.free_positions = []
for x in range(dimention[0]):
for y in range(dimention[1]):
self.free_positions.append([x,y])
for x,y in self.prohibited_positions:
if [x,y] in self.free_positions:
self.free_positions.remove([x,y])
for piece in self.pieces:
if self.piece.position in self.free_positions:
self.free_positions.remove(piece.position)
def append(self,piece):
pos = piece.position
if pos in self.free_positions:
self.pieces.append(piece)
self.free_positions.remove(pos)
class piece:
def __init__(self,name,position,move_offsets):
self.name=name
self.position=position
self.move_offsets=move_offsets
self.possible_movements=move_offsets
def setPos(self,pos):
self.position=pos
def ValidMovements(self,dim,free_positions,prohibited_positions):
aux = []
for i in self.possible_movements:
newX = self.position[0] + i[0]
newY = self.position[1] + i[1]
newPos = [newX,newY]
if legal(newPos,dim):
aux.append(newPos)
for i in list(aux):
if i not in free_positions:
aux.remove(i)

Unexpected results in Conway's Game of Life

I have been trying to write my own version of Conway's Game of Life as practice for Python using Pygame. I first wrote the functions for initializing the game field, and then calculating the next generation. I verified it's functionality using the console to print the results and verify that they returned the expected results (just 2 generations deep by hand on a 5x5 grid).
An important note of how I am calculating the neighbors... Instead of doing a for loop through the entire array and doing for loops to count for each cell, I have implemented an array that holds the neighbor counts. Only making changes when a cells status is changed. This means I don't waste time calculating neighbors for cells that have not changed.
When it came time to use Pygame to display the array with rectangles, I wrote the following program. At first I was drawing the screen by filling in the entire screen white, and then drawing the live cells as black (this can be done by commenting out the else statement in update()). I expected this to work as normal, but when I ran the program all I ended up with was the screen filling in black.
I was perplexed by the result so i drew white rectangles for the unpopulated cells (using the else statement. And got a better looking result, but instead of the cells eventually all dying, they eventually multiplied across the whole screen. This is opposite of what I expected, as I was expecting it to eventually stabilize.
Anyone know what I am doing wrong? I know that this is not the best way of writing this program, I welcome comments of how I can make it better.
RETURN = run simulation
'R' = randomize
'T' = tick one generation
'C' = clear game field
'N' = display neighbor map
import pygame
from pygame.locals import *
import numpy as np
from random import *
import copy
fieldSize = [100,50]
cellSize = 10 # size of >10 is recommended to see neighbor count
windowSize = [fieldSize[0]*cellSize, fieldSize[1]*cellSize]
# calculate the last cell in each axis so it is not done repeatedly
lastCell = [(fieldSize[0]-1), (fieldSize[1]-1)]
dX = float(windowSize[0])/float(fieldSize[0])
dY = float(windowSize[1])/float(fieldSize[1])
colorAlive = [0,125,0]
colorDead = [0, 0, 0]
# todo list
# 1. make cLife take in the field size
# 2. convert random functions to numpy.random.randint
class cLife():
def randomize(self):
self.neighbors = np.zeros(fieldSize)
# fill in the game field with random numbers
for x in range(fieldSize[0]):
for y in range(fieldSize[1]):
if(randint(0,99)<20):
self.gameField[x][y] = 1
self.updateNeighbors([x,y], True)
else:
self.gameField[x][y] = 0
def displayNeighbors(self, surface):
self.drawField(surface)
for x in range(fieldSize[0]):
for y in range(fieldSize[1]):
neighborCount=font.render(str(int(self.neighbors[x][y])), 1,(200,200,200))
surface.blit(neighborCount, (x*dX+dX/3, y*dY+dY/3.5))
pygame.display.flip()
# This is the function to update the neighbor map, the game field is torroidal so the complexity is greatly
# increased. I have handcoded each instruction to avoid countless if statements and for loops.
# Hopefully, this has drastically improved the performance. Using this method also allows me to avoid calculating
# the neighbor map for every single cell because the neighbor map is updated only for the cells affected by a change.
def updateNeighbors(self, pos, status):
if(status == True):
change = 1
else:
change = -1
# testing for the cells in the center of the field (most cells are in the center so this is first)
# cells are filled in starting on the top-left corner going clockwise
if((pos[0]>0 and pos[0]<lastCell[0])and(pos[1]>0 and pos[1]<lastCell[1])):
self.neighbors[pos[0]-1][pos[1]-1] += change
self.neighbors[pos[0]][pos[1]-1] += change
self.neighbors[pos[0]+1][pos[1]-1] += change
self.neighbors[pos[0]+1][pos[1]] += change
self.neighbors[pos[0]+1][pos[1]+1] += change
self.neighbors[pos[0]][pos[1]+1] += change
self.neighbors[pos[0]-1][pos[1]+1] += change
self.neighbors[pos[0]-1][pos[1]] += change
elif(pos[0] == 0): # left edge
if(pos[1] == 0): # top left corner
self.neighbors[lastCell[0]][lastCell[1]] += change
self.neighbors[0][lastCell[1]] += change
self.neighbors[1][lastCell[1]] += change
self.neighbors[1][0] += change
self.neighbors[1][1] += change
self.neighbors[0][1] += change
self.neighbors[lastCell[0]][1] += change
self.neighbors[lastCell[0]][0] += change
elif(pos[1] == lastCell[1]): # bottom left corner
self.neighbors[lastCell[0]][pos[1]-1] += change
self.neighbors[0][pos[1]-1] += change
self.neighbors[1][pos[1]-1] += change
self.neighbors[1][pos[1]] += change
self.neighbors[1][0] += change
self.neighbors[0][0] += change
self.neighbors[lastCell[0]][0] += change
self.neighbors[lastCell[0]][pos[1]] += change
else: # everything else
self.neighbors[lastCell[0]][pos[1]-1] += change
self.neighbors[0][pos[1]-1] += change
self.neighbors[1][pos[1]-1] += change
self.neighbors[1][pos[1]] += change
self.neighbors[1][pos[1]+1] += change
self.neighbors[0][pos[1]+1] += change
self.neighbors[lastCell[0]][pos[1]+1] += change
self.neighbors[lastCell[0]][pos[1]] += change
elif(pos[0] == lastCell[0]): # right edge
if(pos[1] == 0): # top right corner
self.neighbors[pos[0]-1][lastCell[1]] += change
self.neighbors[pos[0]][lastCell[1]] += change
self.neighbors[0][lastCell[1]] += change
self.neighbors[0][0] += change
self.neighbors[0][1] += change
self.neighbors[pos[0]][1] += change
self.neighbors[pos[0]-1][1] += change
self.neighbors[pos[0]-1][0] += change
elif(pos[1] == lastCell[1]): # bottom right corner
self.neighbors[pos[0]-1][pos[1]-1] += change
self.neighbors[pos[0]][pos[1]-1] += change
self.neighbors[0][pos[1]-1] += change
self.neighbors[0][pos[1]] += change
self.neighbors[0][0] += change
self.neighbors[pos[0]][0] += change
self.neighbors[pos[0]-1][0] += change
self.neighbors[pos[0]-1][pos[1]] += change
else: # everything else
self.neighbors[pos[0]-1][pos[1]-1] += change
self.neighbors[pos[0]][pos[1]-1] += change
self.neighbors[0][pos[1]-1] += change
self.neighbors[0][pos[1]] += change
self.neighbors[0][pos[1]+1] += change
self.neighbors[pos[0]][pos[1]+1] += change
self.neighbors[pos[0]-1][pos[1]+1] += change
self.neighbors[pos[0]-1][pos[1]] += change
elif(pos[1] == 0): # top edge, corners already taken care of
self.neighbors[pos[0]-1][lastCell[1]] += change
self.neighbors[pos[0]][lastCell[1]] += change
self.neighbors[pos[0]+1][lastCell[1]] += change
self.neighbors[pos[0]+1][0] += change
self.neighbors[pos[0]+1][1] += change
self.neighbors[pos[0]][1] += change
self.neighbors[pos[0]-1][1] += change
self.neighbors[pos[0]-1][0] += change
elif(pos[1] == lastCell[1]): # bottom edge, corners already taken care of
self.neighbors[pos[0]-1][pos[1]-1] += change
self.neighbors[pos[0]][pos[1]-1] += change
self.neighbors[pos[0]+1][pos[1]-1] += change
self.neighbors[pos[0]+1][pos[1]] += change
self.neighbors[pos[0]+1][0] += change
self.neighbors[pos[0]][0] += change
self.neighbors[pos[0]-1][0] += change
self.neighbors[pos[0]-1][pos[1]] += change
def nextGeneration(self):
# copy the neighbor map, because changes will be made during the update
self.neighborsOld = copy.deepcopy(self.neighbors)
for x in range(fieldSize[0]):
for y in range(fieldSize[1]):
# Any live cell with fewer than two live neighbours dies, as if caused by under-population.
if(self.gameField[x][y] == 1 and self.neighborsOld[x][y] < 2):
self.gameField[x][y] = 0
self.updateNeighbors([x,y], False)
# Any live cell with more than three live neighbours dies, as if by overcrowding.
elif(self.gameField[x][y] == 1 and self.neighborsOld[x][y] >3):
self.gameField[x][y] = 0
self.updateNeighbors([x,y], False)
# Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
elif(self.gameField[x][y] == 0 and self.neighborsOld[x][y] == 3):
self.gameField[x][y] = 1
self.updateNeighbors([x,y], True)
def drawField(self, surface):
surface.fill(colorDead)
# loop through and draw each live cell
for x in range(fieldSize[0]):
for y in range(fieldSize[1]):
if(self.gameField[x][y] == 1):
pygame.draw.rect(surface, colorAlive, [dX*x, dY*y, dX, dY])
pygame.display.flip()
def __init__(self):
# initialize the game field and neighbor map with zeros
self.gameField = np.zeros(fieldSize)
self.neighbors = np.zeros(fieldSize)
# begining of the program
game = cLife()
pygame.init()
surface = pygame.display.set_mode(windowSize)
pygame.display.set_caption("Conway\'s Game of Life")
clock = pygame.time.Clock()
pygame.font.init()
font=pygame.font.Font(None,10)
surface.fill(colorDead)
game.randomize()
game.drawField(surface)
pygame.display.flip()
running = False
while True:
#clock.tick(60)
# handling events
for event in pygame.event.get():
if(event.type == pygame.MOUSEBUTTONDOWN):
mousePos = pygame.mouse.get_pos()
x = int(mousePos[0]/dX)
y = int(mousePos[1]/dY)
if(game.gameField[x][y] == 0):
game.gameField[x][y] = 1
game.updateNeighbors([x, y], True)
game.drawField(surface)
else:
game.gameField[x][y] = 0
game.updateNeighbors([x, y], False)
game.drawField(surface)
elif(event.type == pygame.QUIT):
pygame.quit()
elif(event.type == pygame.KEYDOWN):
# return key starts and stops the simulation
if(event.key == pygame.K_RETURN):
if(running == False):
running = True
else:
running = False
# 't' key ticks the simulation forward one generation
elif(event.key == pygame.K_t and running == False):
game.nextGeneration()
game.drawField(surface)
# 'r' randomizes the playfield
elif(event.key == pygame.K_r):
game.randomize()
game.drawField(surface)
# 'c' clears the game field
elif(event.key == pygame.K_c):
running = False
game.gameField = np.zeros(fieldSize)
game.neighbors = np.zeros(fieldSize)
game.drawField(surface)
# 'n' displays the neighbor map
elif(event.key == pygame.K_n):
game.displayNeighbors(surface)
if(running == True):
game.nextGeneration()
game.drawField(surface)
self.neighborsOld = self.neighbors does not copy the map, it only points to it.
See :
a = [[1,2],[3,4]]
b = a
b[0][0] = 9
>>> a
[[9, 2], [3, 4]]
You need to either make a copy (a[:]) for every row in a, or use the copy module and use deepcopy:
b = [x[:] for x in a]
or
import copy
b = copy.deepcopy(a)
Either way, it results in
b[0][0] = 9
>>> a
[[1, 2], [3, 4]]

Categories