Советы

Пишем игру Pac-Man на Python в 300 строк кода

Pygame is a game library written using the SDL library. SDL, the full name Simple DirectMedia Layer, was written by a big cow named Sam Lantinga. It is said that he wanted to let Loki (dedicated to porting Windows games to Linux) A great good guy company, unfortunately, has closed down, alas, good guys don’t live long…) More effective work has created this stuff.

SDL is written in C, but it can also be developed in C++. Of course, there are many other languages. Pygame is a library that uses it in Python. Pygame has been around for a long time, and many excellent programmers have joined them to make Pygame better and better.

development tools:

Python version: 3.6.4 Related modules: pygame module;

  • and some modules that come with Python.
  • Install Python and add to environment variables, pip installs the required related modules.

Game introduction:

The player controls the protagonist Pac-Man of the game by ↑↓←→ to eat all beans hidden in the maze, and cannot be caught by ghosts. If you can successfully eat all the beans in the maze and are not caught by the ghost, the game wins, otherwise the game fails.

Step1: Define the game sprite class

Пишем игру Pac-Man на Python в 300 строк кодаПишем игру Pac-Man на Python в 300 строк кода ③ Character class: The role category includes Pac-Man and ghosts. The movement of ghosts is controlled by the computer, and the movement of Pac-Man is controlled by the player. Obviously, they all need the ability to update the position of the character and change the direction of the character's movement. The source code is as follows:Пишем игру Pac-Man на Python в 300 строк кода

Step2: Design the game map

Пишем игру Pac-Man на Python в 300 строк кодаПишем игру Pac-Man на Python в 300 строк кода ③ Create a role:Пишем игру Pac-Man на Python в 300 строк кода ④ Create food:Пишем игру Pac-Man на Python в 300 строк кода

Step3: Design the main loop of the game

Пишем игру Pac-Man на Python в 300 строк кодаПишем игру Pac-Man на Python в 300 строк кода The startLevelGame function is used to start a certain level game, and its source code is as follows:Пишем игру Pac-Man на Python в 300 строк кода The showText function is used to display prompt text in the game interface when the game is over or level switching. Its source code is as follows:

Source code:

import os,sys
import sys
import pygame
import random
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
PURPLE = (255, 0, 255)
SKYBLUE = (0, 191, 255)
if getattr(sys, 'frozen', False): cur_path = sys._MEIPASS
else: cur_path = os.path.dirname(__file__)
BGMPATH = os.path.join(cur_path, 'resources/sounds/bg.mp3')
ICONPATH = os.path.join(cur_path,'resources/images/icon.png')
FONTPATH = os.path.join(cur_path,'resources/font/ALGER.TTF')
HEROPATH = os.path.join(cur_path,'resources/images/pacman.png')
BlinkyPATH = os.path.join(cur_path,'resources/images/Blinky.png')
ClydePATH = os.path.join(cur_path,'resources/images/Clyde.png')
InkyPATH = os.path.join(cur_path,'resources/images/Inky.png')
PinkyPATH = os.path.join(cur_path,'resources/images/Pinky.png')
NUMLEVELS = 1
class Wall(pygame.sprite.Sprite): def __init__(self, x, y, width, height, color, **kwargs): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([width, height]) self.image.fill(color) self.rect = self.image.get_rect() self.rect.left = x self.rect.top = y
class Food(pygame.sprite.Sprite): def __init__(self, x, y, width, height, color, bg_color, **kwargs): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([width, height]) self.image.fill(bg_color) self.image.set_colorkey(bg_color) pygame.draw.ellipse(self.image, color, [0, 0, width, height]) self.rect = self.image.get_rect() self.rect.left = x self.rect.top = y
class Player(pygame.sprite.Sprite): def __init__(self, x, y, role_image_path): pygame.sprite.Sprite.__init__(self) self.role_name = role_image_path.split('/')[-1].split('.')[0] self.base_image = pygame.image.load(role_image_path).convert() self.image = self.base_image.copy() self.rect = self.image.get_rect() self.rect.left = x self.rect.top = y self.prev_x = x self.prev_y = y self.base_speed = [30, 30] self.speed = [0, 0] self.is_move = False self.tracks = [] self.tracks_loc = [0, 0] def changeSpeed(self, direction): if direction[0] 0: self.image = self.base_image.copy() elif direction[1] 0: self.image = pygame.transform.rotate(self.base_image, -90) self.speed = [direction[0] * self.base_speed[0], direction[1] * self.base_speed[1]] return self.speed def update(self, wall_sprites, gate_sprites): if not self.is_move: return False x_prev = self.rect.left y_prev = self.rect.top self.rect.left += self.speed[0] self.rect.top += self.speed[1] is_collide = pygame.sprite.spritecollide(self, wall_sprites, False) if gate_sprites is not None: if not is_collide: is_collide = pygame.sprite.spritecollide(self, gate_sprites, False) if is_collide: self.rect.left = x_prev self.rect.top = y_prev return False return True def randomDirection(self): return random.choice([[-0.5, 0], [0.5, 0], [0, 0.5], [0, -0.5]])
class Level1(): def __init__(self): self.info = 'level1' def setupWalls(self, wall_color): self.wall_sprites = pygame.sprite.Group() wall_positions = [[0, 0, 6, 600], [0, 0, 600, 6], [0, 600, 606, 6], [600, 0, 6, 606], [300, 0, 6, 66], [60, 60, 186, 6], [360, 60, 186, 6], [60, 120, 66, 6], [60, 120, 6, 126], [180, 120, 246, 6], [300, 120, 6, 66], [480, 120, 66, 6], [540, 120, 6, 126], [120, 180, 126, 6], [120, 180, 6, 126], [360, 180, 126, 6], [480, 180, 6, 126], [180, 240, 6, 126], [180, 360, 246, 6], [420, 240, 6, 126], [240, 240, 42, 6], [324, 240, 42, 6], [240, 240, 6, 66], [240, 300, 126, 6], [360, 240, 6, 66], [0, 300, 66, 6], [540, 300, 66, 6], [60, 360, 66, 6], [60, 360, 6, 186], [480, 360, 66, 6], [540, 360, 6, 186], [120, 420, 366, 6], [120, 420, 6, 66], [480, 420, 6, 66], [180, 480, 246, 6], [300, 480, 6, 66], [120, 540, 126, 6], [360, 540, 126, 6]] for wall_position in wall_positions: wall = Wall(*wall_position, wall_color) self.wall_sprites.add(wall) return self.wall_sprites def setupGate(self, gate_color): self.gate_sprites = pygame.sprite.Group() self.gate_sprites.add(Wall(282, 242, 42, 2, gate_color)) return self.gate_sprites def setupPlayers(self, hero_image_path, ghost_images_path): self.hero_sprites = pygame.sprite.Group() self.ghost_sprites = pygame.sprite.Group() self.hero_sprites.add(Player(287, 439, hero_image_path)) for each in ghost_images_path: role_name = each.split('/')[-1].split('.')[0] if role_name == 'Blinky': player = Player(287, 199, each) player.is_move = True player.tracks = [[0, -0.5, 4], [0.5, 0, 9], [0, 0.5, 11], [0.5, 0, 3], [0, 0.5, 7], [-0.5, 0, 11], [0, 0.5, 3], [0.5, 0, 15], [0, -0.5, 15], [0.5, 0, 3], [0, -0.5, 11], [-0.5, 0, 3], [0, -0.5, 11], [-0.5, 0, 3], [0, -0.5, 3], [-0.5, 0, 7], [0, -0.5, 3], [0.5, 0, 15], [0, 0.5, 15], [-0.5, 0, 3], [0, 0.5, 3], [-0.5, 0, 3], [0, -0.5, 7], [-0.5, 0, 3], [0, 0.5, 7], [-0.5, 0, 11], [0, -0.5, 7], [0.5, 0, 5]] self.ghost_sprites.add(player) elif role_name == 'Clyde': player = Player(319, 259, each) player.is_move = True player.tracks = [[-1, 0, 2], [0, -0.5, 4], [0.5, 0, 5], [0, 0.5, 7], [-0.5, 0, 11], [0, -0.5, 7], [-0.5, 0, 3], [0, 0.5, 7], [-0.5, 0, 7], [0, 0.5, 15], [0.5, 0, 15], [0, -0.5, 3], [-0.5, 0, 11], [0, -0.5, 7], [0.5, 0, 3], [0, -0.5, 11], [0.5, 0, 9]] self.ghost_sprites.add(player) elif role_name == 'Inky': player = Player(255, 259, each) player.is_move = True player.tracks = [[1, 0, 2], [0, -0.5, 4], [0.5, 0, 10], [0, 0.5, 7], [0.5, 0, 3], [0, -0.5, 3], [0.5, 0, 3], [0, -0.5, 15], [-0.5, 0, 15], [0, 0.5, 3], [0.5, 0, 15], [0, 0.5, 11], [-0.5, 0, 3], [0, -0.5, 7], [-0.5, 0, 11], [0, 0.5, 3], [-0.5, 0, 11], [0, 0.5, 7], [-0.5, 0, 3], [0, -0.5, 3], [-0.5, 0, 3], [0, -0.5, 15], [0.5, 0, 15], [0, 0.5, 3], [-0.5, 0, 15], [0, 0.5, 11], [0.5, 0, 3], [0, -0.5, 11], [0.5, 0, 11], [0, 0.5, 3], [0.5, 0, 1]] self.ghost_sprites.add(player) elif role_name == 'Pinky': player = Player(287, 259, each) player.is_move = True player.tracks = [[0, -1, 4], [0.5, 0, 9], [0, 0.5, 11], [-0.5, 0, 23], [0, 0.5, 7], [0.5, 0, 3], [0, -0.5, 3], [0.5, 0, 19], [0, 0.5, 3], [0.5, 0, 3], [0, 0.5, 3], [0.5, 0, 3], [0, -0.5, 15], [-0.5, 0, 7], [0, 0.5, 3], [-0.5, 0, 19], [0, -0.5, 11], [0.5, 0, 9]] self.ghost_sprites.add(player) return self.hero_sprites, self.ghost_sprites def setupFood(self, food_color, bg_color): self.food_sprites = pygame.sprite.Group() for row in range(19): for col in range(19): if (row == 7 or row == 8) and (col == 8 or col == 9 or col == 10): continue else: food = Food(30*col+32, 30*row+32, 4, 4, food_color, bg_color) is_collide = pygame.sprite.spritecollide(food, self.wall_sprites, False) if is_collide: continue is_collide = pygame.sprite.spritecollide(food, self.hero_sprites, False) if is_collide: continue self.food_sprites.add(food) return self.food_sprites
def startLevelGame(level, screen, font): clock = pygame.time.Clock() SCORE = 0 wall_sprites = level.setupWalls(SKYBLUE) gate_sprites = level.setupGate(WHITE) hero_sprites, ghost_sprites = level.setupPlayers(HEROPATH, [BlinkyPATH, ClydePATH, InkyPATH, PinkyPATH]) food_sprites = level.setupFood(YELLOW, WHITE) is_clearance = False while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(-1) if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: for hero in hero_sprites: hero.changeSpeed([-1, 0]) hero.is_move = True elif event.key == pygame.K_RIGHT: for hero in hero_sprites: hero.changeSpeed([1, 0]) hero.is_move = True elif event.key == pygame.K_UP: for hero in hero_sprites: hero.changeSpeed([0, -1]) hero.is_move = True elif event.key == pygame.K_DOWN: for hero in hero_sprites: hero.changeSpeed([0, 1]) hero.is_move = True if event.type == pygame.KEYUP: if (event.key == pygame.K_LEFT) or (event.key == pygame.K_RIGHT) or (event.key == pygame.K_UP) or (event.key == pygame.K_DOWN): hero.is_move = False screen.fill(BLACK) for hero in hero_sprites: hero.update(wall_sprites, gate_sprites) hero_sprites.draw(screen) for hero in hero_sprites: food_eaten = pygame.sprite.spritecollide(hero, food_sprites, True) SCORE += len(food_eaten) wall_sprites.draw(screen) gate_sprites.draw(screen) food_sprites.draw(screen) for ghost in ghost_sprites: if ghost.tracks_loc[1]

Читайте также:  Большие языковые модели (LLM): что это такое и как они работают?

How To Code Pacman In Python Free Download

In this tutorial for pacman python code, you can learn on How To Code Pacman In Python, you can learn with the help of example given below.

Pac-Man scores points by eating dots in a maze. Unless you’ve recently consumed a power-up, in which case the ghosts are delicious.

We’ve steadily introduced additional features of Pygame Zero, as well as principles related to game writing, in this series.

The Pacman Using Python is an action-adventure maze-chase video game in which the player guides the titular character through a maze. The goal of the game is to consume all of the dots that have been put across the maze while avoiding the four colored ghosts.

The rules of Pacman On Python the player takes control of Pac-Man, who must consume all of the dots inside a maze while avoiding four different colored ghosts. Pac-Man can consume giant flashing dots called “Power Pellets” to temporarily turn the ghosts blue, allowing him to eat them for bonus points.

  • Pac-Man must consume all of the dots inside an enclosed maze while avoiding four colored ghosts. Pac-Man may devour ghosts for bonus points by eating giant flashing dots known as “Power Pellets.”
  • Move your ghost not just where PAC-MAN is, but where you predict PAC-MAN will be on his next turn, if at all possible!
Project Name: Pacman In Python Code
Abstract This Pacman In Python Code is a simple game developed in Python that aims to have some leisure time for the user.
Language/s Used: Python (GUI Based)
Python version (Recommended): 3.8 or 3.9
Type: Desktop Application
Developer: Source Code Hero
Updates: 0

Pacman In Python Code – Project Information

The Pacman In Python Code is a fully functional GUI (Graphical User Interface) system that covers all of the elements that IT students and computer-related courses will require for their college projects.

A Pacman Game In Python is a simple game with a simple concept. This is the first part of a two-part tutorial that will teach you how to use Pygame Zero to create arcade games.

We’ll also use some more complex programming principles to improve our games. We’ll put together the basics of the Pac-Man game in this first section, as well as explain the concept of adding more Python modules to our program.

Additionally, this system is quite useful, and the concept and logic of the project are simple to grasp. The source code is open source and free to use. Simply scroll down and click the download option.

The code given below is the full source code on How To Make Pacman In Python.

Main Function

The code given below is a python file for main.py

import pygame
from game import Game

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 576

def main():
# Initialize all imported pygame modules
pygame.init()
# Set the width and height of the screen [width, height]
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
# Set the current window caption
pygame.display.set_caption(«PACMAN»)
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# Create a game object
game = Game()
# ——— Main Program Loop ————
while not done:
# — Process events (keystrokes, mouse clicks, etc)
done = game.process_events()
# — Game logic should go here
game.run_logic()
# — Draw the current frame
game.display_frame(screen)
# — Limit to 30 frames per second
clock.tick(30)
#tkMessageBox.showinfo(«GAME OVER!»,»Final Score = «+(str)(GAME.score))
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()

if __name__ == '__main__':
main()

To learn more, download the given full source code below…

By the way, if you are new to python programming and you don’t have any idea what Python IDE to use, I have here a list of Best Python IDE for Windows, Linux, Mac OS for you. Additionally, I also have here How to Download and Install Latest Version of Python on Windows.

To start executing a Pacman In Python Code, make sure that you have installed Python in your computer.

Time needed: 5 minutes

These are the steps on how to run Pacman In Python Code

  • Download Source CodeПишем игру Pac-Man на Python в 300 строк кода
  • Extract FileПишем игру Pac-Man на Python в 300 строк кода
  • Open PyCharmПишем игру Pac-Man на Python в 300 строк кода
  • Run ProjectПишем игру Pac-Man на Python в 300 строк кода

Click Here To Download The Source Code!

This article is the way to enhance and develop our skills and logic ideas which is important in practicing the python programming language which is most well known and most usable programming language in many company.

If you have any questions or suggestions about Pacman In Python Code, please feel free to leave a comment below.

Пишем игру на Python — Журнал «Код» программирование без снобизма

Прежде чем мы начнём программировать что-то полезное на Python, давайте закодим что-нибудь интересное. Например, свою игру, где нужно не дать шарику упасть, типа Арканоида. Вы, скорее всего, играли в детстве во что-то подобное, поэтому освоиться будет просто.

Есть игровое поле — простой прямоугольник с твёрдыми границами. Когда шарик касается стенки или потолка, он отскакивает в другую сторону. Если он упадёт на пол — вы проиграли.

Чтобы этого не случилось, внизу вдоль пола летает платформа, а вы ей управляете с помощью стрелок. Ваша задача — подставлять платформу под шарик как можно дольше.

За каждое удачное спасение шарика вы получаете одно очко.

Чтобы реализовать такую логику игры, нужно предусмотреть такие сценарии поведения:

  • игра начинается;
  • шарик начинает двигаться;
  • если нажаты стрелки влево или вправо — двигаем платформу;
  • если шарик коснулся стенок, потолка или платформы — делаем отскок;
  • если шарик коснулся платформы — увеличиваем счёт на единицу;
  • если шарик упал на пол — выводим сообщение и заканчиваем игру.

Хитрость в том, что всё это происходит параллельно и независимо друг от друга. То есть пока шарик летает, мы вполне можем двигать платформу, а можем и оставить её на месте. И когда шарик отскакивает от стен, это тоже не мешает другим объектам двигаться и взаимодействовать между собой.

Получается, что нам нужно определить три класса — платформу, сам шарик и счёт, и определить, как они реагируют на действия друг друга. Поле нам самим определять не нужно — для этого есть уже готовая библиотека. А потом в этих классах мы пропишем методы — они как раз и будут отвечать за поведение наших объектов.

Весь кайф в том, что мы всё это задаём один раз, а потом объекты сами разбираются, как им реагировать друг на друга и что делать в разных ситуациях. Мы не прописываем жёстко весь алгоритм, а задаём правила игры — а для этого классы подходят просто идеально.

По коням, пишем на Python

Для этого проекта вам потребуется установить и запустить среду Python. Как это сделать — читайте в нашей статье.

Чтобы у нас появилась графика в игре, используем библиотеку Tkinter. Она входит в набор стандартных библиотек Python и позволяет рисовать простейшие объекты — линии, прямоугольники, круги и красить их в разные цвета. Такой простой Paint, только для Python.

Чтобы создать окно, где будет видна графика, используют класс Tk(). Он просто делает окно, но без содержимого. Чтобы появилось содержимое, создают холст — видимую часть окна. Именно на нём мы будем рисовать нашу игру. За холст отвечает класс Canvas(), поэтому нам нужно будет создать свой объект из этого класса и дальше уже работать с этим объектом.

Если мы принудительно не ограничим скорость платформы, то она будет перемещаться мгновенно, ведь компьютер считает очень быстро и моментально передвинет её к другому краю. Поэтому мы будем искусственно ограничивать время движения, а для этого нам понадобится модуль Time — он тоже стандартный.

Последнее, что нам глобально нужно, — задавать случайным образом начальное положение шарика и платформы, чтобы было интереснее играть. За это отвечает модуль Random — он помогает генерировать случайные числа и перемешивать данные.

Запишем всё это в виде кода на Python:

# подключаем графическую библиотеку
from tkinter import *
# подключаем модули, которые отвечают за время и случайные числа
import time
import random
# создаём новый объект — окно с игровым полем. В нашем случае переменная окна называется tk, и мы его сделали из класса Tk() — он есть в графической библиотеке
tk = Tk()
# делаем заголовок окна — Games с помощью свойства объекта title
tk.title('Game')
# запрещаем менять размеры окна, для этого используем свойство resizable
tk.resizable(0, 0)
# помещаем наше игровое окно выше остальных окон на компьютере, чтобы другие окна не могли его заслонить
tk.wm_attributes('-topmost', 1)
# создаём новый холст — 400 на 500 пикселей, где и будем рисовать игру
canvas = Canvas(tk, width=500, height=400, highlightthickness=0)
# говорим холсту, что у каждого видимого элемента будут свои отдельные координаты
canvas.pack()
# обновляем окно с холстом
tk.update()

Читайте также:  ТОП-10 книг по языку программирования С++ в 2023 году

Мы подключили все нужные библиотеки, сделали и настроили игровое поле. Теперь займёмся классами.

Начать бесплатно Пишем игру Pac-Man на Python в 300 строк кода Пишем игру Pac-Man на Python в 300 строк кода Пишем игру Pac-Man на Python в 300 строк кода Пишем игру Pac-Man на Python в 300 строк кода

Сначала проговорим словами, что нам нужно от шарика. Он должен уметь:

  • задавать своё начальное положение и направление движение;
  • понимать, когда он коснулся платформы;
  • рисовать сам себя и понимать, когда нужно отрисовать себя в новом положении (например, после отскока от стены).

Этого достаточно, чтобы шарик жил своей жизнью и умел взаимодействовать с окружающей средой. При этом нужно не забыть о том, что каждый класс должен содержать конструктор — код, который отвечает за создание нового объекта. Без этого сделать шарик не получится. Запишем это на Python: # Описываем класс Ball, который будет отвечать за шарик
class Ball:
# конструктор — он вызывается в момент создания нового объекта на основе этого класса
def __init__(self, canvas, paddle, score, color):
# задаём параметры объекта, которые нам передают в скобках в момент создания
self.canvas = canvas
self.paddle = paddle
self.score = score
# цвет нужен был для того, чтобы мы им закрасили весь шарик
# здесь появляется новое свойство id, в котором хранится внутреннее название шарика
# а ещё командой create_oval мы создаём круг радиусом 15 пикселей и закрашиваем нужным цветом
self.id = canvas.create_oval(10,10, 25, 25, fill=color)
# помещаем шарик в точку с координатами 245,100
self.canvas.move(self.id, 245, 100)
# задаём список возможных направлений для старта
starts = [-2, -1, 1, 2]
# перемешиваем его
random.shuffle(starts)
# выбираем первый из перемешанного — это будет вектор движения шарика
self.x = starts[0]
# в самом начале он всегда падает вниз, поэтому уменьшаем значение по оси y
self.y = -2
# шарик узнаёт свою высоту и ширину
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
# свойство, которое отвечает за то, достиг шарик дна или нет. Пока не достиг, значение будет False
self.hit_bottom = False
# обрабатываем касание платформы, для этого получаем 4 координаты шарика в переменной pos (левая верхняя и правая нижняя точки)
def hit_paddle(self, pos):
# получаем кординаты платформы через объект paddle (платформа)
paddle_pos = self.canvas.coords(self.paddle.id)
# если координаты касания совпадают с координатами платформы
if pos[2] >= paddle_pos[0] and pos[0] = paddle_pos[1] and pos[3] = paddle_pos[0] and pos[0] = paddle_pos[1] and pos[3]

Пишем игру Сапёр на Python

Написать игру Сапёр (Mines) на Python с использованием библиотеки Tkinter оказалось не сложно. В этой статье покажем все этапы создания этой игры, которая массово была представлена публике в Windows 95. Следует отметить, что в Windows 3.11 игра winmine уже была. Но кто теперь это вспомнит?

Создадим поле из кнопок 16х16=256 кнопок.

from tkinter import *
from random import choice
frm = []; btn = [] # Списки с фреймами и кнопками

tk = Tk()
tk.title('Achtung, Minen!')

for i in range(0, 16):
frm.append(Frame())
frm[i].pack(expand=YES, fill=BOTH)
for j in range(0, 16):
btn.append(Button(frm[i], text=' ',
font=('mono', 16, 'bold'),
width=2, height=1,))
btn[i*16+j].pack(side=LEFT, expand=NO, fill=Y)

mainloop()

Кнопки размещаются в 16 горизонтальных фреймах. Список btn состоит из 256 кнопок.

Создадим список playArea — игровое поле и переменную счётчик ходов — nMoves. Игровое поле playArea содержит 256 элементов (целые числа). Где число -1 мина, числа 0 … 8 количество мин вокруг клетки. Будем ставить мины на поле после первого хода игрока, с тем, чтобы первый ход не закончился взрывом.

Каждый ход игрока выводит на нажатую кнопку соответствующее значение из списка playArea и деактивирует кнопку.

from tkinter import *
from random import choice
frm = []; btn = [] # Списки с фреймами и кнопками
playArea = []; nMoves = 0 # Игровое поле и счётчик ходов

def play(n): # n — номер нажатой кнопки
global nMoves
nMoves += 1
if nMoves == 1: # Если это первый ход игрока,
i = 0
while i 15:
if playArea[i-17] == -1: k += 1 # слева сверху
if i < 240: if playArea[i+15] == -1: k += 1 # слева снизу if i not in range(-1, 256, 16): if playArea[i+1] == -1: k += 1 # справа if i > 15:
if playArea[i-15] == -1: k += 1 # справа сверху
if i < 240: if playArea[i+17] == -1: k += 1 # справа снизу if i > 15:
if playArea[i-16] == -1: k += 1 # сверху
if i < 240: if playArea[i+16] == -1: k += 1 # снизу playArea[i] = k btn[n].config(text=playArea[n], state=DISABLED) # Отображаем игровую ситуацию tk = Tk() tk.title('Achtung, Minen!') for i in range(0, 16): # Размещаем кнопки frm.append(Frame()) frm[i].pack(expand=YES, fill=BOTH) for j in range(0, 16): btn.append(Button(frm[i], text=' ', font=('mono', 16, 'bold'), width=2, height=1, command=lambda n=i*16+j: play(n))) btn[i*16+j].pack(side=LEFT, expand=NO, fill=Y) playArea.append(0) # Создаём элементы списка playArea mainloop()

С такой программой уже можно играть в сапёра, но нет, ставших нам уже привычными, некоторых мелочей:

Пишем игру Pac-Man на Python в 300 строк кода

  • Вместо «0» должна отображаться пустая кнопка с изменённым цветом.
  • Вместо «-1» необходимо вывести изображение мины.
  • Если мы нарвались на мину:
    • необходимо вывести на экран все мины и
    • необходимо вывести на экран «Game Over»
    • в дальнейшем не допустить вывод на экран сообщения «You win!»
  • Если игрок открыл все поля не занятые минами, вывести на экран сообщение «You win!»
  • Необходимо добавить возможность с помощью правой кнопки мыши помечать клетку под которой возможно скрывается мина.

from tkinter import *
from random import choice
frm = []; btn = [] # Списки с фреймами и кнопками
playArea = []; nMoves = 0 # Игровое поле и счётчик ходов

