```import pygame import random # ініціалізуємо Pygame pygame.init() # задаємо розміри вікна window_width = 800 window_height = 600 # створюємо вікно screen = pygame.display.set_mode((window_width, window_height)) # задаємо колір фону bg_color = (0, 0, 255) # Код для створення зображення гравця player_image = pygame.Surface((50, 50)) # створюємо поверхню з розміром 50x50 пікселів player_image.fill((255, 0, 0)) # заповнюємо поверхню червоним кольором # додаємо ще різноманітні функції для створення зображення гравця, наприклад, наклеювання картинки на поверхню або малювання штучними шляхом # Код для створення зображення монетки coin_image = pygame.Surface((20, 20)) # створюємо поверхню з розміром 20x20 пікселів coin_image.fill((255, 255, 0)) # заповнюємо поверхню жовтим кольором # додаємо ще різноманітні функції для створення зображення монетки, наприклад, наклеювання картинки на поверхню або малювання штучними шляхом # задаємо розміри персонажа player_width = 50 player_height = 50 # задаємо розміри монетки coin_width = 20 coin_height = 20 # задаємо початкову позицію персонажа player_x = window_width // 2 - player_width // 2 player_y = window_height - player_height # задаємо початкові координати монетки coin_x = random.randint(0, window_width - coin_width) coin_y = -coin_height # задаємо швидкість руху персонажа player_speed = 10 # задаємо швидкість руху монетки coin_speed = 5 # заводимо лічильник очків score = 0 # головний цикл гри while True: # обробка подій for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() # переміщення персонажа keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: player_x -= player_speed if keys[pygame.K_RIGHT]: player_x += player_speed # переміщення монетки coin_y += coin_speed if coin_y > window_height: coin_x = random.randint(0, window_width - coin_width) coin_y = -coin_height score += 1 # перевірка зіткнення персонажа з монеткою if player_x < coin_x + coin_width and player_x + player_width > coin_x and player_y < coin_y + coin_height and player_y + player_height > coin_y: coin_x = random.randint(0, window_width - coin_width) coin_y = -coin_height score += 1 # малювання екрану screen.fill(bg_color) screen.blit(player_image, (player_x, player_y)) screen.blit(coin_image, (coin_x, coin_y)) # в # виведення рахунку на екран font = pygame.font.SysFont("comicsansms", 30) text = font.render("Score: " + str(score), True, (255, 255, 255)) screen.blit(text, (10, 10)) # оновлення екрану pygame.display.update() # головний цикл гри while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # обробка натискання клавіш if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerX_change = -10 if event.key == pygame.K_RIGHT: playerX_change = 10 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerX_change = 0 # зміна координат персонажа залежно від натисканих клавіш playerX += playerX_change if playerX <= 0: playerX = 0 elif playerX >= 736: playerX = 736 # зміна координат монетки coinY += coinY_change if coinY > 600: coinY = 0 coinX = random.randint(0, 736) score += 1 # виведення персонажа та монетки на екран screen.blit(playerImg, (playerX, playerY)) screen.blit(coinImg, (coinX, coinY)) # виведення рахунку на екран font = pygame.font.SysFont("comicsansms", 30) text = font.render("Score: " + str(score), True, (255, 255, 255)) screen.blit(text, (10, 10)) # оновлення екрану pygame.display.update() # головний цикл гри while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # обробка натискання клав import pygame # Ініціалізація Pygame pygame.init() # Створення вікна screen = pygame.display.set_mode((800, 600)) # Завантаження зображень player_image = pygame.image.load('player.png') enemy_image = pygame.image.load('enemy.png') background_image = pygame.image.load('background.png') # Розмір зображень player_size = player_image.get_size() enemy_size = enemy_image.get_size() # Початкові координати гравця та ворогів player_x = 50 player_y = 50 enemy_x = 600 enemy_y = 50 # Швидкість руху гравця та ворогів player_speed = 5 enemy_speed = 3 # Головний цикл гри running = True while running: # Обробка подій for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Рух гравця keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: player_x -= player_speed if keys[pygame.K_RIGHT]: player_x += player_speed if keys[pygame.K_UP]: player_y -= player_speed if keys[pygame.K_DOWN]: player_y += player_speed # Рух ворогів if enemy_x < player_x: enemy_x += enemy_speed elif enemy_x > player_x: enemy_x -= enemy_speed if enemy_y < player_y: enemy_y += enemy_speed elif enemy_y > player_y: enemy_y -= enemy_speed # Обробка зіткнень гравця та ворогів player_rect = pygame.Rect(player_x, player_y, player_size[0], player_size[1]) enemy_rect = pygame.Rect(enemy_x, enemy_y, enemy_size[0], enemy_size[1]) if player_rect.colliderect(enemy_rect): running = False # Відображення зображень на екрані screen.blit(background_image, (0, 0)) screen.blit(player_image, (player_x, player_y)) screen.blit(enemy_image, (enemy_x, enemy_y)) # Оновлення екрану pygame.display.update() # Завершення Pygame pygame.quit() ```
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.
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)
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.
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
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
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
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
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)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
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.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |