#importing relevant libraries
from tkinter import *
from time import *
from math import *
from random import *

#making adjustable variable for the screen resolution most things will work with these but platform positions need to be adjusted manually
screenW=600
screenH=600
#setting up tkinter window
root = Tk()
screen = Canvas(root, width=screenW,height=screenH,background="black")
#using level dictionaries to change variables that change on a per level basis
levelDictionaries = [
  {'gravity':1,'friction':1,'name':"1:Getting Started",'bouncy':False},
  {'gravity':0.5,'friction':0.3,'name':"2:To the Moon",'bouncy':False},
  {'gravity':0.75,'friction':1,'name':"3:Bouncy Castle",'bouncy':True},
  {'gravity':1,'friction':1,'name':"You win! Press R to restart."}
]
#setting various values
def setInitialValues():
  global xPos,yPos,ySpeed,xSpeed,platXStart,platYStart,platXEnd,platYEnd,numPlats, onPlat, platform,friction,gravity,platforms,playerSize,platLength,platMid,coinSize,coins,levelNum,levelData,coinCollected,finishLength,gameSpeedMultiplier,easySpeed,fullSpeed,switchDelay,coinSign,coinsCollected,portal,bounceTick,screenM
  
  levelNum = 0
  levelData=levelDictionaries[levelNum]
  playerSize=20
  xPos = 0
  yPos = screenH-playerSize
  ySpeed = 0
  xSpeed = 0
  platXStart=[0,240,420,80,320,0,180,80]
  platYStart=[600,520,480,420,340,280,260,180]
  platXEnd=[600,280,480,200,500,80,240,160]
  platYEnd=[600,540,500,440,360,300,280,200]
  numPlats=len(platXStart)
  onPlat=True
  platform=[]
  friction = 1
  gravity = 1
  platforms=[]
  coins=[]
  platLength=[]
  coinSize=10
  platMid=[]
  coinCollected=[]
  finishLength=0
  gameSpeedMulitplier=1
  easySpeed=False
  fullSpeed=True
  switchDelay=0
  coinSign=[]
  finishPlatform=0
  coinsCollected=0
  portal=[]
  bounceTick=0
  screenM=screenW/2

def keyPressDetector(event):
  global xSpeed, ySpeed, xPos, yPos,onPlat,levelNum,levelData,easySpeed,fullSpeed,switchDelay,platforms,coins,coinSign
#only lets player jump when on platforms
  if onPlat==True:
    if event.keysym == 'w':
      ySpeed = -15
      onPlat = False
  if event.keysym == 'a':
    xSpeed = -10
  if event.keysym == 'd':
    xSpeed = 10
  #restart button
  if event.keysym == 'r':
    for i in range (numPlats):
      screen.delete(platforms[i],coins[i],coinSign[i]) 
    setInitialValues()
    for i in range (numPlats):
      platforms.append(0)
      coins.append(0)
      coinSign.append(0)
  #easy mode which toggles.
  if event.keysym == 'e':
    if easySpeed==True and switchDelay==0:
      easySpeed=False
      fullSpeed=True
      #switchDelay was used because it would instantly switch back to what it was before if it was not included
      switchDelay=1
    if fullSpeed==True and switchDelay==0:
      fullSpeed=False
      easySpeed=True
      switchDelay=1

    
    
