Icebreaker Game python - python

I'm going to create a python game by using a modules called graphics.
I have created a board with ice and I'm confusing how to create the position for the player in the beginning.
link to the graphics modules:
http://mcsp.wartburg.edu/zelle/python/graphics.py
Here is my code:
from graphics import *
from random import *
column, row = 7, 10
WIN_W, WIN_H = 450, 315
WIN_SZ, GAP = 40, 5
COLORS = [ 'blue', 'white']
player = 'X'
win = None
ices = []
def draw_ice(x, y):
global ices
left = GAP + x* (WIN_SZ+GAP)
top = GAP + y* (WIN_SZ+GAP)
r = Rectangle(Point(left, top), Point(left+WIN_SZ, top+WIN_SZ))
ices[x][y].append(r)
bit = randint(1,1)
ices[x][y].append(bool(bit))
ices[x][y][0].setFill(COLORS[bit])
ices[x][y][0].draw(win)
def draw_ices():
for i in range(row):
ices.append([])
for j in range(column):
ices[i].append([])
draw_ice(i, j)
def MS1():
global win
win = GraphWin("Icebreaker", WIN_W, WIN_H)
draw_ices()
while True:
pt = win.getMouse()
x = int((pt.x - GAP)/(WIN_SZ + GAP))
y = int((pt.y - GAP)/(WIN_SZ + GAP))
print(str((pt.x, pt.y)) + ' --> ' + str((x, y)))
ices[x][y][1] = not ices[x][y][0]
ices[x][y][0].setFill(COLORS[ices[x][y][1]])
position in the beginningMS1()
let's say 'X' is the red circle and 'O' is the blue circle.

I don't know anything about the Icebreaker game but I'm hoping the additional logic I provided you below gives you enough to move forward:
from graphics import *
COLUMN, ROW = 7, 10
WIN_W, WIN_H = 455, 320
WIN_SZ, GAP = 40, 5
COLORS = ['blue', 'white']
CIRCLE, RECTANGLE, COLOR = range(3)
player = 'X'
ices = []
def draw_ice(x, y):
left = GAP + x * (WIN_SZ + GAP)
top = GAP + y * (WIN_SZ + GAP)
r = Rectangle(Point(left, top), Point(left + WIN_SZ, top + WIN_SZ))
c = Circle(r.getCenter(), WIN_SZ / 4)
bit = 1
c.setFill(COLORS[bit])
c.setOutline('white')
r.draw(win)
c.draw(win)
ices[x][y] = [c, r, bool(bit)]
def draw_ices():
for i in range(ROW):
ices.append([])
for j in range(COLUMN):
ices[i].append(None)
draw_ice(i, j)
def MS1():
draw_ices()
x_player = ices[0][3][CIRCLE] # X / Red Player
x_player.setFill('red')
o_player = ices[9][3][CIRCLE] # O / Red Player
o_player.setFill('blue')
while True:
pt = win.getMouse()
x = int((pt.x - GAP) / (WIN_SZ + GAP))
y = int((pt.y - GAP) / (WIN_SZ + GAP))
print((pt.x, pt.y), '-->', (x, y))
ices[x][y][COLOR] = not ices[x][y][COLOR]
ices[x][y][CIRCLE].setFill(COLORS[ices[x][y][COLOR]])
win = GraphWin("Icebreaker", WIN_W, WIN_H)
MS1()

Related

planets created from 1d perlin noise terrain look weird

i am trying to make planets using pyglet but they end up looking like stars result
here is my code
also i need a way to convert a batch to a sprite (to move it easily)
import pyglet
from pyglet import shapes
import opensimplex
import math
import time
brtd = 0
######## planets###########
class planetobj():
def __init__(self,seed=1234,age=68,position=(0,0),color=(0,1,0),name="planet",description=" 127.0.0.1 , home sweet home never will thy become infected with the virus that has a closedcure"):
self.seed = seed
self.age = age
self.position = position
self.color = color
self.name = name
self.description = description
def gplanet(self,size):
opensimplex.seed(self.seed)
done = 0
xc = 0
c = 0
self.terrain = []
start = opensimplex.noise2(x=0, y=self.age)
while (done == 0 or xc < 50) and not xc > 100 :
xc = xc + 1
c = c + size
value = opensimplex.noise2(x=xc, y=self.age)
self.terrain.append(value * size)
if xc > 50:
if math.floor(value * 100 ) == math.floor(start * 100):
self.done = 1
def mkplanet(self, x,y):
self.batch = pyglet.graphics.Batch()
corner1 = (x,y)
self.trias = []
counter = 0
cornerback = [0,0]
for i in self.terrain:
counter += 1
radi = (360 / len(self.terrain)) * counter
radi2 = (360 / len(self.terrain)) * ((counter + 1 ) % len(self.terrain))
theta = self.terrain[(counter +1 ) % len(self.terrain)]
corner3 = (x + math.sin(radi) * ( i ) ,math.cos(radi) * ( i ) + y )
corner2 = (x + math.sin(radi2) * ( theta ) ,math.cos(radi2) * ( theta ) + y )
self.trias.append(shapes.Triangle( x,y,corner2[0], corner2[1], corner3[0], corner3[1], color=(255, counter % 255, 255), batch=self.batch) )
############ basic game logic & rendering ###########
scr_X = 400
scr_Y = 300
window = pyglet.window.Window(scr_X,scr_Y)
samplebatch = pyglet.graphics.Batch()
earth = planetobj()
earth.gplanet(200)
planets = []
planets.append(earth)
earth.mkplanet( 50 ,50)
#window.event
def on_draw():
window.clear()
earth.batch.draw()
pyglet.app.run()
i tried changing the values that get divided by 'len(self.terrain)'
but i could not find out how to make the planets look round
EDIT
thank you kind commenter (and also the rest of stackoverflow)
now i made a working version feel free to use it
'''
import opensimplex
import math
import pyglet
from pyglet import shapes
pi = 3.1459
debug = 0
class planetobj():
def __init__(self,seed=1234,age=68,position=(0,0),color=(0,1,0),name="planet",description=" 127.0.0.1 , home sweet home never will thy become infected with the virus that has a closedcure"):
self.seed = seed
self.age = age
self.position = position
self.color = color
self.name = name
self.description = description
def gplanet(self,size):
self.batch = pyglet.graphics.Batch()
opensimplex.seed(self.seed)
done = 0
xc = 0
c = 0
self.terrain = []
start = opensimplex.noise2(x=0, y=self.age)
while (done == 0 or xc < 50) and not xc > 100 :
xc = xc + 1
c = c + size
value = opensimplex.noise2(x=xc, y=self.age)
self.terrain.append(value * 10 + size)
if xc > 36:
if math.floor(value * 100 ) == math.floor(start * 100):
self.done = 1
def mkplanet(self, x,y):
global debug
corner1 = (x,y)
self.trias = []
deltatheta = 360 / len(self.terrain)
for counter,i in enumerate(self.terrain):
theta1 = ((deltatheta * counter)/180) * 3.1459
theta2 = (deltatheta * (counter + 2)/180) * 3.1459
radius = self.terrain[counter]
print(str(theta1) + "," + str(theta2))
radius2 = self.terrain[(counter + 1 )% len(self.terrain)]
corner2 = (x + radius2 * math.cos(theta1), y + radius * math.sin(theta1))
corner3 = ( (x + radius2 * math.cos(theta2)), (y + radius2 * math.sin(theta2)))
self.trias.append(shapes.Triangle(x,y,corner2[0], corner2[1], corner3[0], corner3[1], color=(255, counter % 255, 255), batch=self.batch) )
if debug == 1:
self.trias.append(shapes.Circle( corner2[0], corner2[1], 2, color=(255, counter % 255, 40), batch=self.batch) )
self.trias.append(shapes.Circle( corner3[0], corner3[1], 2, color=(255,255, 255), batch=self.batch) )
############ basic game logic & rendering ###########
scr_X = 400
scr_Y = 300
window = pyglet.window.Window(scr_X,scr_Y)
samplebatch = pyglet.graphics.Batch()
earth = planetobj()
earth.gplanet(150)
earth.mkplanet( 250,150)
print(earth.batch)
earth.batch.draw
#window.event
def on_draw():
window.clear()
earth.batch.draw()
print("drawing")
pyglet.app.run()
'''
OK, I've corrected your trigonometry, but there are some other issues. The random values you get back from the noise generator are between -1 and 1. You are then multiplying that by the planet size, which gives you wild variations from wedge to wedge. What you want is to have a basic wedge size, which you use the noise to adjust bit by bit. Here, I'm saying that the noise should be 3% of the wedge size (size/30).
I didn't want to download opensimplex, so I've used a uniform random number generator. I'm also using matplotlib to plot the triangle, but see if this is closer to what you intended.
import math
import random
import numpy as np
import matplotlib.pyplot as plt
class planetobj():
def __init__(self,seed=1234,age=68,position=(0,0),color=(0,1,0),name="planet",description=""):
self.seed = seed
self.age = age
self.position = position
self.color = color
self.name = name
self.description = description
def gplanet(self,size):
done = 0
xc = 0
self.terrain = []
start = random.uniform(-1,1)
while (done == 0 or xc < 50) and not xc > 100 :
xc = xc + 1
value = random.uniform(-1,1)
self.terrain.append(size + value * size / 30)
if xc > 50 and math.floor(value * 100) == math.floor(start * 100):
done = 1
def mkplanet(self, x,y):
corner1 = (x,y)
self.trias = []
deltatheta = 360 / len(self.terrain)
for counter,i in enumerate(self.terrain):
theta1 = deltatheta * counter
theta2 = deltatheta * (counter + 1)
radius = self.terrain[counter]
corner2 = (x + radius * math.cos(theta1), y + radius * math.sin(theta1))
corner3 = (x + radius * math.cos(theta2), y + radius * math.sin(theta2))
# self.trias.append(shapes.Triangle( x, y, corner2[0], corner2[1], corner3[0], corner3[1], color=(255, counter % 255, 255), batch=self.batch) )
self.trias.append(( x, y, corner2[0], corner2[1], corner3[0], corner3[1], (1.0,(counter%255)/255,1.0) ))
earth = planetobj()
earth.gplanet(200)
earth.mkplanet(50 ,50)
print(earth.trias)
plt.figure()
plt.scatter( [48,48,52,52],[-50,50,-50,50] )
for t in earth.trias:
tri = np.array(t[:6]).reshape(3,2)
plt.gca().add_patch(plt.Polygon( tri, color=t[6] ))
plt.show()
Output:

How can I change the size of my python turtle window?

I am currently trying to draw a Mandelbrot set in python with turtle. However, my problem has nothing to do with the Mandelbrot. I can't change the size of my turtle window. How can I do that?
I tried to initialize a screen and set the screen size with the screensize method. Nothing changes if I do this.
This is my code for drawing the set. I pasted the whole code because I don't know what I did wrong that the screen size doesn't change.
from turtle import *
height = 360
width = 360
screen = Screen()
screen.screensize(width, height)
tu = Turtle()
tu.hideturtle()
tu.speed(0)
tu.penup()
def decreasePoint(n, start1, stop1, start2, stop2):
return ((n - start1) / (stop1 - start1)) * (stop2 - start2) + start2
for x in range(width):
for y in range(height):
a = decreasePoint(x, 0, width, -2, 2)
b = decreasePoint(y, 0, height, -2, 2)
ca = a
cb = b
n = 0
z = 0
while n < 100:
aa = a * a - b * b
bb = 2 * a * b
a = aa + ca
b = bb + cb
n += 1
if abs(a + b) > 16:
break
bright = 'pink'
if (n == 100):
bright = 'black'
tu.goto(x , y)
tu.pendown()
tu.dot(4, bright)
tu.penup()
done()
Instead of:
screen.screensize(width, height)
do:
screen.setup(width, height)
The screensize() method sets the amount of area the turtle can roam, but doesn't change the screen size (despite the name), just the scrollable area. Also, to simplify your code, speed it up and produce a more detailed result, I suggest the following rework:
from turtle import Screen, Turtle
WIDTH, HEIGHT = 360, 360
screen = Screen()
screen.setup(WIDTH + 4, HEIGHT + 8) # fudge factors due to window borders & title bar
screen.setworldcoordinates(0, 0, WIDTH, HEIGHT)
turtle = Turtle()
turtle.hideturtle()
turtle.penup()
def scalePoint(n, start1, stop1, start2, stop2):
return (n - start1) * (stop2 - start2) / (stop1 - start1) + start2
screen.tracer(False)
for x in range(WIDTH):
real = scalePoint(x, 0, WIDTH, -2, 2)
for y in range(HEIGHT):
imaginary = scalePoint(y, 0, HEIGHT, -2, 2)
c = complex(real, imaginary)
z = 0j
color = 'pink'
for _ in range(100):
if abs(z) >= 16.0:
break
z = z * z + c
else:
color = 'black'
turtle.goto(x, y)
turtle.dot(1, color)
screen.update()
screen.tracer(True)
screen.exitonclick()

Zelle graphics in Python: How to move two objects separately

In this program I am able to get the green object to move but not the other one. I commented 'PROBLEM' above an 'if' statement written under function pygame() where I believe the problem exists. Am I supposed to make an elif statement to get the other object to move? Break after if valid(r, c)? etc. Here is the code:
from graphics import *
from time import sleep
''''''
def main():
global win,msg
win = GraphWin("PYGAME", winW, winH)
msg = Text(Point(100, winH - off_field//2), "PYGAME")
msg.draw(win)
make_field()
button_Exit, button_Restart = create_buttons()
pygame()
win.getMouse()
win.close()
''''''
column, row = 12, 10
adjacent = ( ( -1, -1), (0, -1), (1, -1),
( -1, 0), (1, 0),
( -1, 1), (0, 1), (1, 1) )
square_size = 30 # Size of each square on the field
off_field = 100 # Display off the field
# field : main game variable; 'I' = ice, 'B': broken
field = [ [ 'I' for c in range (column)] for r in range (row) ]
# user: identifies whose turn it is to play (click)
user = 0 # How do I switch users?
# Initial users' positions: [r, c]; None later replaced by Circle
users = [ [ row//2, 0, None],
[ row//2, column-1, None] ]
winW, winH = column * square_size, row * square_size + off_field # 360, 400
win = None # main app window
msg = None # main information Text
button_Exit = None # exit button
button_Restart = None # restart button
# squares: grid of squares, initially white, later changed to blue:
squares = None
''''''
# pygame_reset(): resets positions and squares turn white
def pygame_reset():
global win, squares
for r in range(row):
for c in range(column):
squares[r][c].setFill('white')
users[0][:2] = [row//2, 0]
users[1][:2] = [row//2, 0]
# User 1 and 2 are repositioned
# make_field(): makes visual grid of squares
def make_field():
global win, squares
# Allocate memory space for Rectangle objects:
squares = [ [ None for c in range (column)] for r in range (row) ]
for r in range(row):
for c in range(column):
x, y = c * square_size, r * square_size
squares[r][c] = Rectangle(Point(x,y), Point(x + square_size, y + square_size) )
squares[r][c].draw(win)
users[0][2] = Circle(Point(square_size//2, square_size//2 + row //2 *square_size),
square_size//2-5)
users[0][2].setFill('green')
users[0][2].draw(win)
users[1][2] = Circle(Point(square_size*11.5, square_size//2 + row //2 *square_size),
square_size//2-5)
users[1][2].setFill('yellow')
users[1][2].draw(win)
# Reset user's positions and all squares to white:
pygame_reset()
# returns True if position (r, c) is adjacent to
# current user's position
# Recall: users = [ [ r, c, Circle],[ r, c, Circle] ]
def valid(r, c):
pr, pc = users[user][0:2]
for dc, dr in adjacent:
if pr + dr == r and pc + dc == c:
return True
return False
def button_template(win, x, y, w, h, txt):
r = Rectangle(Point(x, y), Point(x+w, y+h))
r.setFill("white")
r.draw(win)
t = Text(r.getCenter(), txt) # same as Point(x+w//2, y+h//2)
t.draw(win)
return [ r, t ]
def create_buttons():
global win, field, squares, msg
button_Exit = button_template(win, 260, winH - off_field//1.25, 60, 25, "Exit")
button_Restart = button_template(win, 260, winH - off_field//2.25, 60, 25, "Restart")
return (button_Exit, button_Restart)
def temporary_color(r, c):
global squares
color = squares[r][c].config['fill']
squares[r][c].setFill('red')
sleep(0.5)
squares[r][c].setFill(color)
def move_user(r, c):
global msg, user, users
pr, pc = users[user][0:2]
dx, dy = square_size * (c - pc), square_size * (r - pr)
users[user][2].move(dx, dy)
users[user][0:2] = [ r, c]
msg.setText("User moves in: " + str((r, c)))
def pygame():
global win, field, squares, msg
while True:
pt = win.getMouse()
if pt.x > 260 and pt.y > winH - off_field//1.25:
msg.setText("Exit")
break
if pt.x > 260 and pt.y > winH - off_field//2.25:
msg.setText("Restart")
break
if pt.y < row * square_size:
r, c = pt.y // square_size, pt.x // square_size
msg.setText(str((r, c)))
# PROBLEM - DO I USE 'break' SOMEWHERE HERE?
if valid(r, c):
move_user(r, c)
# Do I use elif? Break? What to do next?
else:
temporary_color(r, c)
msg.setText("Invalid move")
continue
if valid(r, c):
squares[r][c].setFill('orange')
field[r][c] = 'B'
else:
msg.setText("Not in field")
main()
You need a more sophisticated loop for taking turns. The loop has to keep accepting mouse input until a valid move is made, then switch users. Here's a slightly streamlined version of your program with such a loop:
from time import sleep
from graphics import *
COLUMNS, ROWS = 12, 10
ADJACENT = (
(-1, -1), (0, -1), (1, -1),
(-1, 0), (1, 0),
(-1, 1), (0, 1), (1, 1)
)
SQUARE_SIZE = 30 # Size of each square on the field
OFF_FIELD = 20 # Display off the field
WIN_W, WIN_H = COLUMNS * SQUARE_SIZE, ROWS * SQUARE_SIZE + OFF_FIELD
# pygame_reset(): resets positions and squares turn white
def pygame_reset():
for r in range(ROWS):
for c in range(COLUMNS):
squares[r][c].setFill('white')
# User 1 and 2 are repositioned
users[0][:2] = [ROWS // 2, 0]
users[1][:2] = [ROWS // 2, COLUMNS - 1]
# make_field(): makes visual grid of squares
def make_field():
for r in range(ROWS):
y = r * SQUARE_SIZE
for c in range(COLUMNS):
x = c * SQUARE_SIZE
squares[r][c] = Rectangle(Point(x, y), Point(x + SQUARE_SIZE, y + SQUARE_SIZE))
squares[r][c].draw(win)
users[0][2] = Circle(Point(SQUARE_SIZE//2, SQUARE_SIZE//2 + ROWS//2 * SQUARE_SIZE), SQUARE_SIZE//2 - 5)
users[0][2].setFill('green')
users[1][2] = Circle(Point(SQUARE_SIZE * 11.5, SQUARE_SIZE//2 + ROWS//2 * SQUARE_SIZE), SQUARE_SIZE//2 - 5)
users[1][2].setFill('yellow')
# Reset user's positions and all squares to white:
pygame_reset()
users[0][2].draw(win)
users[1][2].draw(win)
# returns True if position (r, c) is adjacent to
# current user's position
# Recall: users = [[r, c, Circle], [r, c, Circle]]
def valid(r, c):
pr, pc = users[user][:2]
for dc, dr in ADJACENT:
if pr + dr == r and pc + dc == c:
return True
return False
def temporary_color(r, c):
color = squares[r][c].config['fill']
squares[r][c].setFill('red')
sleep(0.5)
squares[r][c].setFill(color)
def move_user(r, c):
pr, pc = users[user][:2]
dx, dy = SQUARE_SIZE * (c - pc), SQUARE_SIZE * (r - pr)
users[user][2].move(dx, dy)
users[user][:2] = r, c
msg.setText("User {} moves to: {}".format(user, (r, c)))
squares[r][c].setFill('orange')
field[r][c] = 'B'
def pygame():
global user
while True:
finished_move = False
while not finished_move:
pt = win.getMouse()
if pt.y < ROWS * SQUARE_SIZE:
r, c = int(pt.y // SQUARE_SIZE), int(pt.x // SQUARE_SIZE)
if valid(r, c):
move_user(r, c)
finished_move = True
else:
temporary_color(r, c)
msg.setText("Invalid move for user {}".format(user))
else:
msg.setText("Not in field")
user = 1 - user # switch user
# field : main game variable; 'I' = ice, 'B': broken
field = [['I' for c in range(COLUMNS)] for r in range(ROWS)]
# squares: grid of squares, initially white, later changed to blue:
squares = [[None for c in range(COLUMNS)] for r in range(ROWS)]
# user: identifies whose turn it is to play (click)
user = 0 # How do I switch users?
# Initial users' positions: [r, c]; None later replaced by Circle
users = [
[ROWS // 2, 0, None],
[ROWS // 2, COLUMNS - 1, None]
]
win = GraphWin("PYGAME", WIN_W, WIN_H) # main app window
msg = Text(Point(WIN_W//2, WIN_H - OFF_FIELD//2), "PYGAME") # main information Text
msg.draw(win)
make_field()
pygame()
win.getMouse()
win.close()
Code-wise, you need to (re)read about the global statement and when it's used.

Python pygame not responding. Sierpinski triangle and problems with randint

The first problem that im getting is with my random numbers. every other time i try and run the program i get an error with a random number. The program worked and would make a sierpinski triangle every other time until i tried to add color into the equation now the display box pops up then everything freezes
import sys, pygame, random, math, array
####initializes pygame
pygame.init()
#####deffining all my functions
def verticiePos(verticies):
for i in range(2):
screen.set_at(verticies[i], (0,0,255))
def randV(verticies):
v = random.choice(verticies)
return v
def Show(delay):
pygame.display.flip()
pygame.time.delay(delay)
def randPoint(h,w):
yRand = random.randint(0,h-1)
#maxX = ((w - yRand) * 2)
xRand = random.randint(0, w-1)
return (xRand, yRand)
def mainFunc():
verticiePos(verticies)
randPoint(h,w)
def colors(point, maxRed, maxBlue, maxGreen, bv, gv):
howRed = (math.sqrt(point[0]**2 + point[1]**2) / maxRed) * 255
howRed = int(howRed)
howGreen = ((math.sqrt((point[0] - gv[0])**2 + (point[1] - gv[1])**2)) / maxGreen) * 255
howGreen = int(howGreen)
howBlue = ((math.sqrt((point[0] - bv[0])**2 + (point[1] - bv[1])**2)) / maxBlue) * 255
howBlue = int(howBlue)
return (howRed, howGreen, howBlue)
#####global variables
xRand = 0
yRand = 0
howRed = 0
howBlue = 0
howGreen = 0
#####Let the user choose the size of the display and setting screne
w = input("What do you want the width of the dcreen to be: ")
w = int(w)
h = input("What do you want the height of the dcreen to be: ")
h = int(h)
size = [w,h]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Project 1, Spierpinski triangle")
######setting up my verticies and all the functions i made
verticies = [(1,h - 1), (int(w/2), 1), (w-1,h-1)]
gv = verticies[1]
bv = verticies[2]
lengthOne = w
lengthTwo = math.sqrt(((w/2)**2) + (h**2))
if lengthOne >= lengthTwo:
maxRed = lengthOne
maxBlue = lengthOne
else:
maxRed = lengthTwo
maxBlue = lengthTwo
maxGreen = lengthTwo
############################################
mainFunc()
point = [yRand,xRand]
iteration = 0
delay = 2
#######the main loop thats plots points
for i in range(10000):
v = randV(verticies)
#colors(point, maxRed, maxBlue, maxGreen, bv, gv)
point = (int((point[0] + v[0])/2), int((point[1] + v[1])/2))
howRed = (math.sqrt(point[0]**2 + point[1]**2) / maxRed) * 200
howRed = int(howRed)
howGreen = ((math.sqrt((point[0] - gv[0])**2 + (point[1] - gv[1])**2)) / maxGreen) * 200
howGreen = int(howGreen)
howBlue = ((math.sqrt((point[0] - bv[0])**2 + (point[1] - bv[1])**2)) / maxBlue) * 200
howBlue = int(howBlue)
screen.set_at(point,(howRed,howGreen,howBlue))
Show(delay)
iteration = iteration + 1
#####the loop went really fast and was hard to see it coming into shape so i added this
if iteration > 2000:
delay = 0
#howRed,howGreen,howBlue
This is an updated version of the code that works i just need to clean it up now
Problem with random:
You use random.randint(yRand, maxX) in randPoint() and sometimes yRand > maxX
but random.randint(a, b) require a <= b
http://docs.python.org/2/library/random.html#random.randint
Problem with freeze ???
I have not problem with freeze but you have loop for i in range(50000): and it takes 1 minute to finish. At first run I thought that program freeze.
You have no event loop to get keyboard event and stop program with ESC.
Function color() always return (0,0,0) - it is black - so I don't see Sierpinski triangle.
#EDIT:
Sierpinski Triangle with recursion
import pygame
import math
class Sierpinski():
def __init__(self):
h = w = int(input("Triangle size: "))
level = int(input("Recursion level: "))
margin = 50 # add to size to make margin around triangle
# initializes pygame and setting screne
pygame.init()
self.screen = pygame.display.set_mode( (w + margin*2, h + margin*2) ) # self. - to make accessible in all function
pygame.display.set_caption("Sierpinski Triangle - Recursion")
# offset to move triangle to middle of window
const_height = math.sqrt(3)/2 # h = a * sqrt(3)/2 = a * const_height
invert_const_height = 1 - const_height
offset = int(h * invert_const_height / 2) # to move triange up - to middle
# main vertices A, B, C
a = (margin, h + margin - offset)
b = (w + margin, h + margin - offset)
c = (w/2 + margin, int(h * invert_const_height) + margin - offset)
self.screen.set_at(a, (255,255,255))
self.screen.set_at(b, (255,255,255))
self.screen.set_at(c, (255,255,255))
# recursion
self.drawTriangle(a, b, c, level)
# main loop (in game)
clock = pygame.time.Clock()
running = True
while running:
# keyboard & mouse event
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# move objects - nothing to do here
# draw object & redraw on screen
pygame.display.set_caption("Sierpinski Triangle - Recursion [FPS: %f]" % (clock.get_fps()))
pygame.display.update()
# frametime
clock.tick(25) # max 25 Frames Per Second
# end program
pygame.quit()
#-------------------------------------------------------
def drawTriangle(self, a, b, c, level):
if level == 0:
return
ab = self.middlePoint(a, b)
ac = self.middlePoint(a, c)
bc = self.middlePoint(b, c)
self.screen.set_at(ab, (255,255,255))
self.screen.set_at(bc, (255,255,255))
self.screen.set_at(ac, (255,255,255))
self.drawTriangle(a, ab, ac, level-1)
self.drawTriangle(b, ab, bc, level-1)
self.drawTriangle(c, bc, ac, level-1)
#-------------------------------------------------------
def middlePoint(self, a, b):
x = (a[0] + b[0])/2
y = (a[1] + b[1])/2
return (x,y)
#----------------------------------------------------------------------
if __name__ == '__main__':
Sierpinski()

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