Home > Backend Development > Python Tutorial > Develop simple games using Python

Develop simple games using Python

php中世界最好的语言
Release: 2018-04-09 11:33:58
Original
7873 people have browsed it

This time I will bring you the use of Python to develop simple small games. What are the precautions for using Python to develop small games. The following is a practical case, let's take a look.

Introduction

The python language has become popular recently. In addition to its useful role in the field of scientific computing, python is also used in games, backgrounds, etc. It also shines. This blog post will follow the formal project development process and teach you step by step to write a python game to feel the fun of it. The game developed this time is called alien invasion.

Install pygame and create a spaceship that can move left and right

Install pygame

My computer is windows 10, python3.6 , pygame download address: Portal

Please download the corresponding python version of pygame by yourself. Run the following command

$ pip install wheel
$ pip install pygame‑1.9.3‑cp36‑cp36m‑win_amd64.whl
Copy after login

Create a Pygame window and respond to user input

Create a new folder alien_invasion, And create a new alien_invasion.py file in the folder and enter the following code.

import sys
import pygame
def run_game():
  #initialize game and create a dispaly object
  pygame.init()
  screen = pygame.display.set_mode((1200,800))
  pygame.display.set_caption("Alien Invasion")
  # set backgroud color
  bg_color = (230,230,230)
  # game loop
  while True:
    # supervise keyboard and mouse item
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        sys.exit()
    # fill color
    screen.fill(bg_color)
    # visualiaze the window
    pygame.display.flip()
run_game()
Copy after login

Run the above code, we can get a window with a gray interface:

$ python alien_invasion.py

Create settings class

In order to easily create some new functions during the process of writing games, let’s write an additional settings module, which contains a Settings class. , to store all settings in one place. This makes it easier to modify the game's appearance later as the project grows. We first modify the display size and display color in alien_invasion.py. First, create a new python file settings.py in the alien_invasion folder, and add the following code to it:

class Settings(object):
  """docstring for Settings"""
  def init(self):
    # initialize setting of game
    # screen setting
    self.screen_width = 1200
    self.screen_height = 800
    self.bg_color = (230,230,230)
Copy after login

Then import the Settings class in alien_invasion.py, and use the relevant settings, modify it as follows:

import sys
import pygame
from settings import Settings
def run_game():
  #initialize game and create a dispaly object
  pygame.init()
  ai_settings = Settings()
  screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
  pygame.display.set_caption("Alien Invasion")
  # set backgroud color
  bg_color = (230,230,230)
  # game loop
  while True:
    # supervise keyboard and mouse item
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        sys.exit()
    # fill color
    screen.fill(ai_settings.bg_color)
    # visualiaze the window
    pygame.display.flip()
run_game()
Copy after login

Add spaceship image

Next, we need to add the spaceship to the game. To draw the player's ship on the screen, we will load an image and draw it using the Pygame() method blit(). Almost all types of image files can be used in games, but using bitmap (.bmp) files is easiest because Pygame loads bitmaps by default. Although other types of images can be loaded, additional libraries need to be installed. We recommend looking for images on a free stock photo site: Portal . We create a new folder called images in the main project folder (alien_invasion) and put the following bmp pictures into it.

Next, we create the ship class ship.py:

import pygame
class Ship():
  def init(self,screen):
    #initialize spaceship and its location
    self.screen = screen
    # load bmp image and get rectangle
    self.image = pygame.image.load('image/ship.bmp')
    self.rect = self.image.get_rect()
    self.screen_rect = screen.get_rect()
    #put spaceship on the bottom of window
    self.rect.centerx = self.screen_rect.centerx
    self.rect.bottom = self.screen_rect.bottom
  def blitme(self):
    #buld the spaceship at the specific location
    self.screen.blit(self.image,self.rect)
Copy after login

Finally we draw the ship on the screen, that is, call blitme in the alien_invasion.py file Method:

import sys
import pygame
from settings import Settings
from ship import Settings
def run_game():
  #initialize game and create a dispaly object
  pygame.init()
  ai_settings = Settings()
  screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
  ship = Ship(screen)
  pygame.display.set_caption("Alien Invasion")
  # set backgroud color
  bg_color = (230,230,230)
  # game loop
  while True:
    # supervise keyboard and mouse item
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        sys.exit()
    # fill color
    screen.fill(ai_settings.bg_color)
    ship.blitme()
    # visualiaze the window
    pygame.display.flip()
run_game()
Copy after login

Refactoring: module game_functions

In large projects, it is often necessary to refactor existing code before adding new code. The purpose of refactoring is to simplify the structure of the code and make it easier to extend. We will implement a game_functions module that will store a number of functions that allow the game Alien invasion to run. By creating the module game_functions, alien_invasion.py can be avoided from being too long, making its logic easier to understand.

Function check_events()

First we move the code that manages events to a function called check_events() function, the purpose is to isolate the event loop

import sys
import pygame
def check_events():
  #respond to keyboard and mouse item
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      sys.exit()
Copy after login

Then we modify the alien_invasion.py code, import the game_functions module, and replace the event loop with a call to the function check_events():

import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
def run_game():
  #initialize game and create a dispaly object
  pygame.init()
  ai_settings = Settings()
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to read and write txt files line by line in python

How to call mysql to update data in Python

The above is the detailed content of Develop simple games using Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template