#there is no collision with the sides of the platforms to make them a bit easier to jump onto
def onPlatform():
  global xPos,yPos,ySpeed,xSpeed,platXStart,platYStart,platXEnd,platYEnd,numPlats,onPlat,platforms,platform,finishLength,bounceTick
  for i in range(numPlats):
    platforms.append(0)
    #platform detection
    if(xPos > platXStart[i]-playerSize and xPos < platXEnd[i]) and yPos+playerSize< platYStart[i] and yPos+playerSize > platYStart[i]-15 and ySpeed>0:
        yPos=platYStart[i]-playerSize
        onPlat=True
        platform=[i]
        #used in level 3 to make sure that the player has fully landed before they jump again. if not included then the player will jump while still in the air due to how the detection works.
        bounceTick=1
    #used to make the player go down if they hit the bottom of the platform
    if(xPos > platXStart[i]-playerSize and xPos < platXEnd[i]) and yPos > platYEnd[i]-5 and yPos < platYEnd[i] + 11 and ySpeed<0:
      yPos = platYEnd[i]
      ySpeed = 1
    #detects if the player has fallen off
    if(xPos>platXEnd[i] or xPos<platXStart[i]-playerSize) and platform==[i] and yPos != screenH-playerSize:
      onPlat=False
    #does the same things but for the platform with the portal
    if(xPos > (screenM-finishLength)-playerSize and (xPos < screenM+finishLength)) and yPos+playerSize< 100 and yPos+playerSize > 85 and ySpeed>0:
      onPlat=True
      platform="Finish"
      yPos=100-playerSize
      bounceTick=1
    if(xPos > (screenM-finishLength)-playerSize and xPos < (screenM+finishLength)) and yPos > 120-5 and yPos < 120 + 11 and ySpeed<0:
      yPos = 120
      ySpeed = 1  
    if(xPos>(screenM+finishLength) or xPos<(screenM-finishLength)-playerSize) and platform=="Finish" and yPos != screenH-playerSize:
      onPlat=False


#fairly self-explanitory
def createPlatforms():
  global platforms,finishPlatform
  for i in range(numPlats):
    platforms.append(0)
    platforms[i]=screen.create_rectangle(platXStart[i],platYStart[i],platXEnd[i],platYEnd[i],fill="deepskyblue")
  finishPlatform=screen.create_rectangle(300-finishLength,100,300+finishLength,120,fill="orange")


#also fairly self explanitory
def createCoins():
  global platLength,platXEnd,platXStart,platMid,coins,platLength,platMid,coinCollected,coinSign
  for i in range(numPlats):
    platLength.append(0)
    platMid.append(0)
    coins.append(0)
    coinSign.append(0)
    coinCollected.append(False)
    platLength[i]=platXEnd[i]-platXStart[i]
    platMid[i]=platXStart[i]+platLength[i]/2
    if(coinCollected[i]==False):
      coins[i]=screen.create_oval(platMid[i]-coinSize,platYStart[i]-coinSize*2,platMid[i]+coinSize,platYStart[i],fill="gold")
      coinSign[i]=screen.create_text(platMid[i],platYStart[i]-coinSize,text="$",fill="darkgoldenrod")



def collectCoins():
 global coins,coinSign,coinCollected,finishLength,coinsCollected
 for i in range(numPlats):
   #detects if the player is touching the coin and collects it
   if(coinCollected[i]==False and xPos<platMid[i]+coinSize and xPos+playerSize>platMid[i]-coinSize and yPos<platYStart[i] and yPos>platYStart[i]-(coinSize*3)):
    finishLength += 10
    coinsCollected += 1
    coinCollected[i]=True



def createPortal():
  #draws the portal when all coins are collected
  global coinsCollected,portal,numPlats
  if coinsCollected==numPlats:
    portal=[screen.create_oval(280,40,320,100,fill="gray"),screen.create_oval(284,44,316,96,fill="midnightblue",outline=""),screen.create_oval(288,48,312,92,fill="mediumblue",outline=""),screen.create_oval(292,52,308,88,fill="blue",outline=""),screen.create_oval(296,56,304,84,fill="cornflowerblue",outline="")]

def resetValues():
  #used to reset values that are changed throughout the level
  global xPos,yPos,ySpeed,xSpeed,onPlat,coinsCollected,coinCollected,finishLength,numPlats
  xPos = 0
  yPos = screenH-playerSize
  ySpeed = 0
  xSpeed = 0
  onPlat=True
  finishLength=0
  coinsCollected=0
  coinCollected.clear()
  for i in range(numPlats):
    coinCollected.append(0)