def play(n): # n — номер нажатой кнопки
global nMoves
nMoves += 1
if nMoves == 1: # Если это первый ход игрока,
i = 0
while i 15:
if playArea[i-17] == -1: k += 1 # слева сверху
if i < 240: if playArea[i+15] == -1: k += 1 # слева снизу if i not in range(-1, 256, 16): if playArea[i+1] == -1: k += 1 # справа if i > 15:
if playArea[i-15] == -1: k += 1 # справа сверху
if i < 240: if playArea[i+17] == -1: k += 1 # справа снизу if i > 15:
if playArea[i-16] == -1: k += 1 # сверху
if i < 240: if playArea[i+16] == -1: k += 1 # снизу playArea[i] = k btn[n].config(text=playArea[n], state=DISABLED) # Отображаем игровую ситуацию if playArea[n] == 0: btn[n].config(text=' ', bg='#ccb') elif playArea[n] == -1: if nMoves < (256 - 40): # Если игрок ещё не выиграл, то проиграл tk.title('Your game is over.') nMoves = 256 # Если проиграл, то уже не выиграет for i in range(0, 256): if playArea[i] == -1: btn[i].config(text='u2665') if nMoves == (256 - 40): # Если все клетки открыты, это победа tk.title('You win!') def marker(n): # помечаем клетку под которой возможно скрывается мина. btn[n].config(text='u2661') tk = Tk() tk.title('Achtung, Minen!') for i in range(0, 16): # Размещаем кнопки frm.append(Frame()) frm[i].pack(expand=YES, fill=BOTH) for j in range(0, 16): btn.append(Button(frm[i], text=' ', font=('mono', 16, 'bold'), width=2, height=1, command=lambda n=i*16+j: play(n))) btn[i*16+j].pack(side=LEFT, expand=NO, fill=Y) btn[i*16+j].bind('', lambda event, n=i*16+j: marker(n)) playArea.append(0) # Создаём элементы списка playArea mainloop() Пишем игру Pac-Man на Python в 300 строк кода

Добавим кнопку «New game» и взрывы мин в случае поражения.

Make Pacman Game In Python With Code

Last updated June 8, 2023 by Jarvis Silva

Today in this tutorial we will make pacman game in python, pacman is one of the most popular games, I used to play this game when I was a kid, It is very simple game you can still play this game if you have Google play games it comes preinstalled on it.

If you don’t have much knowledge on python game development then it is going to be difficult for you but don’t worry I will provide you with the python code and explain you how the code works.

To create this pacman game in python, I will use the freegames python library. It has a collection of free python games, you can use this module to create games in python.

Now let’s see step by step how to make pacman game in python. I will provide you with the python code for pacman game, so read till the end.

If you have python installed, skip this. The first step is to install python, so go to the official python website and download the latest python version.

After download start the python installer and complete the setup it will install python on your computer.

Читайте также:  Руки прочь: автоматизация ручных задач с помощью GitHub Actions

Now you need to install freegames python library first create a new folder for this project and open a command prompt in the project location and paste the below command

pip install freegames

It will install the freegames python module in your project, so now create a python file and go to the next step

from random import choice
from turtle import *

from freegames import floor, vector

state = {'score': 0}
path = Turtle(visible=False)
writer = Turtle(visible=False)
aim = vector(5, 0)
pacman = vector(-40, -80)
ghosts = [
[vector(-180, 160), vector(5, 0)],
[vector(-180, -160), vector(0, 5)],
[vector(100, 160), vector(0, -5)],
[vector(100, -160), vector(-5, 0)],
]
# fmt: off
tiles = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0,
0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]
# fmt: on

def square(x, y):
«»»Draw square using path at (x, y).»»»
path.up()
path.goto(x, y)
path.down()
path.begin_fill()

for count in range(4):
path.forward(20)
path.left(90)

path.end_fill()

def offset(point):
«»»Return offset of point in tiles.»»»
x = (floor(point.x, 20) + 200) / 20
y = (180 — floor(point.y, 20)) / 20
index = int(x + y * 20)
return index

def valid(point):
«»»Return True if point is valid in tiles.»»»
index = offset(point)

if tiles[index] == 0:
return False

index = offset(point + 19)

if tiles[index] == 0:
return False

return point.x % 20 == 0 or point.y % 20 == 0

def world():
«»»Draw world using path.»»»
bgcolor('black')
path.color('blue')

for index in range(len(tiles)):
tile = tiles[index]

