binary tree of 15 processes by C program - fork

How we can make a fork binary tree that gives 15 processes in C program? I tried to write the code but I have some difficulty with the 15 processes. Also, fork always confused me!
Also, For each process, we should print out its process id and the id of its parent.
this is my code:
((when I copy paste my code, I cannot post the question))
if you can help me with the right code, I would be more than happy
thank you

You need to keep forking. This'll spawn 15 processes for you using fork:
#include <stdlib.h>
#include <stdio.h>
int main() {
int returnPid;
int numForks = 0;
while (numForks++ < 15) {
if ((returnPid = fork()) == -1) {
perror("can't fork");
exit(1);
} else if (returnPid == 0) {
// Child process
printf("Child: returnedPid = % d, my pid = %d, parent pid = %d, fork count = %d \n", returnPid, getpid(), getppid(), numForks);
} else {
printf("Parent: returnedPid = %d, my pid = %d, parent pid = %d \n ", returnPid, getpid(), getppid(0));
exit(0);
}
}
exit(0);
}
Output:
Parent: returnedPid = 15622, my pid = 15621, parent pid = 13927
Child: returnedPid = 0, my pid = 15622, parent pid = 1, fork count = 1
Parent: returnedPid = 15623, my pid = 15622, parent pid = 1
Child: returnedPid = 0, my pid = 15623, parent pid = 1, fork count = 2
Parent: returnedPid = 15625, my pid = 15623, parent pid = 1
Child: returnedPid = 0, my pid = 15625, parent pid = 15623, fork count = 3
Parent: returnedPid = 15626, my pid = 15625, parent pid = 1
Child: returnedPid = 0, my pid = 15626, parent pid = 1, fork count = 4
Parent: returnedPid = 15627, my pid = 15626, parent pid = 1
Child: returnedPid = 0, my pid = 15627, parent pid = 15626, fork count = 5
Parent: returnedPid = 15628, my pid = 15627, parent pid = 1
Child: returnedPid = 0, my pid = 15628, parent pid = 1, fork count = 6
Parent: returnedPid = 15629, my pid = 15628, parent pid = 1
Child: returnedPid = 0, my pid = 15629, parent pid = 15628, fork count = 7
Parent: returnedPid = 15631, my pid = 15629, parent pid = 1
Child: returnedPid = 0, my pid = 15631, parent pid = 15629, fork count = 8
Parent: returnedPid = 15632, my pid = 15631, parent pid = 1
Child: returnedPid = 0, my pid = 15632, parent pid = 1, fork count = 9
Parent: returnedPid = 15634, my pid = 15632, parent pid = 1
Child: returnedPid = 0, my pid = 15634, parent pid = 15632, fork count = 10
Parent: returnedPid = 15635, my pid = 15634, parent pid = 1
Child: returnedPid = 0, my pid = 15635, parent pid = 15634, fork count = 11
Parent: returnedPid = 15636, my pid = 15635, parent pid = 1
Child: returnedPid = 0, my pid = 15636, parent pid = 15635, fork count = 12
Parent: returnedPid = 15637, my pid = 15636, parent pid = 1
Child: returnedPid = 0, my pid = 15637, parent pid = 15636, fork count = 13
Parent: returnedPid = 15638, my pid = 15637, parent pid = 1
Child: returnedPid = 0, my pid = 15638, parent pid = 15637, fork count = 14
Parent: returnedPid = 15639, my pid = 15638, parent pid = 1
Child: returnedPid = 0, my pid = 15639, parent pid = 15638, fork count = 15

Related

How Do I Make Enemies In My Game Shoot Missles randomnly?