def nextLevel():
  #changes the level when
  global levelNum,levelDictionaries,levelData
  if coinsCollected==numPlats and (xPos > (screenM-20)-playerSize and xPos < (screenM+20)) and yPos+playerSize < 101 and yPos+playerSize > 59:
  #does not change level if on level 4. 
    if levelNum != 3:
      levelNum += 1
    #loads data for next level
    levelData = levelDictionaries[levelNum]
    resetValues()
    
#shows the title of the level
def levelText():  
  global title
  title=screen.create_text(0,20,text=levelData.get('name'),fill="white",anchor=W,font=("FreeMono",25))


#various miscellanious functions that mostly pertain to movement
def miscFunc():
  global xPos,yPos,ySpeed,xSpeed,numPlats,onPlat,platforms,numPlats,switchDelay,portal,finishPlatform,bounceTick,gameSpeedMultiplier,coins,coinSign
  #used to make sure that the bouncing works properly
  if levelNum==2 and onPlat==True:
    if bounceTick == 1:
      bounceTick=0
    else:
      ySpeed = -15
      onPlat=False
  #used to make difficulty switching work
  if switchDelay == 1: 
    switchDelay -= 1
  #used to keep players on a platform
  if onPlat==True:
    ySpeed = 0
  #gravity
  else:
    ySpeed += levelData.get('gravity')
  #friction
  if xSpeed > 0:
    xSpeed -= levelData.get('friction')
    if xSpeed < levelData.get('friction'):
      xSpeed = 0
  if xSpeed < 0:
    xSpeed += levelData.get('friction')
    if xSpeed*(-1) < levelData.get('friction'):
      xSpeed = 0
  #used to make the player loop around the edges of the screen
  if xPos>screenW:
    xPos=-playerSize+1
  if xPos<-playerSize:
    xPos=screenW-1
  #movement
  yPos = yPos + ySpeed
  xPos = xPos + xSpeed
  #terminal velocity
  if ySpeed > 10:
    ySpeed = 10
  #used for the win screen to make sure they do not fall through as the platform that is usually there is not created
  if yPos+playerSize > screenH:
    yPos = screenH-playerSize
  #difficulty switching
  if fullSpeed==True:
    gameSpeedMultiplier=1
  elif easySpeed==True:
    gameSpeedMultiplier=2



def runGame():
  global xPos,yPos,ySpeed,xSpeed,numPlats,onPlat,platforms,numPlats,switchDelay,portal,finishPlatform,bounceTick,gameSpeedMultiplier,levelNum
  setInitialValues()
  while True:
    #does not draw during the win screen.
    if levelNum != 3:
      createPlatforms()
      createCoins()
      collectCoins()
      createPortal()
      onPlatform()
    #functions
    levelText()
    nextLevel()
    miscFunc()
    #making the player out of different shades of green
    player=[screen.create_rectangle(xPos,yPos,xPos+playerSize,yPos+playerSize,fill="darkgreen",outline=""),screen.create_rectangle(xPos+3,yPos+3,xPos-3+playerSize,yPos-3+playerSize,fill="forestgreen",outline=""),screen.create_rectangle(xPos+6,yPos+6,xPos-6+playerSize,yPos-6+playerSize,fill="limegreen",outline=""),screen.create_rectangle(xPos+9,yPos+9,xPos-9+playerSize,yPos-9+playerSize,fill="lime",outline="")]
    screen.update()
    #sleep changes depending on difficulty allowing for more time to react
    sleep(gameSpeedMultiplier*0.03)
    #deleting things
    screen.delete(title,finishPlatform)
    for i in range(len(player)):
      screen.delete(player[i])
    for i in range(len(portal)):
      screen.delete(portal[i])
    for i in range(numPlats):
      screen.delete(platforms[i],coins[i],coinSign[i])

#other tkinter functions
root.after(1000, runGame)
screen.bind("<Key>",  keyPressDetector) 
screen.pack()
screen.focus_set() 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling