Pygame displays black screen [duplicate] - python

This question already has answers here:
Why is nothing drawn in PyGame at all?
(2 answers)
Why is my PyGame application not running at all?
(2 answers)
Closed 2 years ago.
I'm trying to write a simple sokoban game in python 3.5 using Pygame, however when I run the code I just get a black background. I'm sure I'm just doing something wrong with the blit but still learning so not too sure.
Any help anyone can give would be greatly appreciated :)
import random, pygame, sys
from pygame.locals import *
from Classes import Maze, Move, Player, Box
maze = Maze()
WHITE = (255, 255, 255)
FPS = 30
WINWIDTH = 750
WINHEIGHT = 750
HALFHEIGHT = int(WINWIDTH/2)
HALFWIDTH = int(WINWIDTH/2)
#BASICFONT = pygame.font.Font('freesansbold.tff',100)
#Tile height and width in pixels
TILEWIDTH = 30
TILEHEIGHT = 30
TILEFLOORHEIGHT = 30
IMAGESDICT = {"WALL": pygame.image.load("C:/Users/Trail/Documents/College 2/Object Oriented Programming/Sokoban Implement/images/wall.bmp"),
"FLOOR": pygame.image.load(""C:/Users/Trail/Documents/College 2/Object Oriented Programming/Sokoban Implement/images/floor.bmp"),
"CRATE": pygame.image.load(""C:/Users/Trail/Documents/College 2/Object Oriented Programming/Sokoban Implement/images/object.bmp"),
"TARGET": pygame.image.load("C:/Users/Trail/Documents/College 2/Object Oriented Programming/Sokoban Implement/images/wall.bmp"object_store),
"PLAYER": pygame.image.load("C:/Users/Trail/Documents/College 2/Object Oriented Programming/Sokoban Implement/images/mover_left.bmp")}
TILEMAPPING = {"#":IMAGESDICT["WALL"],
" ":IMAGESDICT["FLOOR"],
"$":IMAGESDICT["CRATE"],
"#":IMAGESDICT["TARGET"],
"P":IMAGESDICT["PLAYER"]}
#Display surface
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAY = pygame.display.set_mode((WINWIDTH,WINHEIGHT))
pygame.display.set_caption("Sokoban")
def Build(maze):
maze.walls(10)
maze.targets(5)
maze.startPos()
mapSurfWidth = maze.getWidth() * TILEWIDTH
mapSurfHeight = maze.getHeight() * TILEHEIGHT
mapSurf = pygame.Surface((mapSurfWidth,mapSurfHeight))
mapSurf.fill(WHITE)
for h in range(maze.getHeight()):
for w in range(maze.getWidth()):
tile = pygame.Rect((w * TILEWIDTH, h * TILEFLOORHEIGHT, TILEWIDTH, TILEHEIGHT))
if maze.getPos(h,w) in TILEMAPPING:
baseTile = TILEMAPPING[maze.getPos(h,w)]
#Draw
mapSurf.blit(baseTile,tile)
return mapSurf
def main():
Build(maze)
main()
And my Maze class (This is indented in my code but not here for formatting):
class Maze:
def __init__(self):
self.width = 20
self.height = 10
#init
width = 20
height = 10
#Create 2D array for maze
self.maze = [[0 for i in range(width)] for j in range(height)]
#Create square grid
for i in range(width):
for j in range(height):
if j == 0 or j == height - 1:
self.maze[j][i] = "#"
elif i == 0 or i == width - 1:
self.maze[j][i] = "#"
else:
self.maze[j][i] = " "
def crates(self,level):
self.level = level
for i in range(0,level):
#Don't spawn here if wall is already generated
if self.maze[i+2][i+5] == "#":
self.maze[i+3][i+6] = "$"
else:
self.maze[i+2][i+5] = "$"
return self.maze
def walls(self,level):
self.level = level
#Semi working, needs randomised for play
for i in range(0,level):
for j in range(0,level):
#Shitty random gen
y = level / 2
x = randint(0,level)
y = randint(0,y)
#Shitty test random wall gen
if x % 3 == 0:
self.maze[y][x] = "#"
"""if (j % 3 == 0) and (i < 4):
self.maze[j][i] = "#"
elif (j % 2 == 0) and (i > 8):
self.maze[i][j] = "#"""
return self.maze
def targets(self,level):
self.level = level
#Test
for i in range(0,level):
self.maze[i+2][i+10] = "#"
return self.maze
def startPos(self):
x = randint(1,5)
y = randint(1,5)
self.maze[x][y] = "P"
return self.maze
def getWidth(self):
return self.width
def getHeight(self):
return self.height
def getPos(self,row,col):
return self.maze[row][col]

Related

Conway's Game of Life Python / PyGame printing error [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm new to python and PyGame and wanted to get some experience by doing what i thought would be a simple project. I can't tell if my error is in my game logic or my PyGame printing. I created two function, one that fills the grid with random values and one that fills the grid with a "Blinker". The program runs without error, however, the rules of the game are not followed. For example, When the "blinker" is set, the program's second frame clears the screen instead of rotating the "blinker".
Any help diagnosing this problem would be appreciated!
import pygame
import random
pygame.init()
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Sizes
size = (600, 600)
width = 20
height = 20
margin = 1
x_size = 600 / width
y_size = 600 / height
def init_grid():
return [[0 for x in range(x_size)] for y in range(y_size)]
def make_spinner(grind):
grid[0][0] = 1
grid[10][10] = 1
grid[10][11] = 1
grid[10][12] = 1
def random_grid(grid):
for x in range(x_size):
for y in range(y_size):
grid[x][y] = random.randint(0, 1)
def print_grid(screen, grid):
for x in range(x_size):
for y in range(y_size):
if grid[x][y] == 1:
pygame.draw.rect(
screen, BLACK, (x * width, y * height, width, height))
else:
pygame.draw.rect(
screen, BLACK, (x * width, y * height, width, height), margin)
def count_neighbours(grid, x, y):
count = 0
for i in range(-1, 1):
for j in range(-1, 1):
count += grid[x + i][y + j]
return count - grid[x][y]
def update_grid(grid):
next_grid = init_grid()
for x in range(x_size):
for y in range(y_size):
if x == 0 or x == x_size - 1 or y == 0 or y == y_size - 1:
next_grid[x][y] = 0
else:
count = count_neighbours(grid, x, y)
value = grid[x][y]
if value == 1 and (count == 2 or count == 3):
next_grid[x][y] = 1
elif value == 0 and count == 3:
next_grid[x][y] = 1
else:
next_grid[x][y] = 0
return next_grid
# Initialise game engine
screen = pygame.display.set_mode(size)
pygame.display.set_caption("The Game of Life")
running = True
clock = pygame.time.Clock()
grid = init_grid()
# random_grid(grid)
make_spinner(grid)
# Game loop
while running:
# Check for exit
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(WHITE)
print_grid(screen, grid)
next_grid = update_grid(grid)
pygame.display.update()
grid = next_grid
clock.tick(2)
pygame.quit()
Your count_neighbors function doesn't iterate over the right cells. range(-1,1) iterates over {-1,0} not {-1,0,1}.
Instead, use:
def count_neighbours(grid, x, y):
count = 0
for i in range(-1,2):
for j in range(-1,2):
count += grid[x + i][y + j]
return count - grid[x][y]

The Pipes in my Pygame Flappy Bird clone lag and jolt around instead of moving fluidly

Below is the basic code for creating and managing the pipes of the game:
import pygame as pg
import sys,os,math,time,random
# colours
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
# general stuff
WIDTH = 1024
HEIGHT = 576
FPS = 60
# other
all_events = [pg.QUIT, pg.ACTIVEEVENT, pg.KEYDOWN, pg.KEYUP, pg.MOUSEMOTION,
pg.MOUSEBUTTONUP, pg.MOUSEBUTTONDOWN, pg.VIDEORESIZE,
pg.VIDEOEXPOSE, pg.USEREVENT]
pg.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
clock = pg.time.Clock()
# Class to manage Pipes
class Pipe_Manager:
def __init__(self):
self.pipe_width = 50
self.pipes = []
self.pipe_speed = 5
self.max_tick = 75
self.spawn_tick = self.max_tick
def manage_pipes(self):
self.spawner()
self.manage()
self.display()
def make_pipe(self):
height = random.randint(100,326)
gap = random.randint(100,250)
surf1 = pg.Surface((self.pipe_width, height))
surf1.fill(green)
surf2 = pg.Surface((self.pipe_width, HEIGHT - (height + gap)))
surf2.fill(green)
# surface, (x,y) and vertical height
pipe = [surf1, [WIDTH, 0], height]
pipe2 = [surf2, [WIDTH, height + gap], HEIGHT - (height + gap)]
self.pipes.append(pipe)
self.pipes.append(pipe2)
def spawner(self):
if self.spawn_tick == self.max_tick:
self.make_pipe()
self.spawn_tick = 0
self.spawn_tick += 1
def manage(self):
for pipe in self.pipes:
# move the pipe
pipe[1][0] -= self.pipe_speed
# check if it's off screen
if pipe[1][0] + self.pipe_width < 0:
self.pipes.remove(pipe)
def display(self):
for pipe in self.pipes:
screen.blit(pipe[0], (pipe[1][0], pipe[1][1]))
################################################################################
pg.event.set_blocked(all_events)
pg.event.set_allowed([pg.QUIT, pg.KEYDOWN])
pipe_manager = Pipe_Manager()
loop = True
while loop:
screen.fill(white)
pipe_manager.manage_pipes()
pg.display.update()
clock.tick(FPS)
The pipes seem to shake as they move horizontally and sometimes the top pipe becomes misaligned from the bottom one.
I hope this isn't a problem specific to my computer because I have abstracted away a significant amount of my flappy-bird-clone code and the source of this pipe lag problem must lie somewhere in here.
The problem is this piece of code:
for pipe in self.pipes:
# move the pipe
pipe[1][0] -= self.pipe_speed
# check if it's off screen
if pipe[1][0] + self.pipe_width < 0:
self.pipes.remove(pipe)
Here you change the list you're currently iterating over. Once a pipe gets removed from the list, the next one misses one movement step.
Take a look at the following example in which you can spot the problem yourself (see how 5 is missing in the output because we removed 4):
>>> l = [1,2,3,4,5,6,7,8,9,10]
>>> for x in l:
... if x == 4:
... l.remove(x)
... print(x)
...
1
2
3
4
6
7
8
9
10
>>>
(There's a reason other languages forbid changing the sequence you're currently iterating).
A simple fix is to make a copy of the list first:
for pipe in self.pipes[:]:
For smoother movement, try increasing your framerate and use timestepping.
Here's a possible way:
import pygame as pg
import sys,os,math,time,random
# colours
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
# general stuff
WIDTH = 1024
HEIGHT = 576
FPS = 120
# other
all_events = [pg.QUIT, pg.ACTIVEEVENT, pg.KEYDOWN, pg.KEYUP, pg.MOUSEMOTION,
pg.MOUSEBUTTONUP, pg.MOUSEBUTTONDOWN, pg.VIDEORESIZE,
pg.VIDEOEXPOSE, pg.USEREVENT]
pg.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
clock = pg.time.Clock()
class Pipe:
def __init__(self, img, pos):
self.img = img
self.pos = pos
# Class to manage Pipes
class Pipe_Manager:
def __init__(self):
self.pipe_width = 50
self.pipes = []
self.pipe_speed = 0.3
self.max_tick = 1500
self.spawn_tick = self.max_tick
def manage_pipes(self, dt):
self.spawner(dt)
self.manage(dt)
self.display()
def make_pipe(self):
height = random.randint(100,326)
gap = random.randint(100,250)
surf1 = pg.Surface((self.pipe_width, height))
surf1.fill(green)
surf2 = pg.Surface((self.pipe_width, HEIGHT - (height + gap)))
surf2.fill(green)
pipe = Pipe(surf1, pg.Vector2(WIDTH, 0))
pipe2 = Pipe(surf2, pg.Vector2(WIDTH, height + gap))
self.pipes.append(pipe)
self.pipes.append(pipe2)
def spawner(self, dt):
if self.spawn_tick >= self.max_tick:
self.make_pipe()
self.spawn_tick = 0
self.spawn_tick += dt
def manage(self, dt):
for pipe in self.pipes[:]:
# move the pipe
pipe.pos.x -= self.pipe_speed * dt
# check if it's off screen
if pipe.pos.x + self.pipe_width < 0:
self.pipes.remove(pipe)
def display(self):
for pipe in self.pipes:
screen.blit(pipe.img, pipe.pos)
################################################################################
pg.event.set_blocked(all_events)
pg.event.set_allowed([pg.QUIT, pg.KEYDOWN])
pipe_manager = Pipe_Manager()
loop = True
dt=0
while loop:
for e in pg.event.get():
if e.type == pg.QUIT:
loop = False
screen.fill(white)
pipe_manager.manage_pipes(dt)
pg.display.update()
dt=clock.tick(FPS)

moving an object in a circular path [duplicate]

This question already has answers here:
Why it doesn't spin in a circle? And how to fix it?
(1 answer)
Ship moves up and left faster than down and right when rotating in pygame
(1 answer)
Closed 2 years ago.
This question is related to
My code is below. You can use any small image for my images.
import sys, os, pygame, itertools
from math import sin,cos,pi, radians
from pygame.locals import *
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50) #Set window position
pygame.init()
clock = pygame.time.Clock()
FPS = 1000
SCREENW = 800 #screen width
SCREENH = 740 #screen height
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
ORANGE = (128, 100, 30)
FONT1= "Cookie-Regular.ttf"
SCREEN = pygame.display.set_mode((SCREENW, SCREENH), 0, 32) #display screen
clock = pygame.time.Clock()
#-------------------------------------------------------------------------------
def maketext(msg,fontsize, colour = ORANGE, font = FONT1):
mafont = pygame.font.Font(font, fontsize)
matext = mafont.render(msg, True, colour)
matext = matext.convert_alpha()
return matext
#-------------------------------------------------------------------------------
def print_info():
""""""
textcos = maketext(str(round(obj.rect.x, 2)) + " " + str(round(obj.rect.y, 2)), 30)
SCREEN.blit(textcos, (obj.rect.x, obj.rect.y + 30))
#-------------------------------------------------------------------------------
class object_factory(pygame.sprite.Sprite):
def __init__(self, imagelist, xpos, ypos, speedx = 0, speedy = 0, value = 0):
"""Constructor"""
pygame.sprite.Sprite.__init__(self)
self.name = ""
self.frame = 0
self.imagelist = imagelist
self.image = imagelist[self.frame]
self.mask = pygame.mask.from_surface(self.image) # pixelmask
self.rect = self.image.get_rect()
self.rect.x = xpos
self.rect.y = ypos
#self.speedx = speedx
#self.speedy = speedy
self.timer = 0
self.timerlimit = 10
#----------------------------------------------------------------------
#def move(self): # wallsprites, Herosprite, looptime
#self.rect.x += self.speedx
#self.rect.y += self.speedy
#----------------------------------------------------------------------
def update(self):
""""""
self.image = self.imagelist[self.frame]
if self.timer >= self.timerlimit:
self.frame += 1
if self.frame >= len(self.imagelist):
self.frame = 0
self.timer = 0
self.timer += 1
plat = pygame.image.load("plt0.png").convert_alpha()
star = pygame.image.load("gemp0.png").convert_alpha()
#box = pygame.image.load("crateB.png").convert_alpha()
platforms = pygame.sprite.Group()
boxes = pygame.sprite.Group()
rotcenx = SCREENW/2
rotceny = SCREENH/2
radius = 200
angle = radians(90) #pi/4 # starting angle 45 degrees
omega = radians(5) #Angular velocity
m = rotcenx + radius * cos(angle) #Starting position x
n = rotceny - radius * sin(angle) #Starting position y
for _ in itertools.repeat(None, 1):
madyax = SCREENW/2
madyay = SCREENH/2
araya = 200
konaya = radians(180) #pi/4 # starting angle 45 degrees
konika_pravegaya = radians(5) #Angular velocity
a = madyax + (araya * cos(konaya)) #Starting position x
b = madyay - (araya * sin(konaya)) #Startinh position y
plat = object_factory([plat], a, b)
plat.araya = araya
plat.konaya = konaya
plat.kp = konika_pravegaya
platforms.add(plat)
while True:
ms = clock.tick(FPS) # milliseconds passed since last frame
#looptime = milliseconds / 1000.0 # seconds passed since last frame
SCREEN.fill((BLACK))
pygame.draw.circle(SCREEN, BLUE, (SCREENW / 2, SCREENH / 2), 5)
##-----------------------------------------------------------
SCREEN.blit(star, (m, n)) # Draw current x,y
angle = angle + omega # New angle, we add angular velocity
m = m + radius * omega * cos(angle + pi / 2) # New x
n = n - radius * omega * sin(angle + pi / 2) # New y
##-----------------------------------------------------------
# show object anchored to center of rotation
pygame.draw.line(SCREEN, ORANGE, (rotcenx, rotceny), (m, n))
text = maketext(str(radius), 30)
SCREEN.blit(text, (m, n - 40))
text = maketext((str(round(m, 2)) + " " + str(round(n, 2))), 30)
SCREEN.blit(text, (m, n + 40)) # Draw current x,y
##------------------------------------------------------------------
for plat in platforms:
plat.konaya = plat.konaya + plat.kp
plat.rect.x = plat.rect.x + plat.araya * plat.kp * cos(plat.konaya + pi / 2)
plat.rect.y = plat.rect.y - plat.araya * plat.kp * sin(plat.konaya + pi / 2)
##------------------------------------------------------------------------
pygame.draw.line(SCREEN, ORANGE, (madyax, madyay), (plat.rect.x, plat.rect.y))
platforms.update()
platforms.draw(SCREEN)
pygame.event.pump()
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
pygame.display.update()
pygame.time.wait(100)
Why does the code work when used outside a class and NOT when in? I simply can't find what I have done wrong.
Please don't ask me to read any Google documents or search on the Internet as I am posting after doing so and NOT finding an answer to my question. I am NOT an expert in math and would only like to know a solution to this problem. Please help.
Link to video is below
http://youtu.be/0oRDX246aj8

Display a certain element in a list

Right now our code creates a grid starting at the top left and filling in rows and columns from left to right, row by row. Currently, there are a bunch of images it can pick from. It is set using a handful of IF statements that picks between shapes and rareshapes. What I am trying to figure out how to do is change the code so instead of it picking a random rareshape, I can decide what rareshape spawns. Still new to Python and finding a lot of little things that make sense to me from other languages don't work in Python so its throwing me off a little.
EDIT:
Here is the full code. Credit for the base code written by cactusbin and revised by Gareth Rees.
import pygame, random, time, sys
from pygame.locals import *
import itertools
import os
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
SHAPE_WIDTH = 64 # Width of each shape (pixels).
SHAPE_HEIGHT = 64 # Height of each shape (pixels).
PUZZLE_COLUMNS = 10 # Number of columns on the board.
PUZZLE_ROWS = 11 # Number of rows on the board.
MARGIN = 118 # Margin around the board (pixels).
WINDOW_WIDTH = PUZZLE_COLUMNS * SHAPE_WIDTH + 2 * MARGIN + 485
WINDOW_HEIGHT = PUZZLE_ROWS * SHAPE_HEIGHT + 2 * MARGIN - 150
FONT_SIZE = 60
TEXT_OFFSET = MARGIN + 950
# Map from number of matches to points scored.
MINIMUM_MATCH = 10
EXTRA_LENGTH_POINTS = .1
RANDOM_POINTS = .3
DELAY_PENALTY_SECONDS = 1
DELAY_PENALTY_POINTS = 0
FPS = 30
EXPLOSION_SPEED = 15 # In frames per second.
SPIN_SPEED = 15
REFILL_SPEED = 10 # In cells per second.
VERTICAL = False
class Cell(object):
"""
A cell on the board, with properties:
`image` -- a `Surface` object containing the sprite to draw here.
`offset` -- vertical offset in pixels for drawing this cell.
"""
def __init__(self, image):
self.offset = 0.0
self.image = image
def tick(self, dt):
self.offset = max(0.0, self.offset - dt * REFILL_SPEED)
class Board(object):
"""
A rectangular board of cells, with properties:
`w` -- width in cells.
`h` -- height in cells.
`size` -- total number of cells.
`board` -- list of cells.
`matches` -- list of matches, each being a list of exploding cells.
`refill` -- list of cells that are moving up to refill the board.
`score` -- score due to chain reactions.
"""
def __init__(self, width, height):
self.explosion = [pygame.image.load('images/explosion{}.png'.format(i))
for i in range(1, 7)]
self.spin = [pygame.image.load('images/powerframe{}.png'.format(i))
for i in range (1, 12)]
self.image_color = {}
self.shapes = []
self.rareshapes = []
colors = 'red blue yellow'
letters = 'acgtu'
for c in colors.split():
im = pygame.image.load('images/{}.png'.format(c))
self.shapes.append(im)
self.image_color[im] = c
for l in letters:
im = pygame.image.load('rareimages/{}{}.png'.format(c, l))
self.rareshapes.append(im)
self.image_color[im] = l
self.background = pygame.image.load("images/bg.png")
self.blank = pygame.image.load("images/blank.png")
self.x = pygame.image.load("images/x.png")
self.w = width
self.h = height
self.size = width * height
self.board = [Cell(self.blank) for _ in range(self.size)]
self.matches = []
self.refill = []
self.score = 0.0
self.spin_time = 15
def randomize(self):
"""
Replace the entire board with fresh shapes.
"""
rare_shapes = [1, 9, 23, 27, 40, 42, 50, 56, 70, 81, 90]
for i in range(self.size):
if i in rare_shapes:
self.board[i] = Cell(random.choice(self.rareshapes))
else:
self.board[i] = Cell(random.choice(self.shapes))
def pos(self, i, j):
"""
Return the index of the cell at position (i, j).
"""
assert(0 <= i < self.w)
assert(0 <= j < self.h)
return j * self.w + i
def busy(self):
"""
Return `True` if the board is busy animating an explosion or a
refill and so no further swaps should be permitted.
"""
return self.refill or self.matches
def tick(self, dt):
"""
Advance the board by `dt` seconds: move rising blocks (if
any); otherwise animate explosions for the matches (if any);
otherwise check for matches.
"""
if self.refill:
for c in self.refill:
c.tick(dt)
self.refill = [c for c in self.refill if c.offset > 0]
if self.refill:
return
elif self.matches:
self.explosion_time += dt
f = int(self.explosion_time * EXPLOSION_SPEED)
if f < len(self.explosion):
self.update_matches(self.explosion[f])
return
self.update_matches(self.blank)
self.refill = list(self.refill_columns())
self.explosion_time = 0
self.matches = self.find_matches()
def draw(self, display):
"""
Draw the board on the pygame surface `display`.
"""
display.blit(self.background, (0, 0))
for i, c in enumerate(self.board):
display.blit(c.image,
(MARGIN + SHAPE_WIDTH * (i % self.w),
MARGIN + SHAPE_HEIGHT * (i // self.w - c.offset) - 68))
display.blit(self.x, (995, 735))
display.blit(self.x, (1112, 735))
display.blit(self.x, (1228, 735))
def swap(self, cursor):
"""
Swap the two board cells covered by `cursor` and update the
matches.
"""
i = self.pos(*cursor)
b = self.board
b[i], b[i+1] = b[i+1], b[i]
self.matches = self.find_matches()
def find_matches(self):
"""
Search for matches (lines of cells with identical images) and
return a list of them, each match being represented as a list
of board positions.
"""
def lines():
for j in range(self.h):
yield range(j * self.w, (j + 1) * self.w)
for i in range(self.w):
yield range(i, self.size, self.w)
def key(i):
return self.image_color.get(self.board[i].image)
def matches():
for line in lines():
for _, group in itertools.groupby(line, key):
match = list(group)
if len(match) >= MINIMUM_MATCH:
yield match
self.score = self.score + 1
return list(matches())
def update_matches(self, image):
"""
Replace all the cells in any of the matches with `image`.
"""
for match in self.matches:
for position in match:
self.board[position].image = image
def refill_columns(self):
"""
Move cells downwards in columns to fill blank cells, and
create new cells as necessary so that each column is full. Set
appropriate offsets for the cells to animate into place.
"""
for i in range(self.w):
target = self.size - i - 1
for pos in range(target, -1, -self.w):
if self.board[pos].image != self.blank:
c = self.board[target]
c.image = self.board[pos].image
c.offset = (target - pos) // self.w
target -= self.w
yield c
offset = 1 + (target - pos) // self.w
for pos in range(target, -1, -self.w):
c = self.board[pos]
c.image = random.choice(self.shapes)
c.offset = offset
yield c
class Game(object):
"""
The state of the game, with properties:
`clock` -- the pygame clock.
`display` -- the window to draw into.
`font` -- a font for drawing the score.
`board` -- the board of cells.
`cursor` -- the current position of the (left half of) the cursor.
`score` -- the player's score.
`last_swap_ticks` --
`swap_time` -- time since last swap (in seconds).
"""
def __init__(self):
pygame.init()
pygame.display.set_caption("Nucleotide")
self.clock = pygame.time.Clock()
self.display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT),
DOUBLEBUF)
self.board = Board(PUZZLE_COLUMNS, PUZZLE_ROWS)
self.font = pygame.font.Font(None, FONT_SIZE)
def start(self):
"""
Start a new game with a random board.
"""
self.board.randomize()
self.cursor = [0, 0]
self.score = 0.0
self.swap_time = 125
def quit(self):
"""
Quit the game and exit the program.
"""
pygame.quit()
sys.exit()
def play(self):
"""
Play a game: repeatedly tick, draw and respond to input until
the QUIT event is received.
"""
self.start()
while True:
self.draw()
dt = min(self.clock.tick(FPS) / 1000, 1 / FPS)
self.swap_time -= dt
for event in pygame.event.get():
if event.type == KEYUP:
self.input(event.key)
elif event.type == QUIT:
self.quit()
elif self.swap_time == 0:
self.quit()
self.board.tick(dt)
def input(self, key):
"""
Respond to the player pressing `key`.
"""
if key == K_q:
self.quit()
elif key == K_RIGHT and self.cursor[0] < self.board.w - 2:
self.cursor[0] += 1
elif key == K_LEFT and self.cursor[0] > 0:
self.cursor[0] -= 1
elif key == K_DOWN and self.cursor[1] < self.board.h - 1:
self.cursor[1] += 1
elif key == K_UP and self.cursor[1] > 0:
self.cursor[1] -= 1
elif key == K_SPACE and not self.board.busy():
self.swap()
def swap(self):
"""
Swap the two cells under the cursor and update the player's score.
"""
self.board.swap(self.cursor)
def draw(self):
self.board.draw(self.display)
self.draw_score()
self.draw_time()
if VERTICAL == False:
self.draw_cursor()
elif VERTICAL == True:
self.draw_cursor2()
pygame.display.update()
def draw_time(self):
s = int(self.swap_time)
text = self.font.render(str(int(s/60)) + ":" + str(s%60).zfill(2),
True, BLACK)
self.display.blit(text, (TEXT_OFFSET, WINDOW_HEIGHT - 170))
def draw_score(self):
total_score = self.score
def draw_cursor(self):
topLeft = (MARGIN + self.cursor[0] * SHAPE_WIDTH,
MARGIN + self.cursor[1] * SHAPE_HEIGHT - 68)
topRight = (topLeft[0] + SHAPE_WIDTH * 2, topLeft[1])
bottomLeft = (topLeft[0], topLeft[1] + SHAPE_HEIGHT)
bottomRight = (topRight[0], topRight[1] + SHAPE_HEIGHT)
pygame.draw.lines(self.display, WHITE, True,
[topLeft, topRight, bottomRight, bottomLeft], 3)
if __name__ == '__main__':
Game().play()
If what you are asking for is a way to more easily specify at which rareshapecount intervals you should place a rare shape instead of a normal shape, the following approach is more readable:
def randomize(self):
"""
Replace the entire board with fresh shapes.
"""
# locations we want to place a rare shape
rare_shapes = [9, 23, 27]
for i in range(self.size):
if i in rare_shapes:
self.board[i] = Cell(random.choice(self.rareshapes))
else:
self.board[i] = Cell (random.choice(self.shapes))
Optionally, you could randomly populate rare_shapes if you don't feel like hardcoding the intervals each time, making for a more varied experience (i.e., if you're designing a game or something similar).
What you mean by "I can decide what rareshape spawns instead of it picking a random rareshape" is unclear to me. Would you care to give more explanations ? Like how you would tell the program which rareshape to use ?
In the meantime, here's a somewhat more pythonic version of your code:
def randomize(self):
"""
Replace the entire board with fresh shapes.
"""
specials = dict((x, self.rareshapes) for x in (9, 23, 27))
get_shape_source = lambda x: specials.get(x, self.shapes)
for i in xrange(min(self.size, 41)):
self.board[i] = Cell(random.choice(get_shape_source(i)))
Note that this would break if len(self.board) < min(self.size, 41) but well, that's still basically what your current code do.
edit: given your comment, the obvious way to explicitly choose which rareshape goes where is to explicitly associate images with spots. Now what's the best way to do so / the best place ton configure this really depends on your whole code or at least on more than what you posted. As a very simple and minimal exemple, you could just have this:
from collections import ordereddict
def load_images(self)
self.image_color = {}
self.shapes = []
self.rareshapes = ordereddict()
colors = 'red', 'blue', 'yellow'
letters = 'acgtu'
for c in colors:
im = pygame.image.load('images/{}.png'.format(c))
self.shapes.append(im)
self.image_color[im] = c
for l in letters:
im = pygame.image.load('rareimages/{}{}.png'.format(c, l))
self.rareshapes.[(c, l)] = im
self.image_color[im] = l
def randomize(self):
"""
Replace the entire board with fresh shapes.
"""
raremap = {
# spot index : rareshape
9: ('red', 'a')],
23: ('blue', 'u'),
27: ('yellow', 'g')
}
for i in xrange(self.size):
if i in raremap:
im = self.rareshapes[raremap[i]]
else:
im = random.choice(self.shapes)
self.board[i] = Cell(im)
But it will be just unmaintainable in the long run - too much hardcoded stuff, and too much knowledge leaking from one method to another. I don't know what 'self' is an instance of, but you should considered splitting the responsabilities so you have the invariant parts in one class and the "configration" (images to load, spots / rareshapes mapping etc) in another. Some design patterns that come to mind are TemplateMethod (where you have an abstract base class with the invariant parts and concrete subclasses implementing the "configuration" part), Builder, and of course Strategy (in your case the "Strategy" class would take care of the configuration).

Python NameError: name -- syntax error [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
I have a compiler error “not defined” although there is a definition
from gasp import *
GRID_SIZE = 30
MARGIN = GRID_SIZE
BACKGROUND_COLOR = color.BLACK # Colors we use
WALL_COLOR = (0.6 * 255, 0.9 * 255, 0.9 * 255)
# The shape of the maze. Each character
# represents a different type of object
# % - Wall
# . - Food
# o - Capsule
# G - Ghost
# P - Chomp
# Other characters are ignored
the_layout = [
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",
"%.....%.................%.....%",
"%o%%%.%.%%%.%%%%%%%.%%%.%.%%%o%",
"%.%.....%......%......%.....%.%",
"%...%%%.%.%%%%.%.%%%%.%.%%%...%",
"%%%.%...%.%.........%.%...%.%%%",
"%...%.%%%.%.%%% %%%.%.%%%.%...%",
"%.%%%.......%GG GG%.......%%%.%",
"%...%.%%%.%.%%%%%%%.%.%%%.%...%",
"%%%.%...%.%.........%.%...%.%%%",
"%...%%%.%.%%%%.%.%%%%.%.%%%...%",
"%.%.....%......%......%.....%.%",
"%o%%%.%.%%%.%%%%%%%.%%%.%.%%%o%",
"%.....%........P........%.....%",
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"]
class Immovable:
def is_a_wall(self):
return False
class Nothing(Immovable):
pass
class Maze:
def __init__(self):
self.have_window = False
self.game_over = False
self.set_layout(the_layout)
set_speed(20)
def set_layout(self, layout):
height = len(layout)
width = len(layout[0])
self.make_window(width, height)
self.make_map(width, height)
max_y = height - 1
for x in range( width ):
for y in range(height):
char = layout[max_y - y][x]
self.make_object((x, y), char)
def make_window(self, width, height):
grid_width = (width -1) * GRID_SIZE
grid_height = (height - 1) * GRID_SIZE
screen_width = 2 * MARGIN + grid_width
screen_height = 2 * MARGIN + grid_height
begin_graphics(screen_width, screen_height,"Chomp",BACKGROUND_COLOR)
def to_screen(self, point):
(x,y) = point
x = x * GRID_SIZE + MARGIN
y = y * GRID_SIZE + MARGIN
return(x,y)
def make_map(self, width, height):
self.width = width
self.height = height
self.map = []
for y in range(width):
new_row = []
for x in range(width):
new_row.append(Nothing())
self.map.append(new_row)
def make_object(self,point,charactor):
(x,y) = point
if charactor == "%":
self.map[y][x] = Wall(self,point)
def finished(self):
return self.game_over
def play(self):
update_when('next_tick')
def done(self):
end_graphics()
self.map = []
def object_at(self,point):
(x,y) = point
if y < 0 or y >= self.height:
return Nothing()
if x < 0 or x >= self.width:
return Nothing()
return self.map[y][x]
class Wall(Immovable):
def __init__(self, maze, point):
self.place = point # Store our position
self.screen_point = maze.to_screen(point)
self.maze = maze # Keep hold of Maze
self.draw()
def draw(self):
(screen_x, screen_y) = self.screen_point
dot_size = GRID_SIZE * 0.2
Circle(self.screen_point, dot_size,
color = WALL_COLOR, filled = 1)
(x, y) = self.place
neighbors = [ (x+1, y), (x-1, y)]
for neighbor in neighbors:
self.check_neighbor(neighbor)
def check_neighbor(self,neighbor):
maze = self.maze
object = maze.object_at(neighbor)
if object.is_a_wall():
here = self.screen_point
there = maze.to_screen(neighbor)
Line(here, there, color = WALL_COLOR,thickness = 2)
def is_a_wall(self):
return True
the_maze = Maze()
while not the_maze.finished():
the_maze.play()
the_maze.done()
I got this error..
Traceback (most recent call last): File "chomp.py", line 110, in
class Wall(Immovable): File "chomp.py", line 124, in Wall
for neighbor in neighbors: NameError: name '
neighbors' is not defined
I spent lot of time still can't find what's wrong, need some help
You never close the function call to Circle() two lines about line 122, that's probably it. You're probably missing an argument based on the trailing comma.
dot_size = GRID_SIZE * 0.2
Circle(self.screen_point, dot_size, # No closing parentheses
(x, y) = self.place
neighbors = [ (x+1, y), (x-1, y)]
for neighbor in neighbors:
self.check_neighbor(neighbor)
Circle(self.screen_point, dot_size,
missing something at the end of that line

Categories