So I'm trying to create space Invaders currently and i'm trying to make the aliens shoot at the player randomnly. I've made it so that one projectile or enemy missle is shot at the player, but I can't figure out how I can make this happen from random places where the aliens are located, and how I can make the enemy repeatedly shoot missles,as opposed to just once as it's doing right now. My code that i'm using is down below (variables related to the shooting of the enemy are enemMissleFire and enemymissles)....
import pygame
import sys
import time
#initialize pygame
pygame.init()
width = 800
height = 600
# set the size for the surface (screen)
screen = pygame.display.set_mode((width, height),pygame.FULLSCREEN)
width = screen.get_width()
height = screen.get_height()
print(width)
print(height)
# set the caption for the screen
pygame.display.set_caption("Space Invaders")
def checkCollision(missles, type, score):
for missle in missles:
collision = missle.collidelist((type))
if collision > -1:
type.pop(collision)
missles.remove(missle)
missle.move_ip(0,missleSpeed)
pygame.draw.rect(screen, WHITE, missle,0)
# define colours you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)
clock = pygame.time.Clock()
FPS = 60
s = 25
#load and scale images
smallInvaderImg = pygame.image.load("images/smallinvader.png")
smallInvaderImg = pygame.transform.scale(smallInvaderImg,(s,s))
medInvaderImg = pygame.image.load("images/crabinvader.png")
medInvaderImg = pygame.transform.scale(medInvaderImg, (s,s))
bigInvaderImg = pygame.image.load("images/biginvader.png")
bigInvaderImg = pygame.transform.scale(bigInvaderImg, (s,s))
shipImg = pygame.image.load("images/ship.png")
shipImg = pygame.transform.scale(shipImg, (60,60))
smallInvaders = []
medInvaders = []
bigInvaders = []
enemiesMap = ["sssssssssss",
"mmmmmmmmmmm",
"mmmmmmmmmmm",
"bbbbbbbbbbb"]
invadertype = [smallInvaders,medInvaders,bigInvaders]
dx = 1
dy = 0
x = 240
y = 0
gap = 10
for element in enemiesMap:
for char in element:
if char == "s":
smallInvaders.append(pygame.Rect(x,y,s,s))
elif char == "m":
medInvaders.append(pygame.Rect(x,y,s,s))
elif char == "b":
bigInvaders.append(pygame.Rect(x,y,s,s))
x += s + gap
y += s + gap
x = 240
score = 2
ship = pygame.Rect(width/2,525,60,60)
if ship.right == width:
ship.right = width
#missles
maxMissles = 3
missleSpeed = -6
missleWidth = 5
missleHeight = 30
enemmissleWidth = 5
enemmissleHeight = 25
missles = []
missleFired = False
lives = 3
playbutton = pygame.Rect(width/2,height/2,155,90)
playbutton.center = (width/2,height/2)
quitbutton = pygame.Rect(width/2,height/2,155,90)
quitbutton.center = (width/2,height/2+110)
playagn = pygame.Rect(width/2,height/2,155,90)
playagn.center = (width/2,height/2)
playword = pygame.font.SysFont("comicsanms", 35)
title = pygame.font.SysFont("comicsanms", 90)
quitword = pygame.font.SysFont("comicsanms",35)
endscreen = pygame.font.SysFont("comicsanms", 90)
playagaintext = pygame.font.SysFont("comicsanms", 35)
enemMissleFire = False
enemmislist = []
enemymissles = (pygame.Rect(ship.centerx,y,enemmissleWidth,enemmissleHeight))
invaderDirSwapped = False
screenControl = 0
main = True
while main:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
main = False
for element in smallInvaders:
element.move_ip(dx,dy)
for element in smallInvaders:
if element.right >= width or element.left <= 0:
dx *= -1
invaderDirSwapped = True
for element in medInvaders:
element.move_ip(dx,dy)
if not invaderDirSwapped:
for element in medInvaders:
if element.right >= width or element.left <= 0:
dx *= -1
invaderDirSwapped = True
for element in bigInvaders:
element.move_ip(dx,0)
if not invaderDirSwapped:
for element in bigInvaders:
if element.right >= width or element.left <=0:
dx *= -1
invaderDirSwapped = True
key_input = pygame.key.get_pressed()
if key_input[pygame.K_RIGHT] and ship.right < width:
ship.move_ip(4,0)
if key_input[pygame.K_LEFT] and ship.left > 0:
ship.move_ip(-4,0)
if key_input[pygame.K_SPACE] and not missleFired:
missleFired = True
missles.append(pygame.Rect(ship.centerx,ship.top,missleWidth,missleHeight))
if screenControl == 0:
screen.fill(BLACK)
texttitle = title.render("SPACE INVADERS", True, WHITE)
textrect = texttitle.get_rect()
textrect.center = (width/2, 100)
screen.blit(texttitle,textrect)
if playbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
screenControl = 1
pygame.draw.rect(screen,WHITE,(playbutton), 0)
if playbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE, (playbutton), 4)
if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
main = False
pygame.draw.rect(screen,WHITE,(quitbutton), 0)
if quitbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,quitbutton,4)
textplay = playword.render("PLAY", True, BLUE)
textrect2 = textplay.get_rect()
textrect2.center = (width/2,height/2)
screen.blit(textplay,textrect2)
textquit = quitword.render("QUIT",True,BLUE)
textrect3 = textquit.get_rect()
textrect3.center = (width/2,height/2+110)
screen.blit(textquit,textrect3)
if screenControl == 1:
screen.fill(BLACK)
if len(missles) > 0:
if missleFired and missles[-1].bottom < (ship.top - 120) and not key_input[pygame.K_SPACE]:
missleFired = False
if len(missles) == 0:
missleFired = False
if enemMissleFire:
enemymissles.colliderect(ship)
enemymissles.move_ip(0,-missleSpeed)
pygame.draw.rect(screen, WHITE, enemymissles,0)
for invader in smallInvaders:
screen.blit(smallInvaderImg, invader)
for invader in medInvaders:
screen.blit(medInvaderImg, invader)
for invader in bigInvaders:
screen.blit(bigInvaderImg, invader)
screen.blit(shipImg,ship)
#move and draw missles
checkCollision(missles,smallInvaders,score)
checkCollision(missles,medInvaders,score)
checkCollision(missles,bigInvaders,score)
if smallInvaders == [] and medInvaders == [] and bigInvaders == []:
screenControl = 2
if screenControl == 2:
screen.fill(BLACK)
if playagn.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
screenControl = 0
pygame.draw.rect(screen,WHITE,(playagn),0)
if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
main = False
pygame.draw.rect(screen,WHITE, (quitbutton),0)
if playagn.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,(playagn), 4)
if quitbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,(quitbutton),4)
textend = endscreen.render("YOU WON!", True, WHITE)
textrect4 = textend.get_rect()
textrect4.center = (width/2, 150)
screen.blit(textend,textrect4)
textplayagn = playagaintext.render("PLAY AGAIN", True, BLUE)
textrect5 = textplayagn.get_rect()
textrect5.center = (width/2,height/2)
screen.blit(textplayagn,textrect5)
textquit = quitword.render("QUIT",True,BLUE)
textrect3 = textquit.get_rect()
textrect3.center = (width/2,height/2+110)
screen.blit(textquit,textrect3)
pygame.display.update()
Regardless, I can't figure out how I can make it so that projectiles can be shot from random aliens, over the course of the player shooting, and so any help would be appreicated.
Import Random and Time
this will get the random and time functions built in
from random import randint as ran
import time
Get the Number
this will get the time between the previous shot and the next
t = ran(Min_Time,Max_Time)
Get The Countdown
this will count a second between numbers
time.sleep(1)
t -= 1
print(t)
Shot!
shoot
if t == 0:
print('shot!')
FINAL CODE (trumpet fanfare)
from random import randint as ran
import time
def randshot(Min_Time,Max_Time):
t = ran(Min_Time,Max_Time)
print(t)
while t:
time.sleep(1)
t -= 1
print(t)
if t == 0:
print('shot!')
while True:
randshot(5,10)
Hope this Helped!

Multiple function calls for parallel processing inside a loop

I wish to detect an image from my webcam and write the result whether it is moving left or right to a file. To increase the frame rate(because this project involves a lot more processing and might be run on a raspberry pi) I decided to do the file writing part through multiprocessing (which I am new to):
code:
function for multi-processing
def send_cmd(cv):
# ####EXECUTE LOGIC AND CREATE COMMAND###
# writing to file
# just a sample command// change as will
dictionary = {'left': 0, 'right': 0, 'stop': 0}
if cv[0] == 'left':
dictionary['right'] = 1
else:
dictionary['left'] = 1
cmd = '{"left":' + str(dictionary['left']) + ',"right":' + str(dictionary['left'
]) + ',"stop":' + str(dictionary['left']) + '}'
print("command written: " + cmd)
f = open('command.txt', 'w')
f.write(cmd)
f.close()
Main code:
while True:
try:
frame = cv.VideoCapture(0)
frame = imutils.resize(frame, width=400)
if W is None or H is None:
(H, W) = frame.shape[:2]
blob = cv.dnn.blobFromImage(cv.resize(frame, (300, 300)),
0.007843, (300, 300), 127.5)
net.setInput(blob)
detections = net.forward()
rects = []
for i in range(0, detections.shape[2]):
if detections[0, 0, i, 2] > args['confidence']:
box = detections[0, 0, i, 3:7] * np.array([W, H, W, H])
rects.append(box.astype('int'))
(startX, startY, endX, endY) = box.astype('int')
cv.rectangle(frame, (startX, startY), (endX, endY), (0,
0xFF, 0), 2)
objects = ct.update(rects)
for (objectID, centroid) in objects.items():
text = 'ID {}'.format(objectID)
cv.putText(
frame,
text,
(centroid[0] - 10, centroid[1] - 10),
cv.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 0xFF, 0),
2,
)
cv.circle(frame, (centroid[0], centroid[1]), 4, (0, 0xFF,
0), -1)
center = (centroid[0], centroid[1])
pts.appendleft(center)
for i in np.arange(1, len(pts)):
if pts[i - 1] is None or pts[i] is None:
continue
if counter >= 10 and i == 1 and pts[-1] is not None:
dX = pts[-1][0] - pts[i][0]
dY = pts[-1][1] - pts[i][1]
global dirX
global dirY
(dirX, dirY) = ('', '')
if np.abs(dX) > 20:
dirX = ('left' if np.sign(dX) == 1 else 'right')
if np.abs(dY) > 20:
dirY = ('up' if np.sign(dY) == 1 else 'down')
#tried multiprocessing with process method but to many process calls at the same time
order = multiprocessing.Process(target = send_cmd,args = ([dirX, dirY]))
order.start()
order.join()
# send_cmd(cv=[dirX, dirY], us=ultra_sonic)
if dirX != '' and dirY != '':
direction = '{}-{}'.format(dirY, dirX)
else:
direction = (dirX if dirX != '' else dirY)
thickness = int(np.sqrt(args['buffer'] / float(i + 1))
* 2.5)
cv.putText(
frame,
direction,
(10, 30),
cv.FONT_HERSHEY_SIMPLEX,
0.65,
(0, 0, 0xFF),
3,
)
cv.putText(
frame,
'dx: {}, dy: {}'.format(dX, dY),
(10, frame.shape[0] - 10),
cv.FONT_HERSHEY_SIMPLEX,
0.35,
(0, 0, 0xFF),
1,
)
cv.imshow('Frame', frame)
key = cv.waitKey(1) & 0xFF
counter += 1
Error:
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
Can someone guide me?

Join - Pig scripts

Iam new to Pig scripts. I need help in joining 'B' and 'E'. Below is my script.
A = LOAD ....
PAPS_1 = FILTER A BY (dataMap#'corr_id_' is NOT null);
B = FOREACH PAPS_1 GENERATE dataMap#'corr_id_' as id, dataMap#'response' as resp, status;
C = LOAD ..
D = FILTER C BY (dataMap#'corr_id_' is NOT null);
E = FOREACH D GENERATE dataMap#'corr_id_' as id, status;
I tried joining like this. But it doesn't work. I am getting null values. Please correct me.
F = JOIN B BY id, E BY id;
Values in B:
23456ac, 200, 0
3453da3, 200, 0
Values in C:
23456ac, 0
3453da3, 0
Values in E:
23456ac, 0
3453da3, 0
My output is:
NULL, 200, 0, NULL, 0
NULL, 200, 0, NULL, 0
Expected is:
23456ac, 200, 0, 23456ac, 0
3453da3, 200, 0, 3453da3, 0
Thanks In Advance

Queue operator for RxJS

Is there an operator in RxJS that would allow me to buffer items and let them out one by one whenever a signal observable fires? Sort of like bufferWhen, but instead of dumping the whole buffer on each signal it would dump a certain number per signal. It could even dump the number that gets emitted by the signal observable.
Input observable: >--a--b--c--d--|
Signal observable: >------1---1-1-|
Count in buffer: !--1--21-2-121-|
Output observable: >------a---b-c-|
Yes, you can use zip to do what you want:
const input = Rx.Observable.from(["a", "b", "c", "d", "e"]);
const signal = new Rx.Subject();
const output = Rx.Observable.zip(input, signal, (i, s) => i);
output.subscribe(value => console.log(value));
signal.next(1);
signal.next(1);
signal.next(1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs#5/bundles/Rx.min.js"></script>
In fact, zip is used as an example in this GitHub issue that pertains to buffering.
If you want to use the signal's emitted value to determine how many buffered values are to be released, you could do something like this:
const input = Rx.Observable.from(["a", "b", "c", "d", "e"]);
const signal = new Rx.Subject();
const output = Rx.Observable.zip(
input,
signal.concatMap(count => Rx.Observable.range(0, count)),
(i, s) => i
);
output.subscribe(value => console.log(value));
signal.next(1);
signal.next(2);
signal.next(1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs#5/bundles/Rx.min.js"></script>
window can be used to separate the timeline. And takeLast is used to hold the output.
let signal = Rx.Observable.interval(1000).take(4);
let input = Rx.Observable.interval(300).take(10).share();
let output = input
.do(value => console.log(`input = ${value}`))
.window(signal)
.do(() => console.log(`*** signal : end OLD and start NEW subObservable`))
.mergeMap(subObservable => {
return subObservable.takeLast(100);
})
.share()
output.subscribe(value => console.log(` output = ${value}`));
Rx.Observable.merge(input.mapTo(1), output.mapTo(-1))
.scan((count, diff) => {
return count + diff;
}, 0)
.subscribe(count => console.log(` count = ${count}`));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>
Result:
22:28:37.971 *** signal : end OLD and start NEW subObservable
22:28:38.289 input = 0
22:28:38.292 count = 1
22:28:38.575 input = 1
22:28:38.576 count = 2
22:28:38.914 input = 2
22:28:38.915 count = 3
<signal received>
22:28:38.977 output = 0
22:28:38.979 count = 2
22:28:38.980 output = 1
22:28:38.982 count = 1
22:28:38.984 output = 2
22:28:38.986 count = 0
22:28:38.988 *** signal : end OLD and start NEW subObservable
22:28:39.175 input = 3
22:28:39.176 count = 1
22:28:39.475 input = 4
22:28:39.478 count = 2
22:28:39.779 input = 5
22:28:39.780 count = 3
<signal received>
22:28:39.984 output = 3
22:28:39.985 count = 2
22:28:39.986 output = 4
22:28:39.988 count = 1
22:28:39.989 output = 5
22:28:39.990 count = 0
22:28:39.992 *** signal : end OLD and start NEW subObservable
22:28:40.075 input = 6
22:28:40.077 count = 1
22:28:40.377 input = 7
22:28:40.378 count = 2
22:28:40.678 input = 8
22:28:40.680 count = 3
22:28:40.987 input = 9
22:28:40.990 count = 4
<input completed>
22:28:40.992 output = 6
22:28:40.993 count = 3
22:28:40.995 output = 7
22:28:40.996 count = 2
22:28:40.998 output = 8
22:28:40.999 count = 1
22:28:41.006 output = 9
22:28:41.007 count = 0

Generating and displaying random platforms in pygame

So this is part of the code for my game, using pygame. I'm trying to generate random platforms (from 3 different options), store them in a list and then blit all platforms in the list to the screen. I am able to generate the platform shapes correctly but other than the first platform i'm unable to position them where i want them.
blue = (0, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
i = 0
c = 0
Done = True
globalplatpos = pygame.Surface([395, 30])
globalplat = globalplatpos.get_rect()
platform_dimensions = plattop, platleft, platw, plath = 0,0,0,0
def play():
#============GAME SETUP============
SIZE = WIDTH, HEIGHT = 800, 600
TITLE = "Duality"
SPEED = 10
JUMPHEIGHT = 300
JUMPCOUNT = 0
JUMPSPEED = 15
GRAVITY = 10
STANDING = 1
JUMPING = 0
globalplatpos.fill(red)
platform = globalplat
platform.bottom = HEIGHT
PLATFORM = []
PLATPOS = []
platstand = True
screen = pygame.display.set_mode(SIZE)
caption = pygame.display.set_caption(TITLE)
clock = pygame.time.Clock()
mainsprite = pygame.image.load("images\mainsprite.png")
mainchar = mainsprite.get_rect()
mainchar.left = 177.5
mainchar.bottom = 570
mirrsprite = pygame.image.load("images\mirrsprite.png")
mirrchar = mirrsprite.get_rect()
mirrchar.left = mainchar.left + 400
mirrchar.bottom = mainchar.bottom
#============GAME SETUP============
#============PLATFORM GENERATOR============
def platform_generator(platform):
global globalplat
global globalplatpos
global platform_dimensions
globalplat = platform.move(0,-60)
globalplatpos.fill(red)
lastplat = PLATFORM[len(PLATFORM) - 1]
platheight = lastplat.top
leftpos = pygame.Surface([131, 30])
leftplat = leftpos.get_rect()
centrepos = pygame.Surface([100, 30])
centreplat = centrepos.get_rect()
rightpos = pygame.Surface([131, 30])
rightplat = rightpos.get_rect()
plat_type = random.randrange(0,3)
if plat_type == 0:
globalplat = leftplat
globalplatpos = leftpos
platform_dimensions = int(globalplat.top + 290), 0, 131, 30
elif plat_type == 1:
globalplat = centreplat
globalplatpos = centrepos
platform_dimensions = int(globalplat.top + 290), 132, 100, 30
elif plat_type == 2:
globalplat = rightplat
globalplatpos = rightpos
platform_dimensions = int(globalplat.top + 290), 233, 131, 30
else:
pass
PLATFORM.append(globalplat)
PLATPOS.append(globalplatpos)
#============PLATFORM GENERATOR============
#============GAME LOOP============
Done = False
while not Done:
clock.tick(60)
fps = clock.get_fps()
print(fps)
platform = globalplat
platpos = globalplatpos
mirrchar.left = mainchar.left + 406
mirrchar.bottom = mainchar.bottom
def update():
screen = pygame.display.set_mode(SIZE)
screen.fill(blue)
screen.blit(mainsprite, mainchar)
screen.blit(mirrsprite, mirrchar)
listpos = 0
pos = PLATPOS[listpos]
platshape = pygame.Rect(platform_dimensions)
platform = pygame.draw.rect(screen, red, platshape, 0)
platpos = globalplatpos
PLATFORM.append(platform)
PLATPOS.append(platpos)
for form in PLATFORM:
pos = PLATPOS[listpos]
listpos += 1
screen.blit(pos, form)
divpos = pygame.Rect(395, 0, 10, HEIGHT)
divrect = pygame.draw.rect(screen, black, divpos, 0)
pygame.display.update()
global i
if i == 0:
globalplat.bottom = HEIGHT
i = 1
PLATFORM.append(globalplat)
PLATPOS.append(globalplatpos)
screen.blit(globalplatpos, globalplat)
elif i == 1 and len(PLATFORM) < 10:
platform_generator(platform)
plat1 = PLATFORM[0]
update()
elif plat1.top > HEIGHT:
plat1 = PLATFORM[0]
pos1 = PLATPOS[0]
del plat1
del pos1
else:
update()
if mainchar.left > 0: #MOVE LEFT
if pygame.key.get_pressed()[K_LEFT] or pygame.key.get_pressed()[K_a]:
mainchar.left -= SPEED
else:
mainchar.left = 0
if mainchar.right < 395: # MOVE RIGHT
if pygame.key.get_pressed()[K_RIGHT] or pygame.key.get_pressed()[K_d]:
mainchar.right += SPEED
else:
mainchar.right = 395
jump = pygame.key.get_pressed()[K_SPACE] or pygame.key.get_pressed()[K_UP]
platstand = mainchar.collidelist(PLATFORM)
for form in PLATFORM:
if mainchar.colliderect(form):
STANDING = 1
mainchar.bottom = form.top
if JUMPING == 0:
if mainchar.collidelist(PLATFORM) > -1:
STANDING = 1
if STANDING == 1:
if jump:
JUMPING = 1
if JUMPING == 1:
if JUMPCOUNT < JUMPHEIGHT/2:
mainchar.bottom -= JUMPSPEED
mirrchar.bottom -= JUMPSPEED
JUMPCOUNT += JUMPSPEED
elif JUMPCOUNT > JUMPHEIGHT/2 and JUMPCOUNT < JUMPHEIGHT * 0.75:
mainchar.bottom -= JUMPSPEED/2
mirrchar.bottom -= JUMPSPEED/2
JUMPCOUNT += JUMPSPEED
elif JUMPCOUNT > JUMPHEIGHT * 0.75 and JUMPCOUNT < JUMPHEIGHT:
mainchar.bottom -= JUMPSPEED/4
mirrchar.bottom -= JUMPSPEED/4
JUMPCOUNT += JUMPSPEED
else:
JUMPCOUNT = 0
JUMPING = 0
STANDING = 0
jump = False
if STANDING == 0:
mainchar.bottom += GRAVITY
mirrchar.bottom += GRAVITY
def gameover():
Done = True
if mainchar.top > HEIGHT:
gameover()
if pygame.key.get_pressed()[K_ESCAPE]:
escape()
for event in pygame.event.get():
if event.type == pygame.QUIT: Done = True
update()
#============GAME LOOP============
I can't run this example but I see one mistake in blit()
You use
screen.blit( position, surface )
but blit() expects
screen.blit( surface, position )
Read PyGame Documentation: pygame.Surface.blit()

Resources