if tile > 0:
x = (index % 20) * 20 — 200
y = 180 — (index // 20) * 20
square(x, y)

if tile == 1:
path.up()
path.goto(x + 10, y + 10)
path.dot(2, 'white')

def move():
«»»Move pacman and all ghosts.»»»
writer.undo()
writer.write(state['score'])

clear()

if valid(pacman + aim):
pacman.move(aim)

index = offset(pacman)

if tiles[index] == 1:
tiles[index] = 2
state['score'] += 1
x = (index % 20) * 20 — 200
y = 180 — (index // 20) * 20
square(x, y)

up()
goto(pacman.x + 10, pacman.y + 10)
dot(20, 'yellow')

for point, course in ghosts:
if valid(point + course):
point.move(course)
else:
options = [
vector(5, 0),
vector(-5, 0),
vector(0, 5),
vector(0, -5),
]
plan = choice(options)
course.x = plan.x
course.y = plan.y

up()
goto(point.x + 10, point.y + 10)
dot(20, 'red')

update()

for point, course in ghosts:
if abs(pacman — point) < 20: return ontimer(move, 100) def change(x, y): """Change pacman aim if valid.""" if valid(pacman + vector(x, y)): aim.x = x aim.y = y setup(420, 420, 370, 0) hideturtle() tracer(False) writer.goto(160, 160) writer.color('white') writer.write(state['score']) listen() onkey(lambda: change(5, 0), 'Right') onkey(lambda: change(-5, 0), 'Left') onkey(lambda: change(0, 5), 'Up') onkey(lambda: change(0, -5), 'Down') world() move() done()

Above is the python pacman code, if you see in the code it uses many functions you may not know so let's see simple explaination of how this code works:

  • The code starts by importing necessary modules, including the choice function from the random module and the Turtle class from the turtle module.
  • It defines a dictionary named state to keep track of the game score and initializes it with a score of 0.
  • The game area is represented by a grid of tiles. The tiles list stores the configuration of the grid, where 0 represents walls, 1 represents pellets, and 2 represents eaten pellets.
  • Several helper functions are defined:
    • square(x, y): Draws a square at the given coordinates (x, y) using the Turtle graphics.
    • offset(point): Converts a point in the game world to an index in the tiles list.
    • valid(point): Checks if a given point is a valid position in the game world, considering walls and boundaries.
    • world(): Draws the game world by iterating through the tiles list and calling square() to draw each tile.
  • The main game loop is defined in the move() function. It updates the game state, moves the pacman and ghosts, checks for collisions, and updates the display. The loop is implemented using recursive calls to move() function with a delay of 100 milliseconds.
  • JS реализует простую мини-игру Pac-Man — Русские Блоги

    Я практиковал JS сегодня и написал небольшое демо Pac-Man

    HTML и CSS

    Сначала определитеdiv, Используется для хранения некоторых элементов Pac-Man, мы добавляем один к немуid=»game», А затем мы добавляем теги, которые мы хотим написать в этом div.

    Мы тутgameДобавлено 3 стены, а потом я напишуcssКод:

    #game { position: absolute; left: 50%; top: 50%; font-size: 0; transform: translateX(-50%) translateY(-50%);
    }
    .wall { display: inline-block; width: 50px; height: 50px; background-color: darkblue; border: 2px solid lightsteelblue; box-sizing: border-box;
    }

    cssЧастично используетсяabsoluteАбсолютное позиционирование, выделите 50% слева и сверху браузера, а затем передайтеtransformСвойство перемещается на 50% в обратном направлении, поэтому вам не нужно передавать настройкиgameШирина и высота перед использованиемmargin-leftсmargin-topПуть быть#gameСосредоточенный.

    Эффект браузера

    Тогда мы используемbrЧтобы обернуть этикетку, напишите вторую и третью строки:

    Положите золотые монеты и Pac-ManCSSСоставить

    .coin { display: inline-block; width: 50px; height: 50px; background-image: url(«./../images/coin.png»); background-position: center center; background-repeat: no-repeat;
    } .bg { display: inline-block; width: 50px; height: 50px; background-color: #000;
    } .pacman { display: inline-block; width: 50px; height: 50px; background-image: url(«./../images/pacman.png»);
    }

    Обнаружил, что дубликата кода много, его можно упростить,#gameВсе из следующегоdivМетки устанавливаются как элементы линейного блока, а затем устанавливаются ширина и высота:

    #game>div { display: inline-block; width: 50px; height: 50px;
    } .wall { background-color: darkblue; border: 2px solid lightsteelblue; box-sizing: border-box;
    } .coin { background-image: url(«./../images/coin.png»); background-position: center center; background-repeat: no-repeat;
    } .bg { background-color: #000;
    } .pacman { background-image: url(«./../images/pacman.png»);
    }

    Теперь давайте посмотрим на эффект в браузере:

    Таким образом, наша самая простая мини-карта Pac-Man готова, если вам нужно больше стен и золотых монет, вы можете добавитьdivЧтобы достичь, но этот метод очень неудобен и не прост для чтения. Ниже мы можем динамически создать нашу карту Pac-Man с помощью js.

    JS часть

    Итак, как создавать элементы в Pac-Man через JS, мы знаем, что у Pac-Man есть стены, Pac-Man, золотые монеты и монстры. Например, мы храним эти элементы в массиве,1Это стена,2Это золотая монета,3В качестве фона пустого пространства,4Pac-Man. (Здесь мы не привлекаем монстров)

    Сначала мы определяем массив:

    var game = [1,2,3,4];

    Тогда мы проходимforЦикл для отображения содержимого массива:

    var html = «»; var gameMap = document.getElementById(«game»); for(var i = 0; i

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *